id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_codereview.68227
this is a small part of my code that allows me to request a file through a load balancer, reading this XML file gives me the server's name (only node inside the XML Document) if the machine isn't inside the LAN then it won't be able to query the website. I give it a longer timeout to make sure that I don't get a ton of errors emailed to me if the network is laggy.Here is the XML file Structure.<?xml version=1.0 encoding=utf-8?><Server> JSODYAPP01T</Server>Here is the Code that retrieves the informationWebRequest request = WebRequest.Create(xmlLocation);request.Timeout = 90000;using (WebResponse response = request.GetResponse())using (XmlReader xmlReader = XmlReader.Create(response.GetResponseStream())){ while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Text) { serverName = xmlReader.Value.ToString(); serverName = serverName.Replace(\r, ); serverName = serverName.Replace(\n, ); serverName = serverName.Replace( , ); } }}is there a better way of doing this?
Parsing an XML File for a single word/phrase
c#;http
Linq to XML is your friendvar serverName = XDocument.Load(response.GetResponseStream()).Element(Server).Value;Your code will be easily broken if someone adds a node to the XML, and your code should be as flexible as possible. Never do such an assumption (It's gonna be the first node)Your method is blocking, consider making it asynchronous.using (var response = await request.GetResponseAsync()){}And by the way, C# got type inference, so why bother typing the type? Use var instead var request = WebRequest.Create(xmlLocation);
_softwareengineering.185718
I'm producing a binary distributable for my Java project. I'm releasing it in two ways:Maven CentralZipped distributable on Google codeMy project is licensed under the Apache 2.0 license. I use a small number of third-party parties, one of which is MIT licensed. I believe it's my obligation to make users of my project aware of the license contents, based on the following text from the license:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.How am I best to reference this within my source and my distributables? I'm currently thinking:My source files needn't reference anything. They just include my Apache 2.0 boilerplate notice.I add a LICENSE.txt file at the root of my project including the Apache 2.0 license text.For my zipped distributable, I need to also add something that indicates a component is MIT licensed. Perhaps a NOTICE file?For my Maven Central distribution, I needn't do anything as my artifact just declares its dependencies, but doesn't actually include them.Does this seem like a valid plan? If so, can anyone advise how to accomplish point 3.
How to include licenses for third-party Maven dependencies?
java;licensing;mit license;maven;apache license
null
_webapps.27113
If I copy text with a line break in it, like this...1st line2nd line...and then paste in into a Google Docs spreadsheet cell, then it pastes '2nd line' into the cell below. What are the easiest ways to avoid this?
Pasting text with line breaks into Google Spreadsheets creates multiple cells
google drive;google spreadsheets
Based on http://productforums.google.com/forum/#!category-topic/docs/formatting/-uEh3jguVu0 you can copy the info single cell by single cell and paste the information in edit mode of the receiving cell; i,e. double-click the cell first before you paste the single cell contents. Though this is hardly 'easy' so there may be a better answer out there...
_unix.237580
Summary: Crashkernel boots at 512MB address in RAM with kexec -e/-l but not with kexec -p - why?Embedded platform with Marvell Armada XP (MV78460) (ARMv7 with 4 cores) and 1GB of RAM. production kernel: customized Linux 3.4.91 rescue kernel: clean kernel.org-Linux (4.2.3) (I am aware that it uses device trees but that works fine by appending DTB to zImage) in user-space, I am using the latest kexec-tools (2.0.10)History: Using kexec -l (with ramdisk and command line params from 3.4.91-kernel, and --atags) and kexec -e, the rescue kernel boots just fine and seems to place itself in the beginning of RAM (according to /proc/iomem) regardless of what is being set via --mem-min and --mem-max. When reserving space in RAM using the boot-option crashkernel, I have to use a high memory address because otherwise it tells me the requested area is already in use. So we set crashkernel=128M@512M. The kernel does not boot with kexec -p.Current status: I understand that relocatable kernels (CONFIG_AUTO_ZRELADDR=y) must reside within the top 128MB which is not possible for us. So I have worked around the standard kernel configuration and forced CONFIG_ARM_PATCH_PHYS_VIRT to no and CONFIG_PHYS_OFFSET to 0x20000000. I had to add a Makefile.boot for the machine where I set zreladdr-y := 0x20008000, params_phys-y := 0x20000100, initrd_phys-y := 0x20800000.Now the kernel still boots fine using kexec -l and kexec -e and according to --mem-min. I can see it is placed at 512MB. However, configuring it with -p and causing a panic, the console says Loading crashdump kernel... Bye! and remains silent forever.All files and everything is only located in RAM.What could I be doing wrong? Should I worry about the decompression errors (even in the good case)?From dmesg:Reserving 128MB of memory at 512MB for crashkernel (System RAM: 760MB)root@host:~# cat /proc/iomem00000000-3bff9fff : System RAM 00008000-00724f43 : Kernel code 0076e000-0087553f : Kernel data 20000000-27ffffff : Crash kernel(some RAM at the end is reserved for persistent storage, that's why it doesn't add up to 1GB)Successful case:root@host:~# kexec -l -t zImage --command-line=console=ttyS0,38400 earlyprintk=ttyS0 root=/dev/ram rdinit=/sbin/init rw irqpoll maxcpus=1 reset_devices --atags --initrd=./initramfs.cpio.gz -d --mem-min=0x20000000 --mem-max=0x28000000 ./zImage_fixed_addrTry gzip decompression.Try LZMA decompression.lzma_decompress_file: read on ./zImage_fixed_addr of 65536 bytes failedkernel: 0xb6c06008 kernel_size: 0x3db659kexec_load: entry = 0x20008000 flags = 0x280000nr_segments = 3segment[0].buf = 0x40e98segment[0].bufsz = 0x3f0segment[0].mem = 0x20001000segment[0].memsz = 0x1000segment[1].buf = 0xb6c06008segment[1].bufsz = 0x3db659segment[1].mem = 0x20008000segment[1].memsz = 0x3dc000segment[2].buf = 0xb5ade008segment[2].bufsz = 0x1127516segment[2].mem = 0x20f6e000segment[2].memsz = 0x1128000root@host:~# kexec -eStarting new kernelBooting Linux on physical CPU 0x0...After boot:root@vanilla:~# cat /proc/iomem20000000-3fffffff : System RAM 20008000-206dd237 : Kernel code 20720000-2078f54f : Kernel dataUnsuccessful case:root@host:~# kexec -p -t zImage --command-line=console=ttyS0,38400 earlyprintk=ttyS0 root=/dev/ram rdinit=/sbin/init rw irqpoll maxcpus=1 reset_devices --atags --initrd=./initramfs.cpio.gz -d ./zImage_fixed_addrTry gzip decompressionTry LZMA decompression.lzma_decompress_file: read on ./zImage_fixed_addr of 65536 bytes failedkernel: 0xb6b69008 kernel_size: 0x3db659phys_offset: 0kernel symbol _stext vaddr = c0008240page_offset is set to c0000000get_crash_notes_per_cpu: crash_notes addr = 10f525c, size = 1024Elf header: p_type = 4, p_offset = 0x10f525c p_paddr = 0x10f525c p_vaddr = 0x0 p_filesz = 0x400 p_memsz = 0x400get_crash_notes_per_cpu: crash_notes addr = 10ff25c, size = 1024Elf header: p_type = 4, p_offset = 0x10ff25c p_paddr = 0x10ff25c p_vaddr = 0x0 p_filesz = 0x400 p_memsz = 0x400get_crash_notes_per_cpu: crash_notes addr = 110925c, size = 1024Elf header: p_type = 4, p_offset = 0x110925c p_paddr = 0x110925c p_vaddr = 0x0 p_filesz = 0x400 p_memsz = 0x400get_crash_notes_per_cpu: crash_notes addr = 111325c, size = 1024Elf header: p_type = 4, p_offset = 0x111325c p_paddr = 0x111325c p_vaddr = 0x0 p_filesz = 0x400 p_memsz = 0x400vmcoreinfo header: p_type = 4, p_offset = 0x7f1330 p_paddr = 0x7f1330 p_vaddr = 0x0 p_filesz = 0x1000 p_memsz = 0x1000Elf header: p_type = 1, p_offset = 0x0 p_paddr = 0x0 p_vaddr = 0xc0000000 p_filesz = 0x20000000 p_memsz = 0x20000000Elf header: p_type = 1, p_offset = 0x28000000 p_paddr = 0x28000000 p_vaddr = 0xe8000000 p_filesz = 0x13ffa000 p_memsz = 0x13ffa000elfcorehdr: 0x27f00000crashkernel: [0x20000000 - 0x27ffffff] (128M)memory range: [0 - 0x1fffffff] (512M)memory range: [0x28000000 - 0x3bff9fff] (319M)kernel command line: console=ttyS0,38400 earlyprintk=ttyS0 root=/dev/ram rdinit=/sbin/init rw irqpoll maxcpus=1 reset_devices elfcorehdr=0x27f00000 mem=130048Kkexec_load: entry = 0x20008000 flags = 0x280001nr_segments = 4segment[0].buf = 0x416e0segment[0].bufsz = 0x410segment[0].mem = 0x20001000segment[0].memsz = 0x1000segment[1].buf = 0xb6b69008segment[1].bufsz = 0x3db659segment[1].mem = 0x20008000segment[1].memsz = 0x3dc000segment[2].buf = 0xb5a41008segment[2].bufsz = 0x1127516segment[2].mem = 0x20f6e000segment[2].memsz = 0x1128000segment[3].buf = 0x412a0segment[3].bufsz = 0x400segment[3].mem = 0x27f00000segment[3].memsz = 0x1000<cause crash via SysRq>Loading crashdump kernel...Bye!
Boot rescue kernel at high memory address using kexec on arm
kernel;memory;kexec
null
_webapps.22981
If I make a member an admin of an organization will this allow that member to invite other members as well? Is this possible?
Trello invitations for Organizations
trello
Anyone who is an admin of an organisation can invite other people so long as they're still an admin.AddingYou can create a new organization through your accounts page, with the Start an Organization button at the bottom.To add members to an organization, first go to the organization profile. You can get to the organization profile from the link in your board page or the link next to the title of a board. Then click Members in the sidebar. In the input field, enter an email address to invite or search for a current member. NOTE: You must be an admin of an organization to add members.So after you've created the organisation, you can create your own Avon club of admins inviting new users to the group on the greater organisation's behalf.
_cstheory.27233
I'm currently enrolled in a course that introduces Turing machines. As I wanted to play around a bit, I wrote a little TM engine and had it search for busy beavers (it successfully found the 4-state 2-symbol BB listed in Wikipedia).To more quickly eliminate bad candidates, I'm searching for conditions that imply indefinite runtime. I found a couple of filters already, but the number of indefinite runs is still rather high (indefinite, as in, either seemingly running forever or sometimes checked manually).In this questions in particular I would like to inquire what space requirements a BB must have after a certain number of shifts. If it accessed less of the tape than this number, it can be dismissed directly. For this purpose, consider the tape length to extend exactly as far as the head went at most in either direction.As simple upper bound I guess something like $N_{shifts} \leq {N_{TapeLength}}^{|Q|}$ could work, though I am not sure this is even correct. Also, it should certainly be possible to improve this boundary considerably.Edit: I currently employ the following eliminations:StaticFixed first/last transition (A0-B1R,xx-H1R)State enumeration orderingAll states in transitive closure of AH in transitive closure of all statesTrap statesEquivalent statesInability to change the tapeDynamicAt either end of the tape, current state's transitive closure (using only 0-transitions) always directs further away
Busy beaver candidate elimination: Minimum space requirements
turing machines
There are many methods for detecting that specific TMs will run infinitely. As Marzio mentioned, Heiner Marzen's page and papers provide almost all of the currently used methods.The method you describe is a great simple requirement. Specifically, if we know that the TM has only moved around on a small tape of size $N_{tape}$, then the exact configuration at every step so far can be described by (1) the symbols at each of these $N_{tape}$ cells, (2) the position of the reading head and (3) the TM state. Thus there are $|Q| \cdot N_{tape} \cdot |S|^{N_{tape}}$ possible configurations (Where $|Q|$ is the number of states and $|S|$ is the number of symbols). So, if the TM has taken more than that many steps of computation, you know that it must have been in one configuration at least twice and thus that it will infinitely repeat.However, I don't think this method works very often in practice because it is more common for TMs to run off infinitely in one direction than to stay on a small section of tape.
_codereview.146556
I am doing some iteration over an array which have another set of array (the nested array). I need to .map() the outer array in such a way that it should filter out the nested array based on some criteria. Following is the example:JSON[{ id: CAM000001, type: 128, name: abc, fieldSets: [ { fields: [ { entity_name: abc_id, type: String, value: }, { entity_name: abc_name, type: String, value: XYZ Inc. }, { entity_name: created_on, type: Date, value: 09/20/2016 } ] } ]}] Code datas = datas.map(data => { data.fieldSets[0].fields = data.fieldSets[0].fields.filter(field => { return field.entity_name === 'abc_name'; }); return data;}); I searched a bit, and it seems like above code has time complexity of \$\mathcal{O}(n^2)\$ (I am still learning about time and space complexity, please correct my understanding if it's wrong). So, considering the large datasets, if fields (nested array) and datas (parent array) is growing in size, it would cost much. So can you please help me to understand what could be the best possible solution to avoid worst time complexities? Is whatever I am doing here correct?
Complexities: Filtering out nested array inside an array
javascript;algorithm;complexity
null
_unix.137514
I've captured udp traffic to a pcap file. When replaying with tcpreplay-edit, I'd like to shorten all pauses (where there is no udp traffic at all) to x seconds max. tcpreplay-edit only has a global speed multiplier.Is there any automated way to do this? Ideally without resorting to guis like wireshark, but any solution is welcome.
Remove pauses greater than x from pcap file
tcpdump;wireshark
null
_unix.136104
Where is the documentation for net.ipv4.conf.all.log_martians sysctl setting? There are man pages for various other TCP/IP/UDP (man 7 tcp, man 7 upd, man 7 ip) settings, but I can't find the net.ipv4.conf.all.log_martians docs.Note: I want official documentation from Linux; not random sites from google.
Where is the documentation for net.ipv4.conf.all.log_martians?
linux;man;documentation
Things you find in the man pages are generally about programming, and the C API. Non-programming documentation is generally found in the kernel itself.https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/Documentation/networking/ip-sysctl.txt?id=bb077d600689dbf9305758efed1e16775db1c84c#n843And those random google sites aren't usually wrong. I'm sure you'll find that many of them are just online versions of the kernel documentation.
_unix.162495
I have a file in /etc named radius which contains the user account details similar to /etc/passwd but of Radius users. How do I configure /etc/nsswitch.conf to check /etc/radius in addition to checking /etc/passwd when searching for local files?For exampleI have a line in my /etc/nsswitch.conf which sayspasswd: files nisfiles here searches only in /etc/passwd. How do I make it search other files?
Editing nsswitch.conf to check for files other than /etc/passwd while searching local files for user details
password;nsswitch;radius
null
_unix.111108
I'm using tape storage drive HP LTO3 1x8 auto-loader which is connected to my server running CentOS. it is detected in CentOS correctly.cat /proc/scsi/scsi Host: scsi2 Channel: 00 Id: 01 Lun: 00 Vendor: HP Model: 1x8 autoloader Rev: 1.50 Type: Medium Changer ANSI SCSI revision: 03lsscsi[1:0:0:0] cd/dvd NECVMWar VMware IDE CDR10 1.00 /dev/sr0[2:0:0:0] disk VMware Virtual disk 1.0 /dev/sda[2:0:1:0] mediumx HP 1x8 autoloader 1.50 /dev/sch0But the tape device file (st* or nst*) inside the /dev directory has not been created.I've loaded all the modules Module Size Used bysym53c8xx 77039 0 aic7xxx 119025 0 st 38660 0autofs4 26888 3sunrpc 243758 1ipt_REJECT 2383 2nf_conntrack_ipv4 9506 2nf_defrag_ipv4 1483 1 nf_conntrack_ipv4iptable_filter 2793 1ip_tables 17831 1 iptable_filterip6t_REJECT 4628 2nf_conntrack_ipv6 8748 2nf_defrag_ipv6 12182 1 nf_conntrack_ipv6xt_state 1492 4nf_conntrack 79453 3 nf_conntrack_ipv4,nf_conntrack_ipv6,xt_stateip6table_filter 2889 1ip6_tables 19458 1 ip6table_filteripv6 322029 29 ip6t_REJECT,nf_conntrack_ipv6,nf_defrag_ipv6ppdev 8729 0parport_pc 22978 0parport 37265 2 ppdev,parport_pce1000 167662 0microcode 112594 0vmware_balloon 7199 0ch 13503 0i2c_piix4 12608 0i2c_core 31276 1 i2c_piix4sg 30124 0shpchp 33482 0ext4 364410 3mbcache 8144 1 ext4jbd2 88738 1 ext4sd_mod 39488 4crc_t10dif 1541 1 sd_modsr_mod 16228 0cdrom 39771 1 sr_modmptspi 17051 12mptscsih 36732 1 mptspimptbase 93845 2 mptspi,mptscsihscsi_transport_spi 26151 3 sym53c8xx,aic7xxx,mptspipata_acpi 3701 0ata_generic 3837 0ata_piix 22846 0dm_mirror 14101 0dm_region_hash 12170 1 dm_mirrordm_log 10122 2 dm_mirror,dm_region_hashdm_mod 81500 12 dm_mirror,dm_logoutput of dmesg | grep scsiscsi0 : ata_piixscsi1 : ata_piixscsi 1:0:0:0: CD-ROM NECVMWar VMware IDE CDR10 1.00 PQ: 0 ANSI: 5scsi2 : ioc0: LSI53C1030 B0, FwRev=01032920h, Ports=1, MaxQ=128, IRQ=17scsi 2:0:0:0: Direct-Access VMware Virtual disk 1.0 PQ: 0 ANSI: 2scsi target2:0:0: Beginning Domain Validationscsi target2:0:0: Domain Validation skipping write testsscsi target2:0:0: Ending Domain Validationscsi target2:0:0: FAST-40 WIDE SCSI 80.0 MB/s ST (25 ns, offset 127)scsi 2:0:1:0: Medium Changer HP 1x8 autoloader 1.50 PQ: 0 ANSI: 3scsi target2:0:1: Beginning Domain Validationsr0: scsi3-mmc drive: 1x/1x writer dvd-ram cd/rw xa/form2 cdda traysr 1:0:0:0: Attached scsi CD-ROM sr0scsi: waiting for bus probes to complete ...scsi target2:0:1: Ending Domain Validationscsi target2:0:1: FAST-160 WIDE SCSI 320.0 MB/s DT IU RDSTRM RTI WRFLOW PCOMP (6.25 ns, offset 127)sr 1:0:0:0: Attached scsi generic sg0 type 5sd 2:0:0:0: Attached scsi generic sg1 type 0scsi 2:0:1:0: Attached scsi generic sg2 type 8ch 2:0:1:0: Attached scsi changer ch0Does anyone face this issue before and find a solution?
I can't find tape device file inside /dev directory
linux;kernel modules;storage;scsi;tape
null
_codereview.154928
I wrote a function to reverse a char-array (string).Since I'm beginner and didn't work with malloc and stuff before, maybe someone could take a look, if this is fine, what I'm doing here?char* reverse_string(char* string){ // getting actual length of the string size_t length = strlen(string); // allocate some space for the new string char* new_string = malloc(sizeof(char)*(length+1)); // index for looping over the string int actual_index = 0; // iterating over the string until '\0' while(string[actual_index] != '\0') new_string[length-actual_index-1] = string[actual_index++]; // setting the last element of string-array to '\0' new_string[length] = '\0'; // free up the allocated memory free(new_string); // return the new string return new_string;}
malloc and free of a char-array
beginner;c;strings;reinventing the wheel;pointers
Here are some things that may help you improve your code.Fix the bugOnce memory is freed, it should not be referenced again. Unfortunately, your code allocates memory and then frees it and then returns a pointer to the freed memory. That's a serious bug! To fix it, simply omit the free within the function and make sure the caller calls free instead. Alternatively, you could avoid all of that by reversing the passed string in place.Use the required #includesThe code uses strlen which means that it should #include <string.h> and malloc and free which means that it should #include <stdlib.h>. It was not difficult to infer, but it helps reviewers if the code is complete.Use const where practicalIn your revere_string routine, the string passed into the function is not and should not be altered. You should indicate that fact by declaring it like this:char* reverse_string(const char* string)Check for NULL pointersThe code must avoid dereferencing a NULL pointer if the call to malloc fails. The only indication that it has failed is if malloc returns NULL; if it does, it would probably make most sense to immediately return that NULL pointer.Learn to use pointers instead of indexingUsing pointers effectively is an important C programming skill. This code could be made much simpler by doing an in-place reversal of the passed string and by using pointers:char* reverse_string(char* string) { if (string == NULL) return string; char *fwd = string; char *rev = &string[strlen(string)-1]; while (rev > fwd) { char tmp = *rev; *rev-- = *fwd; *fwd++ = tmp; } return string;}
_softwareengineering.151440
I've been developing the client-side for my web-app in JavaScript.The JavaScript can communicate with my server over REST (HTTP)[JSON, XML, CSV] or RPC (XML, JSON).I'm writing writing this decoupled client in order to use the same code for both my main website and my PhoneGap mobile apps.However recently I've been worrying that writing the website with almost no static content would prevent search-engines (like Google) from indexing my web-page.I was taught about this restriction about 4 years ago, which is why I'm asking here, to see if this restriction is still in-place.Does heavy JavaScript use adversely impact Googleability?
Does heavy JavaScript use adversely impact Googleability?
javascript;google;research;search engine;seo
Google (and I suspect Bing as well) have gotten much better at reading and indexing text found in JavaScript elements during the past 3-5 years or so. They do this for two reasons. First, to provide better indexing of content for users and, second, to detect and thwart various spamming techniques. The problem is that you may not get indexed as well as you would like for the keywords you want or for long tail combos that may be valuable. Let's say that your topic was on dog training supplies. You might be able to rank for dog training supplies if your incoming links were good and other on-page elements fit the search engines' statistical profiles. However, since you have content for German Shepard training supplies or Great Dane training supplies buried inside a lot of replaceable text, you might not rank as easily for these terms. There are some ways to manage this but the best strategy will depend on specifics for your site.Another thing to consider is that splitting off content into standard and mobile sections can cause ranking problems as well. Make sure that you use the canonical tag to indicate that your standard page is the one that should be considered the primary source. This avoids duplicate content filtering and possible penalties associated with the recent Google Panda update.
_unix.49601
I want to do non-greedy pattern (regular expression) matching in awk.Here is an example:echo @article{gjn, Author = {Grzegorz J. Nalepa}, | awk '{ sub(/@.*,/,); print }'Is it possible to write a regular expression that selects the shorter string?@article{gjn,instead of this long string?:@article{gjn, Author = {Grzegorz J. Nalepa},I want to get this result: Author = {Grzegorz J. Nalepa},I have another example:echo ,article{gjn, Author = {Grzegorz J. Nalepa}, | awk '{ sub(/,[^,]*,/,); print }' ^^^^^Note that I changed the @ characters to comma (,) charactersin the first position of both the input string and the regular expression(and also changed .* to [^,]*).Is it possible to write a regular expression that selects the shorter string?, Author = {Grzegorz J. Nalepa},instead of the longer string?:,article{gjn, Author = {Grzegorz J. Nalepa},I want to get this result:,article{gjn
How to reduce the greediness of a regular expression in AWK?
awk;regular expression
If you want to select @ and up to the first , after that, you need to specify it as @[^,]*,That is @ followed by any number (*) of non-commas ([^,]) followed by a comma (,).
_datascience.19125
I want to calculate the frequency of the words in obama['text'] (obama is the variable where i have stored this series element ) in a dictionary and store it in another column . Without using Counter library , how do i do that . The data is in this format : URI | name | text <http://dbpedia.org/resource/Barack_Obama> Barack Obama barack hussein obama ii brk husen bm born august 4 1961 is the 44th and current president of the united states and the first african american to hold the office born in honolulu hawaii obama is a graduate of columbia university and harvard law school where he served as president of the harvard law review he was a community organizer in chicago before earning his law degree he worked as a civil rights attorney and taught constitutional law at the university of chicago law school from 1992 to 2004 he served three terms representing the 13th district in the illinois senate from 1997 to 2004 running unsuccessfully for the united states house of representatives in 2000in 2004 obama received national attention during his campaign to represent illinois in the united states senate with his victory in the march democratic party primary his keynote address at the democratic national convention in july and his election to the senate in november he began his presidential campaign in 2007 and after a close primary campaign against hillary rodham clinton in 2008 he won sufficient delegates in the democratic party primaries to receive the presidential nomination he then defeated republican nominee john mccain in the general election and was inaugurated as president on january 20 2009 nine months after his election obama was named the 2009 nobel peace prize laureateduring his first two years in office obama signed into law economic stimulus legislation in response to the great recession in the form of the american recovery and reinvestment act of 2009 and the tax relief The output should be in the format in a new column obama['word count']:{ 2009:4 , the :40 , chicago :10and so on }
Count the frequncy of words in a cell of a column in a series
machine learning;python;pandas
Why shouldn't you use the Counter class; it's exactly what you need?from pandas import Seriesfrom collections import Countertext=barack hussein obama ii brk husen bm born august 4 1961 is the 44th and current president of the united states and the first african american to hold the office born in honolulu hawaii obama is a graduate of columbia university and harvard law school where he served as president of the harvard law review he was a community organizer in chicago before earning his law degree he worked as a civil rights attorney and taught constitutional law at the university of chicago law school from 1992 to 2004 he served three terms representing the 13th district in the illinois senate from 1997 to 2004 running unsuccessfully for the united states house of representatives in 2000in 2004 obama received national attention during his campaign to represent illinois in the united states senate with his victory in the march democratic party primary his keynote address at the democratic national convention in july and his election to the senate in november he began his presidential campaign in 2007 and after a close primary campaign against hillary rodham clinton in 2008 he won sufficient delegates in the democratic party primaries to receive the presidential nomination he then defeated republican nominee john mccain in the general election and was inaugurated as president on january 20 2009 nine months after his election obama was named the 2009 nobel peace prize laureate during his first two years in office obama signed into law economic stimulus legislation in response to the great recession in the form of the american recovery and reinvestment act of 2009 and the tax reliefdf = Series(text).to_frame()newdf = df.assign(word_count = lambda x: x[0].str.split(' ').apply(Counter)[0])newdf['word_count']0 {'44th': 1, 'born': 2, 'november': 1, 'running...
_cs.16757
I'm playing around with tournaments and currently have the problem that I need to check whether a given subset of the edges of a tournament is transitive (it need not be acyclic). I'm aware that I can always take the transitive closure of the edge set and see whether it terminates without adding a single edge or not, but I was wondering if there might be a simpler way than that.Note that I'm specifically going for simplicity, not efficiency; the tournaments I want to check are over a maximum of $7$ vertices, so complexity really isn't an issue. I would prefer simple, easy to implement ways. The simplest I could find so far is Floyd-Warshall, but maybe someone knows anything that's simpler still.
Simplest way to check edge set for transitivity
algorithms;graphs;transitivity
There's a very simple algorithm for this:for each edge (u,v) in the graph: for each edge (v,w) in the graph: if (u,w) is not in the graph, return Not transitivereturn TransitiveBasically, if the graph is not transitive, then you can always find some path of length two $u\to v \to w$ such that the edge $u \to w$ is not present in the graph. If the graph is transitive, there won't be any such path of length 2. So, just check this condition.
_webapps.60309
I use Dropbox at my workplace and using selective sync, only allowed the syncing of certain folders. However, as I noticed, other people can easily sync my other files if they simply swoop in my workstation without me noticing.Is it possible to require password checks (or a similar security measure) before allowing changes to Dropbox preferences?
Prevent other users from changing Dropbox Desktop preferences
security;dropbox
null
_unix.160057
I'm trying to write a bash script which will copy a bunch of files and directories from a directory, omitting a couple but taking everything else.I have got a command that does this and works from the command line:cp -r !(dspace.cfg|README.md) ~/tmp/directoryThis does exactly what I want it to do, so I've put it into my bash script (which does some other things besides), so it looks like this:#!/bin/bashSRC=/targetMAVEN=mvn# copy everything except the readme and the dspace.cfg extensioncp -r !(dspace.cfg|README.md) $SRC/configAnd when I run it I get:$ bash addmodule.sh addmodule.sh: line 7: syntax error near unexpected token `('addmodule.sh: line 7: `cp -r !(dspace.cfg|README.md) $SRC/config'I've checked all the obvious things: the shebang is right, I'm running it explicitly with bash from the command line (I've checked that on my Ubuntu 14.04 system that this really is bash and not dash), and I've checked that posix is off (though I'm not sure if that would make any difference in this case).I'm a total newbie at bash programming - basically all I want is a script that wraps up a few commands that I'd run from the command line, and that's about the extent of my knowledge! Any help much appreciated.
bash syntax error near unexpected token `(' - but everything looks like it should work
bash;shell
null
_softwareengineering.132517
Sorry if this question is not appropriate for this stack exchange site, I've never used this one before. I am doing my senior project on computer programming. I'm going to be presenting the project to classmates, teachers and (most importantly) judges, who haven't the slightest clue what programming is.My question is somewhat broad, but how should I make my project to be about programming but still be simple enough for the judges to understand? Here are some things I considered:The project will focus on the history of programming, what it has accomplished, how it is used today, etc. and I will show pictures of code and say This is what code looks like. So the presentation would be simple, easy, and average.Try to explain a little bit of code, perhaps show a loop in action or something like that, and try to make the audience think a bit rather than just watch someone present some stuff they consider to be boring. But then again, I don't want to make them feel stupid or anything.
How to explain the history of programming to non-programmers?
education;history;presentation
If your presentation is about the history of programming I would focus on how a computer only understands binary, and that binary is essentially impossible for a human to understand so programming languages were created. From there I would show the same sample program in several languages to show the evolution to modern languages, something simple but not a bit more than hello world. This would cover concepts like compiling, and how language A can be used to create language B. Talking about how memory constraints factored into design would also be good.Explaining what a loop does or steeping through code explaining why its done this way isn't as related programming, because it would be an explanation of instruction logic that has existed longer than just electronic computers (finite state machines, mechanical computers). While this is a concept that is fundamental to programming, it explains what programming is rather than what has been accomplished through programming/how its used today.
_unix.345099
I'm working with Amazon Linux in AWS and attempting to setup multiple file systems on a single EBS Volume (block device) for compliance reasons. I'm doing this by mounting an EBS Volume to an already-running EC2 Instance, executing a series of commands, unmounting it, creating a snapshot and then turning it into an AMI.I can get everything working with a basic set of commands that simply delete and re-add an existing partition. But when I add a second partition, I'm no longer able to launch any EC2 Instances from that AMI. Instead, using the Get Instance Screenshot functionality in AWS, the EC2 Instance never boots and I see this:When I execute the following commands from a host EC2 Instance on which I've mounted an EBS Volume, everything works as expected:# Make a tar of the current EBS Volumeumount -l /mnt/ebs-volumemount -o ro /dev/xvdf1 /mnt/ebs-volumetar -cf /tmp/ebs.tar --exclude='./dev/*' --exclude='./proc/*' --exclude='./sys/*' /mnt/ebs-volumeumount /mnt/ebs-volume# Replace the old partition with one new partition and format it as ext4sgdisk --delete 1 /dev/xvdfsgdisk --new 1:0:+7800M /dev/xvdf && sgdisk --change-name 1:Linux/sbin/mkfs.ext4 -F -m0 -O ^64bit /dev/xvdf1 && e2label /dev/xvdf1 /# Mount the new partition and restore the snapshotmount /dev/xvdf1 /mnt/ebs-volumecd / && tar -xf /tmp/ebs.tar --acls --selinux --xattrs && rm /tmp/ebs.tar# I don't make any updates to the /etc/fstab fileBut when I execute these commands instead, the EC2 Instance fails to boot as shown above:# Make a tar of the current EBS Volumeumount -l /mnt/ebs-volumemount -o ro /dev/xvdf1 /mnt/ebs-volumetar -cf /tmp/ebs.tar --exclude='./dev/*' --exclude='./proc/*' --exclude='./sys/*' /mnt/ebs-volumeumount /mnt/ebs-volume# Replace the old partition with two new partitions and format them as ext4sgdisk --delete 1 /dev/xvdfsgdisk --new 1:0:+7800M /dev/xvdf && sgdisk --change-name 1:Linuxsgdisk --new 2:0:+100M /dev/xvdf/sbin/mkfs.ext4 -F -m0 -O ^64bit /dev/xvdf1 && e2label /dev/xvdf1 //sbin/mkfs.ext4 -F -m0 -O ^64bit /dev/xvdf2# Mount the new partitions and restore the snapshotmount /dev/xvdf1 /mnt/ebs-volumemkdir -p /mnt/ebs-volume/boot && mount /dev/xvdf2 /mnt/ebs-volume/bootcd / && tar -xf /tmp/ebs.tar --acls --selinux --xattrs && rm /tmp/ebs.tar# I now execute commands that write the below /etc/fstab file to the volume at /mnt/ebs-volume/etc/fstab/etc/fstab:LABEL=/ / ext4 defaults,noatime 1 1/dev/xvda2 /boot ext4 defaults,noatime 0 0tmpfs /dev/shm tmpfs defaults 0 0devpts /dev/pts devpts gid=5,mode=620 0 0sysfs /sys sysfs defaults 0 0proc /proc proc defaults 0 0Why would adding a separate file system for /boot cause this error? Am I missing something in my /etc/fstab or perhaps another file somewhere since I suppose this new configuration is now no longer the same as the original configuration.
Why does this change render my Block Device unbootable?
boot;partition;fdisk;block device;aws
This may require some pre-history of the PC boot sequence to fully explain. (Modern PC's with UEFI do things differently, but the logic is similar).So let's look back at the 80s, when PCs first started to have hard disks.The BIOS would load the first sector of the hard disk. This contained the Master Boot Record (MBR), which was a combination of code and the partition table. There was only 512 bytes to hold all of this, so coding was tight.The MBR would look at the partition table and find out which partition was active and where it started. It would then load a secondary boot system, which was stored inside that partition. (Historically this meant the secondary boot loader had to be within the first 504Mb of disk). This code knew about the filesystem and could load the OS (typically IO.SYS, MSDOS.SYS, COMMAND.COM). And thus DOS booted. A typically new PC would require fdisk /mbr to install this primary boot sector.The fact that it was software in the MBR made the boot process flexible and allowed alternate boot loaders. An early boot loader for Linux was LILO (Linux Loader). This had a primary loader, a secondary loader. It knew about standard Linux filesystems and was able to dual boot Linux and DOS (and Windows).Later GRUB (and then GRUB2) came along. But they all follow the primary/secondary boot loader process.Now what you're doing is moving the secondary boot process when you modify the /boot partition. The (pretty dumb) primary boot loader doesn't know where the find the smart part. And so your VM fails to boot.What you need to do is the modern equivalent of the old fdisk /mbr process; you need to tell your MBR where to find the secondary loader.How you do this depends on what boot loader you're using. It may be grub-install or grub2-install or lilo. It'll depend on the OS variant (CentOS, Ubuntu, Debian, Amazon... they may all be different).This doesn't tell you what to do to fix your build, but at least, now, you should understand why your OS fails to boot!
_codereview.159075
My first 'large' project is to create an organizational tool. Right now, it's pretty basic, but nevertheless functional in terms of the intent of the current release (v0.3.0).My main question is: 'Is what I'm doing procedurally correct/is this the way I should be designing my GUI?'. This is my first time doing any GUI design, and although I feel that the end-product is pretty good for a first attempt, I'm also hopeful that there is something I could/should be doing to either make my code more readable/debuggable or (I guess this is kind of the same thing, but) easier to change in the future.Secondary to that, is the way I'm handling the JList I'm using for the 'log' the best way to do so? I'd eventually like to make a custom type of list that better handles the use of the LogItem objects that I'm using (in my mind called a LogList that accepts LogItems for a .add(LogItem logItem) method.package com.t99sdevelopment;// Created by Trevor Sears <[email protected]> @ 11:45AM - March 16th, 2017.import java.awt.*;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.*;public class Window extends JFrame implements Runnable{ public static LogListModel log = new LogListModel(); private static JFrame frame = new JFrame(); private static JMenuBar menuBar = new JMenuBar(); private static JMenu file_Menu = new JMenu(File); private static JMenuItem open_File_MenuItem = new JMenuItem(Open...); private static JMenuItem reset_File_MenuItem = new JMenuItem(Reset Log); private static JMenuItem close_File_MenuItem = new JMenuItem(Close); private static JMenu edit_Menu = new JMenu(Edit); private static JMenuItem undo_Edit_MenuItem = new JMenuItem(Undo); private static JMenuItem redo_Edit_MenuItem = new JMenuItem(Redo); private static JMenu about_Menu = new JMenu(About); private static JPanel panel = new JPanel(new GridBagLayout()); private static JLabel time_Label = new JLabel(); private static JButton submit_Button = new JButton(); private static JTextField event_TextField = new JTextField(); static JList log_List = new JList(log.toArray()); //not sure if this being public is the best solution to the problem... private static JPopupMenu logCell_PopupMenu = new JPopupMenu(); private static JMenuItem edit_logCell_MenuItem = new JMenuItem(); private static JMenuItem delete_logCell_MenuItem = new JMenuItem(); private static JScrollPane scrollPane = new JScrollPane(log_List, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); private static JButton close_Button = new JButton(); private static JDialog edit_Dialog = new JDialog(frame); private static JPanel edit_Dialog_Panel = new JPanel(); private static JTextField edit_Dialog_edit_TextField = new JTextField(); private static JPanel edit_Dialog_subpanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0)); private static JButton edit_Dialog_submit_Button = new JButton(); private static JButton edit_Dialog_cancel_Button = new JButton(); private static EventLogListener eventLogActionListener = new EventLogListener(); private static LogEditorListener logEditorActionListener = new LogEditorListener(); private static ShutdownListener shutdownActionListener = new ShutdownListener(0); private static GridBagConstraints constraints = new GridBagConstraints(); private static Dimension dimension = new Dimension(500, 200); public static void showWindow() { initializeWindow(); frame.setVisible(true); } private static void initializeWindow(){ initializeRightMousePopupMenu(); initializeLogItemEditDialog(); initializeMenuBar(); frame.setJMenuBar(menuBar); initializePanel(); frame.add(panel); frame.setTitle(organize); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setMinimumSize(dimension); frame.setResizable(false); frame.pack(); frame.setLocationRelativeTo(null); edit_Dialog.setLocationRelativeTo(null); } private static void initializePanel(){ // Time JLabel (time_Label) option setting... time_Label.setHorizontalAlignment(JTextField.CENTER); time_Label.setFont(new Font(Serif, Font.BOLD, 18)); constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 3; constraints.gridheight = 1; constraints.weightx = 0.5; constraints.weighty = 0.05; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.insets = new Insets(5,0,0,0); panel.add(time_Label, constraints); // Submit JButton (submit_Button) option setting... submit_Button.setText(Submit); submit_Button.addActionListener(eventLogActionListener); constraints.gridx = 0; constraints.gridy = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weightx = 0.05; constraints.weighty = 0.1; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.insets = new Insets(0,5,5,3); panel.add(submit_Button, constraints); // Event JTextField (event_TextField) option setting... event_TextField.setColumns(50); event_TextField.setEditable(true); event_TextField.addActionListener(eventLogActionListener); constraints.gridx = 1; constraints.gridy = 1; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.weightx = 0.95; constraints.weighty = 0.1; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.insets = new Insets(0,3,5,5); panel.add(event_TextField, constraints); // Logs JTextArea (logs_TextArea) option setting... log_List.setModel(log); constraints.gridx = 0; constraints.gridy = 2; constraints.gridwidth = 3; constraints.gridheight = 1; constraints.weightx = 0.5; constraints.weighty = 0.9; constraints.ipady = 40; constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(0,5,0,5); panel.add(scrollPane, constraints); // Close JButton (close_Button) option setting... close_Button.setText(Close); close_Button.addActionListener(shutdownActionListener); constraints.gridx = 2; constraints.gridy = 3; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weightx = 1; constraints.weighty = 0.05; constraints.ipady = 0; constraints.fill = GridBagConstraints.NONE; constraints.anchor = GridBagConstraints.LINE_END; constraints.insets = new Insets(0,0,0,10); panel.add(close_Button, constraints); } private static void initializeMenuBar(){ open_File_MenuItem.setToolTipText(This doesn't do anything right now!); undo_Edit_MenuItem.setToolTipText(This doesn't do anything right now!); redo_Edit_MenuItem.setToolTipText(This doesn't do anything right now!); about_Menu.setToolTipText(This doesn't do anything right now!); reset_File_MenuItem.addActionListener(n -> log.clear()); close_File_MenuItem.addActionListener(shutdownActionListener); file_Menu.add(open_File_MenuItem); file_Menu.addSeparator(); file_Menu.add(reset_File_MenuItem); file_Menu.add(close_File_MenuItem); edit_Menu.add(undo_Edit_MenuItem); edit_Menu.add(redo_Edit_MenuItem); menuBar.add(file_Menu); menuBar.add(edit_Menu); menuBar.add(about_Menu); } private static void initializeRightMousePopupMenu(){ log_List.addMouseListener(new MouseAdapter(){ public void mouseReleased(MouseEvent e){ if(SwingUtilities.isRightMouseButton(e)){ log_List.setSelectedIndex(log_List.locationToIndex(e.getPoint())); edit_Dialog_edit_TextField.setText(log.getEvent(log_List.getSelectedIndex())); logCell_PopupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); edit_logCell_MenuItem.setText(Edit); edit_logCell_MenuItem.addActionListener(e -> edit_Dialog.setVisible(true)); logCell_PopupMenu.add(edit_logCell_MenuItem); delete_logCell_MenuItem.setText(Delete); delete_logCell_MenuItem.addActionListener(e -> log.remove(log_List.getSelectedIndex())); logCell_PopupMenu.add(delete_logCell_MenuItem); } private static void initializeLogItemEditDialog(){ edit_Dialog_Panel.setLayout(new BoxLayout(edit_Dialog_Panel, BoxLayout.Y_AXIS)); edit_Dialog_Panel.add(Box.createRigidArea(new Dimension(0, 5))); // Edit JTextField (edit_Dialog_edit_TextField) option setting... edit_Dialog_edit_TextField.setColumns(50); edit_Dialog_edit_TextField.addActionListener(logEditorActionListener); edit_Dialog_Panel.add(edit_Dialog_edit_TextField); edit_Dialog_Panel.add(Box.createRigidArea(new Dimension(0, 5))); edit_Dialog_subpanel.add(Box.createRigidArea(new Dimension(250, 0))); // Submit JButton (edit_Dialog_submit_Button) option setting... edit_Dialog_submit_Button.setText(OK); edit_Dialog_submit_Button.addActionListener(logEditorActionListener); edit_Dialog_subpanel.add(edit_Dialog_submit_Button); // Cancel JButton (edit_Dialog_cancel_Button) option setting... edit_Dialog_cancel_Button.setText(Cancel); edit_Dialog_cancel_Button.addActionListener(e -> disposeEditDialog()); edit_Dialog_subpanel.setBackground(new Color(35, 100, 50, 1)); edit_Dialog_subpanel.add(edit_Dialog_cancel_Button); edit_Dialog_Panel.add(edit_Dialog_subpanel); edit_Dialog_Panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); edit_Dialog.setModal(true); edit_Dialog.setSize(new Dimension(500, 150)); edit_Dialog.setTitle(Edit); edit_Dialog.add(edit_Dialog_Panel); edit_Dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); edit_Dialog.pack(); } public static void appendNewEvent(String event){ log.addElement(new LogItem(event)); log_List.ensureIndexIsVisible(log_List.getModel().getSize() - 1); event_TextField.setText(); } public static String getEventLogText(){ return event_TextField.getText(); } public static String getEditedDialogText(){ return edit_Dialog_edit_TextField.getText(); } public static void disposeEditDialog(){ edit_Dialog.dispose(); } public void run() { while(true){ time_Label.setText(DateChanger.getTime()); } }}The rest of the project can be found here. The link is more for the curious than anything - it includes pre-compiled binaries of a small handful of previous releases.EDIT: To help ease those of you that are cringing - I've implemented most, if not all of your suggested changes. See the above link if you're interested.
Organizational Tool GUI with Java Swing (and GridBagLayout)
java;linked list;swing;gui
null
_unix.284791
I keep getting an error when booting Alpine Linux Networking failed to start. I'm using a RPI3 which is connected by an ethernet cable to the box. Here's the /etc/network/interfaces :auto loiface lo inet loopbackauto eth0iface eth0 inet static address 192.168.1.1 netmask 255.255.255.0 gateway 192.168.1.255when typing netstat -r I have :Destination Gateway Genmask Flags MSS Window irtt Iface192.168.1.0 * 255.2555.255.0 U 0 0 0 eth0I turned it into dhcp and it worked. Any ideas as to the problem?
Networking failed to start on Alpine linux
networking;raspberry pi;alpine linux
Your gateway is wrong.With the subnet mask you are using, the gateway is not a valid ip address.Once you get the ip address via DHCP, run:route -n | grep 0.0.0.0 | head -1 | awk '{print $2}'And put that as gateway.Of course, the address entry should be different from the gateway.Hope it helps..: Francesco
_scicomp.25794
The following is related to a question a asked a few days back 1, but now I would like to focus on just one part of the problem.I have problems computing the integral over the reference element:$$ \int_{0}^1 (f - \Pi_h^1(f))^2 dx. $$I think I understood how to use the basis functions on the reference element and what the values of $f$ should be for the interpolant. The problem is with the first $f$ in the integrand. How can I map it? If the affine map is $x = x_j + \gamma (x_{j+1} - x_j)$ I can substitute it into $f$ and obtain$$ f(x(\gamma)) = cos(2 \pi (x_j + \gamma (x_{j+1} - x_j))). $$How can I continue? I was following these beautiful notes on page $49$ but that is very simple.Using Python to do this I ended up with this:def func_ref(z, x, a, b): cos_a = np.cos(2*np.pi*x[a]) cos_b = np.cos(2*np.pi*x[b]) return np.power((cos_a - cos_a * (1 - z) + cos_b * z) * (x[b] - x[a]), 2)where x is simply the vector containing the nodes, a and b would be the left and right neighbor, z the variable of integration. The first term, $\mathbf{cos_a}$ should be the first $f$ of the integrand but I do not know/understand how to do this. Thank you.Possible solution:Is it correct to write$$ \int_{0}^1 (cos(2\pi (x_i + \gamma (x_{i+1} - x_i)) - cos(x_i)(1-\gamma) + cos(x_{j+1})\gamma)^2 (x_{i+1} - x_i) d \gamma $$and integrate with respect to $\gamma$?
Integral over reference element in $1$D FEM: how to map the quadrature points?
finite element;python;integration
null
_unix.247756
I have a Raspberry Pi (with Raspbian Jessie) since yesterday and already installed some usefull tools - e.g. TightVNC. I configured it and it works fine, but now I want to stop my raspberry from booting into desktop mode. So if I connect over VNC I just want to see a shell window, like if I press Ctrl-Alt-F1 for example. Is there a way to configure my VNC to work like this? I already searched the web and didn't find something useful.. so please help me!
Raspberry Pi VNC to shell
debian;vnc
null
_unix.37336
What patchlevel does this SLES machine has? 10.2 or 10.4?SERVER:~ # cat /etc/issueSUSE LINUX Enterprise Server 10.2Kernel \r (\m), \lSERVER:~ # SERVER:~ # cat /etc/SuSE-release SUSE Linux Enterprise Server 10 (x86_64)VERSION = 10PATCHLEVEL = 4SERVER:~ # UPDATE: SERVER:/etc # rpm -V sles-releaseS.5....T c /etc/issueS.5....T c /etc/issue.netS.5....T c /etc/motdSERVER:/etc # zypper sl# | Enabled | Refresh | Type | Name | URI --+---------+---------+------+-----------------------------------------------------+-----------------------------------------------------------------------1 | No | No | YaST | SUSE Linux Enterprise Server 10 SP2 | cd:///?devices=/dev/hda 2 | Yes | Yes | YaST | SUSE Linux Enterprise Server 10 SP2-20110317-171027 | nfs://123.123.123.123/usr/sys/inst.images/Linux/SuSE/SLES10_x86_64/10.2SERVER:/etc # uname -r2.6.16.60-0.91.1-smpUPDATE #2: SERVER:/etc # cat /etc/issue.rpmnewWelcome to SUSE Linux Enterprise Server 10 SP4 (x86_64) - Kernel \r (\l).UPDATE #3SERVER:/etc # SERVER:~ # rpm -qi glibcName : glibc Relocations: (not relocatable)Version : 2.4 Vendor: SUSE LINUX Products GmbH, Nuernberg, GermanyRelease : 31.95.1 Build Date: Mon Sep 19 16:43:25 2011Install Date: Sun Mar 18 08:01:27 2012 Build Host: macintyreGroup : System/Libraries Source RPM: glibc-2.4-31.95.1.src.rpmSize : 5141247 License: BSD 3-Clause; GPL v2 or later; LGPL v2.1 or laterSignature : DSA/SHA1, Mon Sep 19 16:45:00 2011, Key ID a84edae89c800acaPackager : http://bugs.opensuse.orgURL : http://www.gnu.org/software/libc/libc.htmlSummary : Standard Shared Libraries (from the GNU C Library)Description :The GNU C Library provides the most important standard libraries usedby nearly all programs: the standard C library, the standard mathlibrary, and the POSIX thread library. A system is not functionalwithout these libraries.Distribution: SUSE Linux Enterprise 10SERVER:~ #
How to detect SLES version?
sles
Most probably you have got a SLES10 SP4.Do a rpm -V sles-release - if /etc/SuSE-relase does not show 5 (i.e. changed md5-checksum) the file content is original.If you update your question with your exact kernel version (uname -r) I can even tell you more.You can also check which repositories are active on that system: zypper slUpdate on uname/zypper results:Here is a list of SLES-kernels and their release dates. This shows your kernel to be a SLES10 SP4 released on 2011-10-28. There is a more recent SP4 kernel from 2012-01-23.Your output from zypper sl puzzles me. I can not see how your system got to SLES10 SP4 - there are only SLES10 SP2 repositories shown. I think it is worth to look into this a bit deeper... (see my current comment to your question)
_codereview.164364
I'm currently working on a text adventure game for my first project. I am a beginner so I am seeking help with my code. Please comment any tips and general help regarding with making my code better, faster or more organised! I only started Python two weeks ago so any help would be greatly appreciated. I decided to only submit the code for the first room as I don't want to submit too much code at once.health = 100coins = 0tutorial = TruegameStart = Falsedeath = Falsespawn = TruelivingRoom = FalseBathroom = FalseBedroom = FalseKitchen = FalsewardrobeSpawn = FalsespawnStart = Truetelev = Falsedef countCoins(): print print(You have: + str(coins) + coins)while gameStart == True: if spawn == True: if spawnStart == True: print print(bcolors.FAIL + You wake up in a room you don't recognise, with no idea how you got there) print print(bcolors.ENDC + You look around and see a wardrobe and a door) spawnStart = False elif spawnStart == False: print spawnIn = raw_input() spawnIn = spawnIn.lower() if spawnIn == coins: countCoins() spawnStart = False elif spawnIn == wardrobe: if wardrobeSpawn == False: print print The wardrobe seems quite empty, but you do find a coin in the far left corner, you put it in your pocket print coins += 1 wardrobeSpawn = True spawnStart = False elif wardrobeSpawn == True: print This wardrobe looks oddly familiar, you have already explored it print spawnStart = False elif spawnIn == door: print print (You walk out the door) print spawn = False livingRoom = True elif spawnIn == look: print(You look around and see a wardrobe and a door) print spawnStart = False else: print(That is an unvalid command. Try again) print spawnStart = False
Text Adventure Game in Python
python;python 3.x;adventure game
null
_cs.32579
In computation theory, when talking about the computability and complexity of aproblem, what is the definition of a problem? How specific should a problem be? For example, can the followingsall be function evaluation problems?evaluate $f$, where $f(x)=x^2, x \in \mathbb R$evaluate any function in $\mathbb R^{\mathbb R}$.evaluate any function in $Y^X$, where $X$ and $Y$ are any two sets.Without restriction to the computability and complexity of a problem (oreven without restriction to computation theory), how is a problem defined? Can the above examples in 1 all be function evaluation problems?Thanks.
What is the definition of a problem
complexity theory;terminology;computability
null
_cstheory.38258
Given two trees A and B, each of their nodes except some leaves have a type (which also determines the number of children, the node has, having that type). The leaves which don't have a type are identified by letters (variables) (a,b,c,...). Each letter may occur multiple times in a tree. The task is to devise an algorithm to 'solve' the 'equation' A=B, i.e. assign trees to the variables (possibly containing other variables). One tree (x) equals to an other (y) iff x and y are the same variables or the root of both have the same type and their respective children are equal.In the following the types are numbers.Example 1:A tree is1|-2|-aB tree is1|-2|-3The solution is a->3Example 2:A tree is1|-2|-aB tree is1|-3|-3This does not have a solution.Example 3:A tree is1|-2|-aB tree is1|-2|-bThe solution is a=b (the equation is underdetermined so to say)
Solving a tree-equation?
graph algorithms;term rewriting systems
The process you seem to be looking for (merging two descriptions of labeled trees) is called unification. According to the linked Wikipedia article it can be solved in linear time.
_unix.223402
For easily specifying remote files for editing with vim or emacs from the shell, I would like to have tab-completion like available for scp.Completions for scp work well and fast, if your.ssh/config iscorrectlyconfigured.So why not for vim, and other ssh-capable editors? I feel, the standard bash-completion package could benefit from a completion function set for ssh-capable editors, which AFAIK does not yet exist publicly.(In environments, where afuse and sshfs are available to me, I use as work-around a user-level afuse sshfs auto-mounter daemon spawned from shell init to on-demand background mount remote file-systems into a tree under ~/scp/.)
Bash command-line completion function for vim and emacs 'scp://' remote file paths
bash;vim;emacs;autocomplete;bashrc
null
_softwareengineering.328041
I am slowly creating a simple programming language (a bit like Lua).The interpreter has 2 important methods, exec and evaluate.exec reads the tokens 1 by 1 and does stuff as it says like creating new variables, etc.evaluate basically interprets a bit differently.It understands ==, new numbers (5.3), +-*/^% and new strings with .It also understands variables and takes their value to be used.In the end of evaluate, it returns one value for exec to use.A ginormous design hole in this interpreter is the fact that you cannot create new strings in exec without creating a variable. Meaning:string a = some string;a.someStringMethod();Works, but this:some string.someStringMethod();does not.This also means multidimensional arrays do not work, although I plan to use . instead of [ and ].If you still do not understand how the interpreter right now here is the GitHub page on it:https://github.com/lvivtotoro/mau/blob/master/Mau/src/org/midnightas/mau/Mau.java#L56So the overall question is: How would I merge these 2 methods?
Slowly creating programming language; How to join these 2 methods?
java;language design
null
_softwareengineering.75648
In my brief time as a professional programmer I've seen lots of applications written by programmers who's entire education appears to have been reading the first couple of chapters in a .NET 2.0 book.Heck when I started I wrote most of those applications!What are the biggest design patterns crucial for writing AWESOME .NET applications?By awesome I mean on the inside too!
What are the main practices and design patterns every .NET guy should know?
c#;.net;design patterns
First: Know your basic tools wellKnow the ASP.Net event model. You'll get in a mess if you don't.Understand the mechanics of OO. A surprising number of relatively experienced .Net programmers still seem to think it is 1972.Start reading Code Complete.Second: Learn to separate concernsThe most common design-crime I see in ASP.Net development is to stuff all the business logic in the code-behind. I know that all the Microsoft examples do it that way. I know it is justified on small apps. And I know I sometimes do it that way. But really, it is bad design, and is my pet hate for the week.Third: Learn everything else about designMost of the poor quality .Net code that I see is the result of poor OO design. Therefore, I'd recommend a good understanding of:SOLID principlesGoF Design PatternsMVC (for ASP.Net MVC)Fourth: Get to know more toolsYou know how Microsoft make things easy by providing lots of out-of-the-box tools? Well, you're going to hit their limitations sooner or later. When you do, you're either going to have to bend them to your will or roll your own. Either way, you're going to have to get-down-dirty with some CSS and Javascript.FinallyOnce you've done that lot, you're well on your way to awesome.[Edit: Fixed-up the sequence for learning this sutff. Apparenty I couldn't count yesterday...]
_datascience.19326
Bayesian Network deals with probabilities, so how does one use it for predicting an quantitative result ? There are couple of research papers that I came across that uses Tree Augmented Naive Bayes, but couldnt understand how its functions to forecast a quantitative outcome variable.
How would you use Bayesian Network for forecasting?
predictive modeling;regression;bayesian networks
null
_cs.11479
I am attempting to prove the following problem is undecidable. Given a Turing machine $M$ and input $x$, does $M$ visit infinitely many tape cells on input $x$? I am considering a reduction from the halting problem. Is this the right approach?
Show the problem of a machine visiting infinitely many tape cells on some input is undecidable
computability;turing machines;reductions;undecidability;halting problem
null
_scicomp.20515
I am wondering how Dirichlet boundary conditions in global sparse finite element matrices are actually implemented efficiently. For example lets say that our global finite element matrix was:$$K = \begin{bmatrix} 5 & 2 & 0 & -1 & 0 \\ 2 & 4 & 1 & 0 & 0 \\ 0 & 1 & 6 & 3 & 2 \\ -1 & 0 & 3 & 7 & 0 \\ 0 & 0 & 2 & 0 & 3\end{bmatrix}\hspace{5mm}\text{and right-hand side vector}\hspace{5mm} b = \begin{bmatrix} b1 \\ b2 \\ b3 \\ b4 \\ b5 \\\end{bmatrix}$$Then to apply a Dirichlet condition on the first node ($x_{1}=c$) we would zero out the first row, put a 1 at $K_{11}$, and subtract the first column from the right-hand side. For example our system would become:$$K = \begin{bmatrix} 1 & 0 & 0 & 0 & 0 \\ 0 & 4 & 1 & 0 & 0 \\ 0 & 1 & 6 & 3 & 2 \\ 0 & 0 & 3 & 7 & 0 \\ 0 & 0 & 2 & 0 & 3\end{bmatrix}\hspace{5mm}\text{and right-hand side vector}\hspace{5mm} b = \begin{bmatrix} c \\ b2-2\times{c} \\ b3-0\times{c} \\ b4+1\times{c} \\ b5-0\times{c} \\\end{bmatrix}$$This is all well and good in theory, but if our K matrix is stored in compressed row format (CRS) then moving the columns to the right-hand side becomes expensive for large systems (with many nodes being dirichlet). An alternative would be to not move the columns corresponding to a Dirichlet condition to the right-hand side, i.e. our system would become:$$K = \begin{bmatrix} 1 & 0 & 0 & 0 & 0 \\ 2 & 4 & 1 & 0 & 0 \\ 0 & 1 & 6 & 3 & 2 \\ -1 & 0 & 3 & 7 & 0 \\ 0 & 0 & 2 & 0 & 3\end{bmatrix}\hspace{5mm}\text{and right-hand side vector}\hspace{5mm} b = \begin{bmatrix} c \\ b2 \\ b3 \\ b4 \\ b5 \\\end{bmatrix}$$This however has a major draw back in that the system is no longer symmetric and so we could no longer use preconditioned conjugate gradient (or other symmetric solvers). One interesting solution that I came across is the Method of Large Numbers which I found in the book Programming Finite Elements in Java by Gennadiy Nikishkov. This method uses the fact that double precision only contains around 16 digits of accuracy. Instead of putting a 1 in the $K_{11}$ position we place a large number. For example our system becomes:$$K = \begin{bmatrix} 1.0e64 & 2 & 0 & -1 & 0 \\ 2 & 4 & 1 & 0 & 0 \\ 0 & 1 & 6 & 3 & 2 \\ -1 & 0 & 3 & 7 & 0 \\ 0 & 0 & 2 & 0 & 3\end{bmatrix}\hspace{5mm}\text{and right-hand side vector}\hspace{5mm} b = \begin{bmatrix} c\times{1.0e64} \\ b2 \\ b3 \\ b4 \\ b5 \\\end{bmatrix}$$The advantages of this method are that it maintains the symmetry of the matrix while also being very efficient for sparse storage formats. My questions then are as follows:How are Dirichlet boundary conditions typically implemented in finite element codes for heat/fluids? Do people use the method of large numbers usually or do they do something else? Is there any disadvantage to the method of large numbers that someone can see? I am assuming that there is probably some standard efficient method used in most commercial and non-commercial codes that solves this problem (obviously I not expecting people to know all the inner workings of every commercial finite element solver, but this problem seems basic/fundamental enough that someone likely has worked on such projects and could provide guidance).
How to efficiently implement Dirichlet boundary conditions in global sparse finite element stiffnes matrices
finite element;sparse;boundary conditions
In deal.II (http://www.dealii.org -- disclaimer: I'm one of the principal authors of that library), we do eliminate whole rows and columns, and it is not too expensive overall. The trick is to use the fact that the sparsity pattern is typically symmetric, so you know which rows you need to look into when eliminating a whole column.The better approach, in my view, is to eliminate these rows and columns in the cell matrices, before they are added to the global matrix. There you work with full matrices, so everything is efficient.I have never heard of the large-numbers approach and would not use it because surely it will lead to terribly ill-conditioned problems.For reference, the algorithms we use in deal.II are described conceptually in lectures 21.6 and 21.65 at http://www.math.tamu.edu/~bangerth/videos.html . They closely match your description.
_unix.175869
I have installed kali linux in virtual box with a windows host, and when I try to update kali it completes 5-10 packages and aborts saying connection failed. I have a slow connection and want to get a manual update and to know how to install it manually.
How to update kali without internet connection manually?
upgrade;kali linux
null
_webapps.25365
I click Hide all by CityVille on my smart list and it seems to work. The stories disappear the message below appears:Stories hidden. UndoStories from CityVille won't appear in your News Feed anymore. However, when I reload the list, I still see these stories. I also don't think this is an eventual consistency matter since I've been trying to hide the stories for days.Is CityVille getting some sort of special treatment from Facebook? Are they hacking their way in my lists in spite of Facebook (very very unlikely)? Is there any way to get rid of them?
How do I hide CityVille stories in smart lists for real?
facebook;spam prevention
null
_unix.301702
I was trying to use a tool a tool written in java called fastqc (for people who are interested in what is fastqc. when I tried typing the command : fastqc I got the error: Exception in thread main java.lang.NoClassDefFoundError: uk/ac/babraham/FastQC/FastQCApplicationCaused by: java.lang.ClassNotFoundException: uk.ac.babraham.FastQC.FastQCApplication at java.net.URLClassLoader$1.run(URLClassLoader.java:217) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:323) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294) at java.lang.ClassLoader.loadClass(ClassLoader.java:268)when someone had similar previously,some one suggested that in similar case, I need to set the class path to the directory which contains FastQC installation: and depending on having a standard class path or non-standard classpath on my machine, I need to append existing classpath like: java -Xmx250m -classpath /usr/local/FastQC uk.ac.bbsrc.babraham.FastQC.FastQCApplicationor java -Xmx250m -classpath /usr/local/FastQC:$CLASSPATH uk.ac.bbsrc.babraham.FastQC.FastQCApplicationSince my directory which contains the FastQC is /u32/myusername/Tool/FastQCso I tried both: java -Xmx250m -classpath /u32/myusername/Tool/FastQC uk.ac.bbsrc.babraham.FastQC.FastQCApplicationand java -Xmx250m -classpath /u32/myusername/Tool/FastQC:$CLASSPATH uk.ac.bbsrc.babraham.FastQC.FastQCApplicationbut none of them seemed to work. Did I mess something up? I am not sure about what -Xmx250m means, with or without it, the path setting did not work. Sorry for my ignorance. Any idea or suggestion appreciated.
Setting classpath in Java
java
null
_unix.355208
Starting from a base script like: import webbrowserurl = 'http://www.google.com'webbrowser.open_new_tab(url) (How can I call the print function to be opened in another terminal?)What happened? I simply opened google.com but now, I would like to get in the same code the possibility to print out the pages opened in the browser as a normal browsing activity would going on. I explain better myself script.py I get google.com --- at the same time would be great opening a terminal and printing the URL, and even opening a new tab in terminal would happen : tab0: google.com tab1---yahoo.com, I close tab0 and prints--tab0 closed.Reference:Urllib2?? something helphttps://askubuntu.com/questions/338294/output-url-of-open-firefox-tabs-in-terminal
Output URL of open tabs in python 3.6.1 (windows)
bash;python;firefox;chrome;python3
null
_unix.286403
I've enabled svm and iommu in the bios, but I get not available from dmesg:root@xen:~# dmesg |grep -i iommu[ 0.000000] Command line: placeholder root=UUID=0b6a99ef-b56b-4d71-9f63-4895d0276674 ro nouveau.blacklist=1 amd_iommu=on iommu=pt iommu=soft iommu=1 pci-stub=10de:1401,10de:0fba[ 0.000000] Kernel command line: placeholder root=UUID=0b6a99ef-b56b-4d71-9f63-4895d0276674 ro nouveau.blacklist=1 amd_iommu=on iommu=pt iommu=soft iommu=1 pci-stub=10de:1401,10de:0fba[ 5.177737] AMD IOMMUv2 driver by Joerg Roedel <[email protected]>[ 5.177744] AMD IOMMUv2 functionality not available on this systembios settings (sorry for blurriness):system info:root@xen:~# uname -aLinux xen 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:33:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linuxroot@xen:~# cat /etc/lsb-release DISTRIB_ID=UbuntuDISTRIB_RELEASE=16.04DISTRIB_CODENAME=xenialDISTRIB_DESCRIPTION=Ubuntu 16.04 LTSroot@xen:~# dmidecode |grep -i product Product Name: To be filled by O.E.M. Product Name: 990FXA-UD5 R5root@xen:~# grep Processor /proc/cpuinfo |tail -1model name : AMD FX(tm)-8300 Eight-Core Processorroot@xen:~# grep iommu /etc/default/grub GRUB_CMDLINE_LINUX_DEFAULT=nouveau.blacklist=1 amd_iommu=on iommu=pt iommu=soft iommu=1 pci-stub=10de:1401,10de:0fbaDo I need to update the motherboard bios? It's currently at F3; if possible, I'd like to avoid it because it might brick the motherboard.
How to enable IOMMU on Gigabyte 990FXA-UD5 R5
linux;virtual machine;bios
null
_unix.253026
I have 168307 jpg photos in one folder - result of a recovery from an accidentally formatted hard drive. Casual browsing shows that 80% of files have been recovered ok, most even have valid EXIF data (incl. timestamp), some are partially recovered (a part of image missing but still usable), some are totally useless (most image wasn't recovered). All of the files have random numeric names and all have same date & time in the file system. As such they are unusable. What I want to do is:create a set of thumbnails to browse manually through them and fairly quickly remove files that are useless,using the preserved EXIF tags to automatically sort remaining images into a neat tree of folders (year/month/day/pics like structure - or a set of folders with YYYY-MM-DD as file name). What tools would you recommend for such a task? Should I try something like digikam for the first part and some command line tools for the second?
Sort & organize a huge heap of photos
images
null
_unix.45758
I am writing for some help regarding Postfix configuration. I cannot seem to get Postfix configured properly to transfer mail to the mailing list installed on the same server. I followed many steps over the last few days, and the last one I followed is at http://www.postfix.org/VIRTUAL_README.html under the section Mailing Lists.Can someone please look at this and let me know what I am missing?Basically, Postfix has been configured for base email to be sent to [email protected] and I would like the mail list to use [email protected].**DYN-DNS** listtest.company.org A 216.111.222.85 listtest.company.org MX 216.111.222.85 listtest.company.org TXT v=spf1 a ptr mx ip4:216.111.222.85 mx:mail-test.company.org -allmail-test.company.org A 216.111.222.85 mail-test.company.org MX 216.111.222.85 mail-test.company.org TXT v=spf1 a ptr mx ip4:216.111.222.85 mx:mail-test.company.org -all**main.cf**myhostname = mail-test.company.orgmydomain = company.orgmyorigin = $hostnamealias_maps = hash:/etc/aliases, hash:/etc/mailman/aliasesalias_database = hash:/etc/aliases, hash:/etc/mailman/aliases recipient_delimiter = +virtual_alias_maps = hash:/etc/postfix/virtual mydestination = $myhostname, listtest.$mydomain/etc/postfix/virtual: [email protected] listname-request [email protected] listname [email protected] owner-listname/etc/aliases: listname: /usr/lib/mailman/mail/mailman post mailman owner-listname: ... listname-request: ...**mm_cfg.py**DEFAULT_URL_HOST = 'listtest.company.org'DEFAULT_EMAIL_HOST = 'listtest.company.org'add_virtualhost(DEFAULT_URL_HOST, DEFAULT_EMAIL_HOST)MTA = 'Postfix'The first part of the log shows the rejection of listtest.company.org -- whereas the second part shows successful transfer to mail-test.company.org/var/log/maillogAug 17 15:46:50 listserv postfix/smtpd[19870]: NOQUEUE: reject: RCPT fromMail1.company.org[66.173.196.101]: 554 5.7.1 <[email protected]>: Relay access denied; from=<[email protected]> to=<[email protected]> proto=SMTP helo=<MAIL1.company.ORG>Aug 17 15:46:50 listserv postfix/cleanup[19877]: D3F93209F1: message-id=<[email protected]>Aug 17 15:46:50 listserv postfix/smtpd[19870]: disconnect from Mail1.company.org[66.173.196.101]Aug 17 15:46:50 listserv postfix/qmgr[19197]: D3F93209F1: from=<[email protected]>, size=6670, nrcpt=1 (queue active)Aug 17 15:46:50 listserv postfix/cleanup[19877]: F37B120A3B: message-id=<[email protected]>Aug 17 15:46:51 listserv postfix/qmgr[19197]: F37B120A3B: from=<[email protected]>, size=6819, nrcpt=1 (queue active)Aug 17 15:46:51 listserv postfix/local[19878]: D3F93209F1:to=<[email protected]>, relay=local, delay=0.18,delays=0.17/0.01/0/0, dsn=2.0.0, status=sent (forwarded as F37B120A3B)Aug 17 15:46:51 app02-listserv postfix/qmgr[19197]: D3F93209F1: removedAny help would be greatly appreciated.
Mailman / Postfix Configuration Assistance
rhel;alias;postfix;mailman
null
_unix.156784
I am trying to teach myself to write Shell Scripts on my Raspberry Pi, but I am struggling to make a menu where a user can choose from these different options:display a list of current usersdisplay a list of all files including hidden files in the home directoryoutput a calendar for the current monthquit the script.I am aware that some kind of loop is also needed, any suggestions guys?
New to linux, learning shell scripts
linux
There is an excellent tool for managing dialogs named dialog ;). I don't know is it installed on your raspberry but it can be surely compiled for.Here is an article about it's features with examples:http://www.linuxjournal.com/article/2807
_unix.263783
when I installed the updates on my computer (Ubuntu 14.04), I typed the password, thinking that it was asked for regular updating , but when I noticed some strange behavior and crash at this moment, I suspected the malicious activity. I checked if there were some modified filesfind /sbin -mtime -1and it showed me :/sbin/sbin/ldconfig.real/sbin/ldconfigI checked then for rootkits with : chkrootkit | grep INFECTEDand it showed nothingNevertheless I worry about ldconfig ldconfig.real files, and so I'm looking for the methods to update them in such a way that last changes (possible malicious activity) will be deleted . when I try to reinstall ldconfig , I have this error while removing with apt-getE: Unable to locate package ldconfig
how to fix potentially infected binary files?
ubuntu;security;software installation;binary
Both files come from libc-bin$ dpkg -S /sbin/ldconfig{,.real}libc-bin: /sbin/ldconfiglibc-bin: /sbin/ldconfig.realSo you could reinstall with:sudo apt install --reinstall libc-binBut if something that fundamental as libc is really infected, you're not going to be able to remove it from a live system. It could trivially monkey-patch anything linking to it to just reinfect your computer. You could probably chroot-mount it from a LiveCD and reinstall everything... Or just reinstall from scratch and copy your (checked and sanitised) data over.But are you really infected in the first place? I don't know why you think you are. There have been libc patches recently (they are usually fairly frequent IME) so I'm not sure what you're seeing is anything but standard stuff.I really think you're unnecessarily bridging what is more likely to be a bad update, random bug, a service that reloaded onto a new version of libc, etc into a disaster scenario. Especially when we're talking about some warnings without knowing what they were. Warnings happen all the time.You only have a few options:Audit the files from a safe environment (ie a Live CD/USB). If yours claim to be the same version as the originals but their md5sum (or sha256sum, however paranoid you want to be) differ, you have a problem.Assume disaster and reinstall.Take the blue pill, the story ends, you wake up in your bed and believe whatever you want to believe. Ignorance is bliss, right?
_codereview.74550
I have just started using Python, and I am attempting to make a prime number sequence generator, where it will print the a specified amount prime numbers in terminal. I have other versions of this also, and versions for the Fibonacci sequence, although, I will post just the version for prime numbers I specified above. P = 2 Count = 1 X = int(raw_input('choose number: ')) def Main(P, X): while Count <= X: isprime = True for x in range(2, P - 1): if P % x == 0: isprime = False if isprime: print P Count += 1 P += 1I am currently trying to optimize this code so that it runs as fast as possible, and then making small edits. I did this by putting a get daytime now function at the beginning and the end of the sequence generator, and printing the time, then looping it all a specified amount of times.from datetime import datetime as dtP = 2Count = 1Count2 = 1X = int(raw_input('choose number: '))def Main(P, Count, X): t1 = dt.now() while Count <= X: isprime = True for x in range(2, P - 1): if P % x == 0: isprime = False if isprime: Count += 1 P += 1 t2 = dt.now() print ((t2-t1).microseconds)while Count2 <= 20: Main(P, Count, X) Count2 += 1As far as my knowledge of Python extends, I have optimized this code so it runs quite efficiently. However, I want to know if anyone can help make this code any better, however, it needs to stay within one function (two if necessary), and it does the same type of thing. Also, if it is possible to explain why it does better, that would be appreciated. However, any comment or feedback would be nice.
Prime Number Sequence generator
python;beginner;primes
A logical optimization here would be to remember the primes you have already calculated. Consider the theory:A prime is a number that is divisible by itself and 1 onlyIt follows that, to test if any number X is prime, you only need to find 1 prime number less than X which divides in to X without a remainder. There is no need to test non-prime numbers, because if a non-prime divides cleanly in to X, then the prime factors would also divide in to X.So, if you keep a record of the previously calculated primes, then you only need to scan those values to see if they divide in to X. In essence, each time you print a prime, also add it to a list.This will require 'seeding' the prime list with the value 2.A second optimization is that a number X is only prime if it has a factor. A factor is a number, multiplied by another number, that is equal to the original value X.The useful theory here, is that, as the value of the first factor increases, the value of the second factor decreases. There is a point when the first and second factors 'cross over' and the second factor becomes less than the first.The cross-over point is the square-root of the number X. When you pass the square-root of the number, you have tested all the possible factors... there's no need to scan values larger than the root, because, if they were factors, you would have found them already by identifying the small factor that matches the larger factor.Putting these two items together, you should modify your code to:Have a special case for 2, which is prime, and store it in the seed array.preserve the prime numbers you find in the same array.for values larger than 2, you only need to use values from the pre-identified prime array to test for factorsyou only need to look for prime factors that are less than, or equal to the square-root of the value.
_softwareengineering.117825
In my team, people have tendency to develop a POC (which is very close to actual deliverable in terms of features) which takes good amount of time to be created. And then spend a significant time to refactor the POC so that it matches the design principles using all required design patterns, sometimes naming etc... One advantage everyone in team says is you have the confidence to meet deadlines one so called POC is ready, then you can spend time on design.Just curious about, is it really good to refactor code after developing it in quick mode or we should spend time initially to work on architecture and design of the code?EDIT:After reading the answers I realized that, as most of guys said, what I am talking of is more than POC and as rightly put by Carl is an evolutionary prototype. This is definitely not a throwaway code. Intention of the output is always to go to production.
Is it ok to write a quick software programme and then refactor it?
refactoring;methodology
null
_unix.213193
I'm working in an embedded Linux system trying to get it booting its root file system in ram using initramfs. The system comes up for the most part but then has trouble in the init scripts. I've narrowed the problem down to the following.The system cannot recognize any relative paths. Let me explain more...Not only are symlinks that point to files in relative locations broken, but simply running a simple command like such doesn't work:$ pwd/etc/network$ cat ../inittabcat: can't open '../inittab': No such file or directoryBut this works fine:$ cat /etc/inittab<inittab output ...>Any idea what could be going on?UPDATE1A standard ls .. command appears to function as expected. Also, the inode references look ok I believe? $ ls .. default/ inputrc moduli random-seed ssh_config sshd_config dhcp/ issue mtab@ resolv.conf@ ssh_host_dsa_key ssl/ fstab ld.so.conf network/ rsyslog.conf ssh_host_dsa_key.pub sysconfig/ fstab.bak ld.so.conf.d/ nsswitch.conf rsyslog.d/ ssh_host_ecdsa_key ts.conf group logrotate.conf os-release screenrc* ssh_host_ecdsa_key.pub udev/ hostname logrotate.d/ passwd securetty ssh_host_key hosts ltrace.conf passwd- services ssh_host_key.pub init.d/ memstat.conf profile shadow ssh_host_rsa_key inittab mke2fs.conf protocols shadow- ssh_host_rsa_key.pub $ cd / ; ls -lid /etc 1547 drwxr-xr-x 12 root root 0 Jan 1 00:49 /etc/ $ cd /etc ; ls -lid . 1547 drwxr-xr-x 12 root root 0 Jan 1 00:49 ./ $ cd /etc/network ; ls -lid .. 1547 drwxr-xr-x 12 root root 0 Jan 1 00:49 ../With even more digging, I've discovered that relative paths work AS LONG AS you do not cross the boundry of the root of the file system:$ cd usr/$ ls ../etcls: ../etc: No such file or directory$ cd ../etc$ cd network/$ ls ..default/ inputrc moduli random-seed ssh_config sshd_configdhcp/ issue mtab@ resolv.conf@ ssh_host_dsa_key ssl/fstab ld.so.conf network/ rsyslog.conf ssh_host_dsa_key.pub sysconfig/fstab.bak ld.so.conf.d/ nsswitch.conf rsyslog.d/ ssh_host_ecdsa_key ts.confgroup logrotate.conf os-release screenrc* ssh_host_ecdsa_key.pub udev/hostname logrotate.d/ passwd securetty ssh_host_keyhosts ltrace.conf passwd- services ssh_host_key.pubinit.d/ memstat.conf profile shadow ssh_host_rsa_keyinittab mke2fs.conf protocols shadow- ssh_host_rsa_key.pub$ ls ../../usrls: ../../usr: No such file or directoryThis leads me to believe that I have not properly mounted the root filesystem. Perhaps this output is the most telling of that?$ dfFilesystem Size Used Available Use% Mounted ondevtmpfs 204.2M 0 204.2M 0% /devtmpfs 251.7M 0 251.7M 0% /dev/shmtmpfs 251.7M 76.0K 251.6M 0% /tmpUPDATE2After additional searching, I believe the following best describes my scenario:2) The newer initial ramfs image, initramfs. Here one populates a directory, and then creates a compressed cpio archive which is expanded into ramfs upon boot and becomes the root filesystem. The kernel must be configured with CONFIG_BLK_DEV_INITRD=y but one does not need to set CONFIG_BLK_DEV_RAM_SIZE, nor does one need to set CONFIG_TMPFS=y. When the system is up, df does not report the root filesystem and one cannot interact with it by doing things like mount --bind / dir. Also the distinction between what RAM is set aside for the filesystem and what RAM is used for processes is blurred. df reports nothing and free reports total usage without distinction, ie. used RAM = RAM used for files (as reported by du) plus RAM used for processes.However, I am a bit surprised by this. Does this imply I will not be able to interact around the root of the file system when using initramfs?UPDATE3This post indicates that what I am trying to accomplish is not unreasonable:Now normally an initramfs is temporary, only used to run some programs extremely early in the boot process. After those programs run, control is turned over to the real filesystem running on a physical disk. However you do not have to do that. There is nothing stopping you from running out of the initramfs indefinitelyHow can I run out of the initramfs indefinitely but yet also be able to traverse across the root of the file system?
Relative path to anything not working (while running from initramfs)
linux;path;embedded;busybox;initramfs
null
_unix.27666
Sometimes you run a program from the terminal, say, lxpanel†. The terminal won't drop you back to the prompt, it'll hang. You can press Ctrl+C to get back to the prompt, but that will kill lxpanel. However, pressing Alt+F2 (which pops up a window to take a command) and running lxpanel works gracefully.Why is this? What is different between running a command from the terminal and from the 'run' window that appears when you press Alt+F2?† lxpanel here was just used as an example. I have experienced this with multiple programs
Why do some commands 'hang' the terminal until they've finished?
shell;command line;jobs
By default the terminal will run the program in the foreground, so you won't end up back at the shell until the program has finished. This is useful for programs that read from stdin and/or write to stdout -- you generally don't want many of them running at once. If you want a program to run in the background, you can start it like this:$ lxpanel &Or if it's already running, you can suspend it with Ctrl+Z and then run bg to move it into the background. Either way you will end up with a new shell prompt, but the program is still running and its output will appear in the terminal (so it can suddenly show up while you're in the middle of typing)Some programs (typically daemons) will fork a separate process when they start, and then let the main process immediately exit. This lets the program keep running without blocking your shell
_unix.345511
I am using the :vim COMPANY_ID ~/Projects/creditdutile/loanrabbit/* | cw command to look for the word COMPANY_ID in the loanrabbit directory. However, that command look for just for file I guess, not in subdirectories. How could I make a global research with that command?
Search in file, but not into subdirectories
vim
I assume you're invoking that command from inside Vim. You can use ** to search a directory tree. i.e.:vimgrep COMPANY_ID ~/Projects/creditdutile/loanrabbit/** | cwSee :h starstar-wildcard for the full documentation on **. Also note that you can use ** as part of a path. For example I often search some templates with::vimgrep h1 temp**/*.htmland it matches both templates/foo.html and temp/extra/templates/bar.htmlShameless marketing: we have a Vi & Vim stack exchange community
_codereview.63130
Just as a learning exercise, I set out making a stopwatch without looking up how to do it etc.I know it will have been done many times before. I'm just looking for some feedback on what I should do to make the code more efficient / cleaner / in keeping with standards etc.This is the result// declare varsvar secondsDiv = $(#seconds);var minsDiv = $(#mins);var hoursDiv = $(#hours);var interval = null;var timer = false;// return the value of a given divfunction getCurrentValue(value) { return value.html();}// reset the value of a chosen div to 00function resetValue(value){ value.html(00);}// check if values are more than 59 to progress the timerfunction check59() { var currentSec = getCurrentValue(secondsDiv); var currentMins = getCurrentValue(minsDiv); var currentHours = getCurrentValue(hoursDiv); // check the seconds to become a minute if (currentSec > 59) { currentMins++; if (currentMins < 10) { minsDiv.html(0 + currentMins); } else { minsDiv.html(currentMins); } resetValue(secondsDiv); } // check the minutes to become an hour if (currentMins > 59) { currentHours++; if (currentHours < 10) { hoursDiv.html(0 + currentHours); } else { hoursDiv.html(currentHours); } resetValue(minsDiv); }}// add secondsfunction addSecond() { var currentSec = getCurrentValue(secondsDiv); currentSec++; if (currentSec < 10) { secondsDiv.html(0 + currentSec); } else { secondsDiv.html(currentSec); } check59();} // run the initial addSecond function every second$(#startTimer).click(function(){ if (timer===false) { timer = true; interval = setInterval(addSecond, 1000); }});// stop the addSecond function every second$(#pauseTimer).click(function(){ clearInterval(interval); timer = false;});// reset all values$(#clearTimer).click(function(){ resetValue(secondsDiv); resetValue(minsDiv); resetValue(hoursDiv);});
JavaScript / jQuery stopwatch
javascript;jquery;timer
null
_unix.8766
I'm using rsync and the flags -nPaAXz ~/ to check which files are going to be copied.This is far too verbose to make any sense of.How could I filter the output so I view the list of files/folders that are going to be copied to a certain depth, eg:1 folder deep/home/afile/home/afolder//home/anotherfolder/2 folders deep/home/afile/home/afolder/afile/home/afolder/anotherfile/home/afolder/afolder//home/anotherfolder/afile
Filtering paths to a specific depth
grep;sed;rsync;regular expression
This command takes each path and truncates it to n folders deep (defined in the \{0,n\} section of the sed command and the {0,n} section of the grep command). It's then piped into uniq to filter out the duplicates.rsync -nPaAXz src_dir dst_dir | sed -n 's@^\(\([^/][^/]*/\)\{0,2\}\).*@\1@p' | uniqThe same thing can also be achieved using grep:rsync -nPaAXz src_dir dst_dir | grep -oE ^([^/]+/){0,2}Although the above wont work with GNU grep versions < 2.5.3 due to a bug.
_webapps.48266
I'm trying to find a way of getting the location of friends of friends (town/city and country) and plot them on a map.I can easily search for Friends of my friends but is there a way of exporting the results to CSV, json, or some other easily parsed format?
Is it possible to export data from Facebook's graph search?
facebook;facebook graph search
null
_unix.289814
I am using a simple for loop to process certain input files and get the output in one file. What I am using is for k in ../some_directory/*.txt; do command (containing -i $k -o outputfile.txt); doneNow each loop gives an output. I want the output to be written in one file. This loop just replaces all the previous files and gives me a number of outputfile.txt files each with the output from every loop. How can I append the command to one file? I don't want the screen output but the output from each of the command.NOTE: I am not talking about this or this
Appending output of command in for loop
shell script;files
Just thought of a simpler solution. I just needed to give the same file name as output as the input. That solved my problem as all the changes get appended and the old output file gets backed up.Thanks
_softwareengineering.209691
I got surprised when I visited some sites with an 'aspx' extension at the end of their URLs and when I looked at their html source I didn't see any view state like the follwing:<input type=hidden name=__VIEWSTATE id=__VIEWSTATE value=SNIKalxBOk0/lp+SgXklgi/0/IUoRXTjEjp6NrL2ColFXGht1bTDit5V+wHdkcuM3YVmVNKG1jpM6zAg+MQCnvPDvlEvK8RNwHblq8NN1Ys= />How did they prevent this to happen? even if you turn the view state off you'll get at least of of the above input in your HTML output. Here is one of the examples that I looked at: http://www.ada.org/index.aspx
ASP.NET without viewstate input, How comes?
asp.net
The site, or at least the pages I clicked on, are almost certainly not using WebForms. One of the key give-aways is the complete lack of a single top-level form such as:<body> <form method=post action=/>That combined with the lack of __VIEWSTATE and __EVENTTARGET and __EVENTARGUMENT hidden inputs seems fairly conclusive. However looking at the HTML for the site the following jumps out at me:<span id=ADASlideShow1_rptSlideshow_ctl03_lblVideoType style=display: none;>None</span>The id is typical webforms output so this would suggest that either:They have ported an ASP.NET WebForms site over to some other technology (possibly just plain HTML contained in a .aspx file - as the previous poster mentioned the functionality seems to be done using Flash and jQuery) and retained the HTML structure and ids in order to keep the CSS and Javascript in working condition.Or they are using ASP.NET WebForm controls but with all ViewState and control interactions turned off - however I'm fairly sure that without the top level form tag webform controls just won't work at all (however it's been a while since I did any webforms work so I could be proved wrong).
_unix.244799
Some flac files apparently have a cuesheet metadata block. I know how to split flacs files with shnsplit when I have a separate cuesheet at hand (cf. How do I split a flac with a cue?), but how do I split a flac when the cuesheet is stored inside a metadata block of the flac file?Command-line preferred.
Splitting a flac from a cuesheet metadata block
command line;audio;flac
By exporting the cue-sheet to a file first. For example, metaflac has an --export-cuesheet-to=FILE option.From man metaflac:Export CUESHEET block to a cuesheet file, suitable for use by CD authoring software. Use '-' for stdout. Only one FLAC file may be specified on the command line.For example:f='file.flac'bn=$(basename $f .flac)cue=$bn.cue[ ! -e $cue ] && metaflac --export-cuesheet-to=$cue $fshnsplit -f $cue -t '%n-%t' -o flac $f
_unix.23263
I have attached a new LCD to my embedded Linux device and when I run the system I found that it is shifted to the right. (the display starts from the middle of the LCD)I found 2 frame buffer drivers under Linux kernel driver and modify in following areas:#ifdef CONFIG_TOPPOLY_TD035TTEA3_320X240 hsync_len : 64, vsync_len : 6, left_margin : 125, upper_margin : 70, right_margin: 115, lower_margin : 36, sync: 0, cmap_static: 0, #endifBut the problem is still there. What should I do?
Embedded linux LCD not calibrated
drivers;embedded;arm;display settings;framebuffer
null
_softwareengineering.71264
Software development techniques exist to solve problems. I think a key problem we face is conquering complexity. Also, software developers must often classify and understand complex systems, separating accidental complexity from essential complexity. I believe that sufficiently useful definitions of these terms all exist on Wikipedia.My question is: What techniques are most valuable in conquering complexity, as a professional software developer, and/or software architect?Answer examplar; a blog post on conquering complexity that seems to be coming at things from a java/c++/OOP centric perspective.
Conquering Complexity: Valuable techniques
architecture;complexity
YAGNI. The best way to avoid accidental complexity is to stop making stuff more generic and flexible than they have to be. For instance, don't start looking for frameworks and libraries until you actually know that you need them. Instead of solving todays problems, we spend time thinking up potential problems that might arise in the future. Don't do that. Focus on today.
_unix.123674
Can I see images and watch movies inside the terminal emulator? In case of virtual console I can do it via framebuffer, but what about terminal emulators?
Can I see images and watch movies inside the terminal emulator
video;images;terminal emulator
null
_codereview.104966
I'm trying to parse an object generated from an Excel file. The output lists each cell with its contents. If the cell is just a number then it remains a number but if the cell contains a formula (has attribute f) I want to make that a getter so whenever that cell is called the result is updated in case the other cells change.var Sheet = function Sheet(obj) { var i; for (i in obj){ if (obj[i].f !== undefined){ this['_'+i] = obj[i].f; } else { this[i] = obj[i].v; } }}var SheetConstructor = function(obj){ var new_sheet = new Sheet(obj); var getters = Object.keys(new_sheet).filter( function(attr){ if (attr.charAt(0) === '_'){ return attr } }); for (g in getters){ Object.defineProperty(new_sheet, getters[g].substring(1), { get: function(){ return eval(new_sheet[getters[g]]); } }); } return new_sheet;}Input object:{ B2: { t: 'n', v: 20, w: '20' }, C2: { t: 'n', v: 115, w: '115' }, B3: { t: 'n', v: 400, f: 'this.B2*20', w: '400' }, C3: { t: 'n', v: 600, w: '600' }, B5: { t: 'n', v: 20, w: '20' }, D6: { t: 'n', v: 22, w: '22' }, D7: { t: 'n', v: 36, w: '36' }, B8: { t: 'n', v: 26.666666666666668, f: 'this.B2 * this.C2', w: '26.66666667' }, D8: { t: 'n', v: 153, f: 'this.B5 + this.D6 + this.D7', w: '153' }}I know the security implications of eval() and am not worried about them in this case. This setup currently works but eventually I will have references across multiple sheets so I wanted some feedback on my solution.
Getters, constructors and eval
javascript;excel
null
_unix.324389
My Shell script include series of steps for example first stepApp= read -p ### Please enter Application name Env = read -p ### Enter Enviornment name (Dev,test)second stepcd /opt/Weblogic/mkdir $Appmkdir $EnvThird Step cp /tmp/weblogic/* /opt/weblogic/$App/$Env/*So my question is how can I record what user is entering each time? Is there a way I can store the user the whole input and output to something call temp.txt? This way I can review to find out which user has enterred which input.I hope my question is clear.
How can I record Shell script outputs to log file
shell script;shell
null
_unix.222868
I have a directory with a very large number of subdirectories (~800) that were generated programmatically. I want to get a count of the number of files in each of these subdirectories to check for anomalies (if the code broke on a run then some of the files will be missing). What's a quick way to do this? The sort of output I'm looking for is: Name_of_Folder_1 [# of files in Folder 1] Name_of_Folder_2 [# of files in Folder 2]...
Get number of files in each directory
shell script;ls
Assuming that you have no spaces in your directory names:for dir in $(find . -type d); do echo ${dir}: $(find ${dir} -maxdepth 1 -type f | wc -l)done
_codereview.2988
I've been playing around with Python off and on for about the past year and recently came up with the following 68 (was 62) lines. I think I'll try making a calculator out of it. I'd really like to know what readers here think of its attributes such as coding style, readability, and feasible purposefulness.# notes: separate addresses from data lest the loop of doom comethclass Interpreter: def __init__(self): self.memory = { } self.dictionary = {mov : self.mov, put : self.put, add : self.add, sub : self.sub, clr : self.clr, cpy : self.cpy, ref : self.ref } self.hooks = {self.val(0) : self.out } def interpret(self, line): x = line.split( ) vals = tuple(self.val(y) for y in x[1:]) dereferenced = [] keys_only = tuple(key for key in self.memory) for val in vals: while val in self.memory: val = self.memory[val] dereferenced.append(val) vals = tuple(y for y in dereferenced) self.dictionary[x[0]](vals) def val(self, x): return tuple(int(y) for y in str(x).split(.)) def mov(self, value): self.ptr = value[0] def put(self, value): self.memory[self.ptr] = value[0] def clr(self, value): if self.ptr in self.hooks and self.ptr in self.memory: x = self.hooks[self.ptr] y = self.memory[self.ptr] for z in y: x(z) del self.memory[self.ptr] def add(self, values): self.put(self.mat(values, lambda x, y: x + y)) def sub(self, values): self.put(self.mat(values, lambda x, y: x - y)) def mat(self, values, op): a, b = self.memory[values[0]], self.memory[values[1]] if len(a) > len(b): a, b = b, a c = [op(a[x], b[x]) for x in xrange(len(b))] + [x for x in a[len(a):]] return [tuple(x for x in c)] def cpy(self, value): self.put(value) def out(self, x): print chr(x), def ref(self, x): self.put(x)interp = Interpreter()for x in file(__file__.split('/')[-1].split(.)[-2] + .why): interp.interpret(x.strip())
Simple Language Interpreter
python;interpreter
To allow your module to be loadable by other files, it's customary to write the end of it with a if __name__ == '__main__': conditional like so:if __name__ == '__main__': interp = Interpreter() for x in file(__file__.split('/')[-1].split(.)[-2] + .why): interp.interpret(x.strip())Maybe I'm being picky (but you did ask for style input), read PEP8 and try to follow it as best you can (stand). One thing that jumped out at me right away was your 2 space indentation vs. the PEP8 recommendation of 4. One letter variables are usually only recommended for looping vars. You could probably increase the readability of your code by renaming some of those x's, y's, a's, etc.Another maxim of Python programming is to use the tools provided, I was pondering what you were doing with:__file__.split('/')[-1].split(.)[-2] + .whyan alternative that uses existing Python modules (and is more portable across platforms) is:os.path.splitext(os.path.basename(__file__))[0] + .whyIt's about the same length, and is a good deal more clear as to what you're doing as the function names spell it out.
_webapps.59770
I am trying to create a Google Document that has complex questions we ask clients. I want to add a link at the end of each question that will launch a pop-up for additional information.I currently have a .gs file that houses the script below:function showDialog() { var html = HtmlService.createHtmlOutputFromFile('Help File.html') .setWidth(400) .setHeight(300); DocumentApp.getUi() // Or DocumentApp or FormApp. .showModalDialog(html, <b>Hello World!</b> ); }I also have a .html file with the following code:< div>Hello, world! < input type=button value=Close onclick=google.script.host.close() />< /div>}Is there a way to embed this into a link on the Google Doc? Currently, I am able to click Run from the Google Apps Script to make the pop-up window work.
Create help pop-up in Google Document using Google Apps Script
google apps script;google documents
null
_webapps.369
If I search Google from different countries (e.c. google.de, google.co.uk, google.fr, etc.), will they all bring exactly the same search results? Will the order be different?
Google search from global sites
google search;geolocation
No. It gives priority to local results.For example if you look for apple in google.it, as first result, it gives:Apple Apple progetta e crea iPod e iTunes, computer Mac desktop e portatili, il sistema operativo >OS X ei rivoluzionari iPhone e iPad. www.apple.com/it/
_unix.139583
I have a Linux machine set up to forward IPv4 packets. I'm looking to do this:if packet matches both source and destination, forward to GW X.How do I specify the source field? Do I need to use iptables?
ip route match multiple fields
linux;routing
null
_vi.8425
I am new to Vim and I am trying to remap the four (arrow) navigation keys hjkl one step to the right on the keyboard to getj downk up l left; rightI am following the recommendations given in this answer[1], andI am using a norwegian keyboard where the ; key is replaced by an key.In my ~/.vimrc I have:nnoremap l hnnoremap lI have installed the repmo plugin, and I suspect that is the cause of the problems I have with this.So the problem is that the l key does not map to h (left); instead, when I press l, the cursor moves to the right.To debug, I tried to print out the actual mappings::map h gives:nx h & <SNR>9_repmo('h','l')<CR>:map l gives:n l <SNR>9_lastkeyx l <SNR>9_lastkeyFootnotes:[1] Answer to stackoverflow.com question: Vim users, where do you rest your right hand?
Remapping home row keys hjkl when using repmo plugin
key bindings
null
_scicomp.20684
I am having problems with solving a hyperbolic wave problem with Dirichlet BCs. I have tried reducing the time step sizes, which does not affect the results, and notices increasing the number of nodes makes the results worse. I have concluded the problem is with the boundary or certainly spatial.My code is 1D, and the grid is structured. I have used FVM with central differencing. At the boundaries I have simply set the term at the boundary equal to the Dirichlet condition (for instance: velocity at east face $v_e = A$, where $A$ is the Dirichlet BC).I was wondering if there are any ways using which I could get rid of the oscillations in my results by means of changing the way I am implementing the BC or any other quick fixes. I have also tried upwinding, and did not even obtain convergence.
Dirichlet BCs - alternative implementation methods
finite difference;boundary conditions;finite volume;discretization;wave propagation
null
_unix.203173
Is possible to configure a Linux computer to work as a network printer device ? I have an USB printer that I intend to share in the network like a native network printer device.Is that possible? How?NOTES:'Autonomous' network printers usually communicate with the protocol HP Jetdirect (Also known as Raw).I have a RS/6000 with AIX 5 that finds and works with any kind of 'autonomous' network printer. And I would like to expose through Linux (preferably Debian) an USB printer in the network, like any ordinary network printer (autonomous device) which I could access in AIX.EDIT:I need to do in AIX something like that, where 'my_printer_ip' is the Linux IP:$ netcat my_printer_ip 9100$ Hello remote USB printer plugged in a Linux !$ <Ctrl+D>
Linux as a network printer device (Raw, port 9100)
networking;aix;cups;printer
After some researches and tries...These network printers devices, could implement some protocols, being one of them the one called HP JetDirect, also known as Raw, JetDirect, either just 9100. It seems to be the most common protocol supported by network printers.A network printer configuration sample: The JetDirect protocol is just an ordinary network stream, and not a real protocol, at least in my tests. So, you don't need CUPS neither any kind of printer engine to have a Linux behaving like a network printer, all you need is a 'network stream server' like inetd (or xinetd), to listen to the port 9100 and redirect this stream to the printer stream.Consider a printer stream in the port /dev/lp0, where we could do something like that:$ echo Hi local legacy printer ! >/dev/lp0Now we could redirect the stream coming in the port 9100 to the /dev/lp0, just using the old school inetd:9100 stream tcp nowait cat > /dev/lp0So, in any other remote system (like AIX), we could get the legacy parallel (or USB) printer plugged in a Linux to work like a network printer:$ netcat linux_ip 9100$ Hello remote Parallel printer plugged in a Linux !$ <Ctrl+D>Of course, there are concurrency issues which beyond others solutions could be handled by CUPS configuring the local printer under a spooler.It worked for me !
_unix.345132
I am looking for the sed command to replace text like this [word1 word2] to nothing.I triedsed -i -e 's/[Word1 Word2]//g'It didn't work and replaced entire my text in disorder way.I would like to request you to help me to replace special characters like these.Thanking you,Punith.
SED command to replace [Word1 Word2] to nothing
linux;sed;regular expression;replace
null
_cs.44954
In my theory of computation class last Spring my professor said in passing that a programming language cannot be both fully recursive and polymorphic. I didn't think much of it till now? What does it mean to be fully polymorphic and why does that mean you a language can't be fully recursive?
Why can't a programming language be both fully recursive and polymorphic
programming languages;recursion;semantics
null
_webmaster.42400
Possible Duplicate:Does the Google spider render JavaScript? I'm writing an article that is broken up into sections, where the content of each section is hidden unless the user expands that section. To be more concrete, this is what I am talking about: http://jqueryui.com/accordion/#collapsible. In that example, the text for Section 1 is visible whereas the text for all of the other sections do not appear. My question is, will the text contained in those other sections be accessible to search engines?
Will text that appears dynamically (via javascript/jquery) be indexed by search engines?
seo;javascript;google search;jquery
null
_softwareengineering.50283
I have a personal web project I cut my teeth on learning how to program. I wrote it in PHP and learned as I went. I eventually I re-factored it to use MVC and removed all mixing of php/html.Right now it has no users, save myself, and it makes no money. I have a strong desire to rewrite the entire app. Which really isn't that large of an app.I have a lot of reasons why I should not rewrite it. I know that I should move forward. It's a working app now and it will only set me back to rewrite it. But I can't shake this feeling that I would be better off using a different programming language in the long run. That I'd enjoy it more. That I'd feel comfortable with it. I feel like my one good reason to rewrite my app is that I have a gut feeling that I should.PHP seems like a hack thrown together. I want to use a language that feels more elegant to me. Any feedback you have would be welcome.
One good reason for a rewrite
php;python;javascript;rewrite
If your the only user and there are no deadlines or constraints why not rewrite it. It sounds like mainly an academic exercise anyway so you can't really lose.
_cstheory.38087
The Calculus of Constructions is a very simple core functional language with dependent types. Per curry-howard isomorphism, it could, potentially, be very useful for writing programs and proofs. It, though, has a few problems: induction isn't derivable, it isn't possible to prove 0!= 1, and pattern matching on algebraic data structures take linear time. In order to solve those issues, practical languages such as Coq are based on the Calculus of Inductive Constructions instead, which add a layer of primitive datatypes on top of CoC. That, unfortunately, makes the core language very complex.An alternative solution to those problems is a new primitive, self, which is a construction that allows a type to reference its typed term. This construct, together with the Parigot encoding, and a slightly weakened but still useful notion of contradiction, is sufficient to solve the problems above. The proposed language, though, is still somewhat complex. In particular, it has different Pi types, complex kind machinery and requires a restricted form of recursion (for the Parigot encoding).Is it possible to be simpler? I.e., can the calculus of constructions with only self types and nothing else from this paper still be able to derive induction and employ the parigot encoding?
Are there simple core languages which are consistent and expressive?
type theory;lambda calculus;functional programming
null
_cstheory.12929
I want to compute a mixed strategy that will be the Nash Equilibrium of the game.I have used my knowledge in order to create the system for the mixed strategy.I concluded on a system with 3 variables and 5 constrains.I am not able to solve this system using the common Gaussian Elimination method.This system is a linear program from what I can imagine.I have searched google for similar examples but all the examples was on 2-player games with only 2 strategies per player.In those games was quite easy to compute the mixed strategy.I am thinking of using the simplex method for finding the NE but I am thinking that this is weird for such a small game...Are there simpler method that can be used in computing a NE profile?Thank you.
Compute Nash Equilibrium for 2-player games
linear programming;gt.game theory
We have developed a user-friendly browser-based system to input and solve 2-player strategic-form and extensive-form games:http://www.gametheoryexplorer.org/ (GTE)Currently, we support:finding all equilibria via polyhedral vertex enumeration (which works on the strategic-form representation, which is converted to in the case of extensive-form games; this uses David Avis' lrs http://cgm.cs.mcgill.ca/~avis/C/lrs.htmlW); andfinding one equilibrium using Lemke's algorithm (which works on the strategic-form representation or on the sequence-form representation for extensive-form games).You can use lrs separately offline to solve larger bimatrix games.The GTE project is under active development (supported by the Google Summer of Code in 2011, 2012, and 2014), so please provide feedback and/or let us know if you would like to contribute) [email protected] a paper that covers the basic theory and a number of methods for enumeration of equilibria, see D. Avis, G. Rosenberg, R. Savani , and B. von Stengel (2010).Enumeration of Nash Equilibria for Two-Player Games.Economic Theory 42, 9-37.For a paper that describes GTE and what it can do, seeR. Savani and B. von Stengel (2014).Game Theory Explorer - Software for the Applied Game Theorist.Computational Management Science, 29 pages, to appear. arXiv versionZouzias' answer gives a good description of how to use support enumeration, which works fine for small examples. The methods in the paper above and used in GTE will in general be much quicker than support enumeration for finding extreme equilibria. In addition, GTE will find the complete set of equilibria (which can include convex combinations of extreme equilibria) by finding maximal cliques in a bipartite graph.
_unix.323532
Is there anybody who knows that how to install package using yum on different directory but not in root(/) directory ?Whenever I'm using yum install package-name command by default it is installing package in root(/) directory but i want to install package in different directory.Even rpm -ivh -r /path/path package.rpm doesn't work for me. I'm getting error: open of docker-engine.rpm failed: No such file or directoryThank you.
Yum Install package-name to different directory
linux;centos;yum
null
_codereview.147108
I have made a small script which grabs data into a map from 80 CSV files and calculates some statistics like average, standard deviation etc. It's also adding some additional data to map from filename.Can you please check if it is a correct way to do so? The idea is to get a list of files in the folder using file-seq, map this to function which reads file lazy, while skipping the first line, convert all text to decimals using read-string, multiply all the data by 1e9 and then calculates all the necessary statistics.The script works perfectly. I am just concerned about the right style to write programs in Clojure since I am pretty new to it.Data in CSV files is just numbers in scientific format like 1.721e-9 written in one column.(def data (map (fn [fsc] (->> (io/reader fsc) (line-seq) (rest) (map read-string) (map #(* % 1e9)) ((fn [se] (let [x se x2 (map #(* % %) se) n (count se) sum-x (reduce + x) sum-x2 (reduce + x2) average (/ sum-x n) variance (- (/ sum-x2 n) (math/expt average 2))] (merge {:n n :average average :variance variance :st-dev (math/sqrt variance) :st-dev-sample (math/sqrt (/ (* n variance) (- n 1)))} (-> (.getName fsc) (clojure.string/split #\s) ((partial zipmap [:type :color :voltage :temperature])) (#(assoc % :voltage (read-string (re-find #[+-]?\d+ (% :voltage))))) (#(assoc % :temperature (read-string (% :temperature)))) ))))))) (->> (clojure.java.io/file data) (file-seq) (rest))))
Multiple files data processing in Clojure
csv;clojure;statistics
Don't forget about forConsider using for instead of map in places where you use an anonymous function with map. This particularly applies to the outer-most map, since with map what you are maping over is sort of hanging by itself at the end of the code.(def data (for [fsc (->> (clojure.java.io/file data) (file-seq) (rest))))] (->> ...)))In this case in particular, what you are processing is made more clear with for.Break the code up into (named) functionsIn a similar vein to using for, consider breaking the code up into named functions. While anonymous functions are obviously sufficient, a good name can bring a lot of clarity to your code.At minimum, I would put functions like #(* % %) inside a let or letfn:(let [square (fn [x] (* x x)] ...)But if you think you have a use for the same function in other places, make it a top-level definition:(defn square [x] (* x x))Consider using fn in favor of #(...)Personally, I eschew the use of #(...) reader syntax to define functions and just use fn instead. I think the #() syntax was a well-intentioned solution to a largely non-existant problem (verbose anonymous functions), and to the extent anonymous functions are verbose in Lisps, the #() syntax is a poor replacement. It's barely shorter than an equivalent fn form, arguably more difficult to grok (based on the questions I've seen surrounding it on stackoverflow), and has some fundamental limitations (e.g., can't be nested).Obviously, this is a very subjective view, and certainly not everyone agrees with it.Use comments to add clarityBe sure to use comments to provide high-level descriptions of lower-level operations. For example, there are a couple places where you use rest to skip the first element in a sequence. A comment in these places indicating why this element needs to be skipped would go along way.Likewise, consider adding comments for the major blocks of the code -- i.e., high-level descriptions of each of the loops. Simple one-liners should be sufficient for most of these. You might want a little more description for the mergeing part, though, since that seems to be the core of the logic.
_softwareengineering.121825
I have learned in Agile Development that: Refactoring is the process of clarifying and simplifying the design of existing code, without changing its behavior.I have heard about some GUI refactoring tools like ReSharper and DevExpress Refactor Pro!Here are my questions: How does it takes place in the Software development process and how far it effects the system?Does Refactoring using these tools really speed up the process of development/maintenance?
Role of Refactoring in good programming pratices?
development process;refactoring
First of all, depending upon the site of refactoring one can distinguish several types of it: code refactoring, database (schema) refactoring, refactoring of unit tests, refactoring of GUI etc.There are several situations where you can meet refactoring during software development:Refactoring is known to be a mandatory step in certain agile development techniques like test-driven development. It is supposed to perform refactoring step after every implementation step. In this case the refactoring targets just the last implementation and its goal is to integrate the new code into the existing code corpus in the most optimal way.Refactoring can be done some internal problems in the working code are detected: this is called code smell. This estimation is in many aspects rather subjective, despite the fact that it can be actually based upon certain code metrics (like number of lines of code per method, cyclomatic complexity of the code etc.). Here the goal of refactoring is to improve the code quality by changing it so that the metrics used for quality estimation return to the expected domain.You often need to refactor the code to achieve certain principles of programming in your code, look for Clean Code development to learn more about such principles.You may need to perform refactoring of your code and database schema to prepare it for coming changes, especially if those were not considered during the design phase of the project. For example data normalization and denormalization take often place during data-driven software development to prepare the database for possible extensions.Refactoring tools available on the market basically support the developer in two ways:While writing your code, you get suggestions how you can improve it on-the-fly. Whereas many fallacies can be detected directly by your IDE, like Visual Studio or Eclipse (for example dead code, variables declared but not used etc.), the refactoring tools like Resharper can reveal problems which are far less evident, like re-writing the loops in LINQ queries etc.These tools also support you with custom refactoring steps, like global renaming of your identifiers, splitting your class declarations into separate properly named files, extracting interfaces and base classes from your class implementation etc. They save a lot of work here, especially if your project has a large code base, but you must first know what you really want to refactor.Actually using tools like ReSharper in everyday's development is so useful that it makes you almost dependent on them: they really accelerate the process of code writing, especially if you know how to use them appropriately!
_softwareengineering.164810
I've been doing software for a long time, but almost all of it has been back-end centric.I recently decided to learn Swing and tried to apply MVC principles. I realize that in Swing the View is handled for you by the components you add to the window/frame/panel, and the Controller is your code responding to the events. However, when it comes to Model I quickly found that I needed TWO models. One is the back-end model representing the underlying data universe. That model is completely unaware of the UI and the fact that it's even being displayed. The second is a version of the model with additional attributes governing display-related aspects. For example, the project I chose was a tool that cross-references the database instances, schemas and tables in a huge enterprise application containing 140 db instances, several hundred schemas and thousands of tables. Sometimes when looking at unfamiliar code you have a table name but finding which instance and schema it's in is a chore.The tool displays 3 columns: DB Instance, Schema and Table, and each column contains only unique names. When you click on a table name (for instance) the schema and instance columns get filtered showing where that particular table occurs. Clicking on a schema name or instance name results in similar filtering behavior on the other two columns.I have a backend model containing a three-level tree (Instance, Schema, Table) but this is inappropriate for the UI I want to display. So I have a second display-model that is built from the backend model, and backs the three columns. That is where I store flags indicating which entries are visible based on user input. The two models are significantly different in structure, and the display-model entries contain references to the backend-model entries. In a sense the display-model entries are adapters that allow the backend-model entries to be handled in a display-appropriate way.I haven't run across any references to this, but my gut feel is that this must be a very common problem. Has anybody else run into this issue, and what are the accepted UI programming ways to accomplish the objective?
MVC two models required?
mvc;model
This is a fairly common situation and your choice of pattern is very dependant on the circumstance and your personal preference.Where you're not simply writing a CRUD application, you can have a domain model which models the business domain and a view model, specific to the application, for displaying and editing that data. Some would argue that even when the two models look the same, you shouldn't expose your data model directly to the view anyway.Or you can consider the domain to include more than just your data (known as Fat Models), in which case the way that you access it -- the API exposed to your front-end application -- doesn't have to relate to the way that you store it in any sense.Also have a look at the related pattern called Command-Query Responsibility Segregation. This is based on the theory that the data model you use to manipulate data is almost always different from the data model(s) you use to view the same data. It draws a very distinct line between the two and allows you to develop the two independently.
_unix.317298
I'm seeking to cache passphrases for use on an unattended machine. As doing this poses some risk, I'd prefer choosing which passphrases get cached and avoid setting both default-cache-ttl and max-cache-ttl to obnoxiously high values as well as avoid needing to clear gpg-agent's entire cache periodically - hence I'm looking for a solution with gpg-preset-passphrase. Some of the information I found while troubleshooting refer to older versions of GnuPG so I'm unsure if I have sufficiently accounted for all the differences.First, as prescribed by man 1 gpg-agent, I have export GPG_TTY=$(tty) in my .bashrc.Now suppose I run eval $(gpg-agent --daemon --allow-preset-passphrase --default-cache-ttl 1 --max-cache-ttl 31536000) to start gpg-agent, noting that gpg-preset-passphrase still honors --max-cache-ttl (default 2 hours).I then get the keygrip $KEYGRIP of the desired secret subkey with gpg --with-keygrip -K.With that I try /path/to/gpg-preset-passphrase -c $KEYGRIP. Upon hitting return, this prints: gpg-preset-passphrase: caching passphrase failed: Not implementedAttempting again adding --verbose --debug 6 --log-file /path/to/gpg-agent.log to gpg-agent, my log is appended with gpg-agent[4206] listening on socket /run/user/1000/gnupg/S.gpg-agent gpg-agent[4207] gpg-agent (GnuPG) 2.1.15 started gpg-agent[4207] handler 0x7f86ef783700 for fd 5 started gpg-agent[4207] command PRESET_PASSPHRASE failed: Not implemented gpg-agent[4207] handler 0x7f86ef783700 for fd 5 terminatedI'm unsure where to proceed from this apart from diving deeper into the source, so I'm wondering if anyone can first correct the steps I'm taking.
What are the steps needed to cache passphrases entered via pinentry using gpg-preset-passphrase in 2.1.15?
gpg;gpg agent
null
_reverseengineering.12609
meanwhile, I am learning more and more how to reverse engineer. Ive figured out tons of stuff already, but I came to the point, where I just need some little explanation whats going on in the constructor of a specific class.I know, that this specific class (Class A) inherits 3 other Classes (lets say: class B, class C, class D).Class A calls the constructors of B,C,D. Everything up to here is clear for me. But:Class D has a method addListener which points to an attribute (this + 0x34).(this + 0x34) is assigned in the constructor to a address..int A::A(void *someObject) { B::B(); C::C(); *this = 0x1f18e8; *(this + 0x28) = 0x1f190c; // whats going here? *(this + 0x34) = 0x1f193c; // and here? // Ive seen, that those addressees are inside of the vtable of Class A // // __ZTV12A: // vtable for A // ... // 001f18e8 db 0xc6 // 001f193c db 0xb0 // 001f190c db 0xba // ... D::D(); // Some other attributes, but these are clear for me (just // have to name them right, by figuring out where these attributes are used): *(this + 0x38) = someObject; *(this + 0x3c) = 0x0; *(this + 0x50) = 0x0; *(this + 0x54) = 0x0; *(this + 0x40) = 0xffffffff; *(this + 0x44) = 0xffffffff; *(this + 0x48) = 0xffffffff; *(this + 0x4c) = 0x0; D::addListener(this + 0x34);}Am I right with my conclusion, that D::addListener() adds the class it self to the listener?In fact I just want to figure out what kind of object is added to the listener: D::addListener(this + 0x34);I hope my question is clear enough :)
Whats going on in this Class Constructor?
disassembly;x86;c++;address;pointer
Your question is a bit unclear as you first say Class C has a method addListerner which points to an attribute (this + 0x34)., then D::addListener(this + 0x34);. Typo?Also, you should read about (typical) implementations of multiple inheritance. Assume your classes B, C, D have methods b, c, d respectively. A will inherit all of them. Now, if A does not override these methods, and anything calls them, they have to be delegated to the correct superclass - the original methods. But these original methods will expect a class layout that corresponds to the original classes. Which means, A needs to embed all 3 classes into itself.Which means A will be laid out like this:+-----+-------------------+| 00 | vtable of A |+-----+-------------------+| 04 | member 1 of A || 08 | member 2 of A || | ... |+-----+-------------------+| 28 | vtable of B |+-----+-------------------+| 2c | member 1 of B || 30 | member 2 of B || | ... |+-----+-------------------+| 34 | vtable of C |+-----+-------------------+| 38 | member 1 of C || 3c | member 2 of C || | ... |+-----+-------------------+| ?? | vtable of D |+-----+-------------------+| ?? | member 1 of D || ?? | member 2 of D || | ... |+-----+-------------------+So, yes, your conclusion is correct: D::addListener() adds the class itself to the listener. But because D::addListener() expects a D, not an A, the thing that's passed isn't the complete A, it's just the part of A that makes D. To make this look exactly like a D, it needs its own vtable that looks like a D vtable.But of course, parts of these vtables can be shared. A needs all methods in its vtable, so the vtable pointers of the partial classes B, C and D can point to the appropriate part of the As vtable, they don't need their complete own copies.As to your what's going on here questions - these initialize the vtables of the partial classes. (In your assembly listing, you should treat those addresses as arrays of words, not bytes). What i wonder is why there's only 3 of them, there should be 4 for A, B, C and D. Something seems to be confused or omitted here, just like you said Class C has first, then used D::addListener.
_datascience.16413
I'm following along the NLTK book and would like to change the size of the axes in a lexical dispersion plot:import nltkfrom nltk.corpus import inauguralcfd = nltk.ConditionalFreqDist( (target, fileid[:4]) # [:4] slices only the years of the speeches for fileid in inaugural.fileids() for word in inaugural.words(fileid) for target in [liberty, equality, brotherhood] if word.lower().startswith(target))Because it gets very crowded otherwise:cfd.plot(title=French ideals in US-American speeches through time)the __doc__ doesn't seem to mention it:print(cfd.plot.__doc__) Plot the given samples from the conditional frequency distribution. For a cumulative plot, specify cumulative=True. (Requires Matplotlib to be installed.) :param samples: The samples to plot :type samples: list :param title: The title for the graph :type title: str :param conditions: The conditions to plot (default is all) :type conditions: listAnd I think there is nothing on it in the NLTK documentation, but also not in the matplotlib documentation (where I figured the plot functionality comes from): http://www.nltk.org/py-modindex.html#cap-phttp://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot(sorry for the code-block links, I'm new here and can't post more than 2 links but still felt like making it easier for someone reading this :)I'd be glad if someone could point me into the right direction! Thanks!
How to change plot size in nltk.plot()
python;nlp;nltk;jupyter;ipython
null
_softwareengineering.266630
I think this question is specific to indie developers be concerned about. Think about it as a license clarification or a license practical use case.I need to know how must be my project basic packages structure and how can I distribute it?I am an app developer, I have no site yet, I will just create the code (package (B) will be my placeholder assets I manage to create with my very limited skills, or assets I could buy later to let my project have some unique visual/sfx/music features, if it does not conflict with package (C) in any way that could cause me trouble).I thought:A) a binary proprietary executables application package (no source distribution).B) a media/assets package of proprietary media (could be packed together with (A)).C) a media/assets package of CC content. The problem about package (C) is:Is CC-0 the only CC content I can be tranquil about? I will have to redistribute it at least as CC-BY package according to this: if-i-create-a-collection-that-includes-a-work-offered-under-a-cc-license-which-licenses-may-i-choose-for-the-collection How ok is to use CC-BY and CC-BY-SA content on package (C)? As I read, any CC-BY-SA, at least, interfere with screenshots, videos and any other promoting media (but that promoting media is not too much troublesome to me at least, unless I create cut-scenes with my own project). Does any CC-BY-SA content affect package (A) or (B) in any way other than specified at (2)? So (A) or (B) would have to fall under some CC license?Does this CC-BY-SA clause For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image (synching) will be considered an Adaptation for the purpose of this License. will force me to freely distribute my project as open source about the synchronization code part of my project engine (or even the full source code)? considering the project may be seen as a performance.The package (C) may be required for the application to run, so, in this case of unbreakable dependency, will it affect the application license in any way? Also, in case I am able to make the application run without it, would the application still be affected by it?May I distribute package (C) together with my application solely, and later on, users (who bought it) may redistribute package (C) freely and even publish it on sites that redistribute CC content? Or am I forced to promptly make that package freely available on my site (or at the site that will sell it) and/or on some other site? Or can I only distribute it from some other site and only link to it from my site?PS.: License code excerpts confirming the answer are mostly appreciated! I've been trying to read and understand it all, but it is surely not easy to me... Other granted sources of information like FAQs or another kind, may be good enough too (as they usually refer to the license code trying to make it more easy to understand).PS.2: to anyone interested, some interesting common sense notions to be aware about public domain media: http://pixabay.com/en/blog/posts/public-domain-images-what-is-allowed-and-what-is-4/
How do CC licenses (0, BY, BY-SA) affect proprietary/closed source applications?
licensing;creative commons
null
_codereview.95614
I wanted to be able to tokenize a few different containers so I created a generic way to do it. I originally wrote this in Visual Studio 2012, but I had to modify it to get it to compile on Ideone.Here is a brief description of my tokenizer functions:Tokenize (): Tokenizes a container based on a single delimiter.TokenizeIf (): Tokenizes a container based on a single delimiter and a condition.BackInsertTokenize () and BackInsertTokenizeIf (): Wrapper for containers that can use a std::back_inserter iterator.A specialized BackInsertTokenize () for character types (char, wchar, etc).Here are my generic tokenizer functions:#include <algorithm>#include <iterator>#include <string>#include <utility>template <typename Token, typename Iter, typename OutIter, typename Condition>auto TokenizeIf (Iter begin, Iter end, OutIter out, typename std::iterator_traits <Iter>::value_type delimiter, Condition condition) -> OutIter{ if (begin == end) { return out ; } auto current = begin ; auto next = begin ; do { next = std::find (current, end, delimiter) ; Token token (current, next) ; if (condition (token) == true) { *out++ = std::move (token) ; } current = next ; } while (next != end && ++current != end) ; if (next != end) { Token token ; if (condition (token) == true) { *out++ = std::move (token) ; } } return out ;};template <typename Token, typename Iter, typename OutIter>auto Tokenize (Iter begin, Iter end, OutIter out, typename std::iterator_traits <Iter>::value_type delimiter) -> OutIter{ if (begin == end) { return out ; } auto current = begin ; auto next = begin ; do { next = std::find (current, end, delimiter) ; *out++ = Token (current, next) ; current = next ; } while (next != end && ++current != end) ; if (next != end) { *out++ = Token () ; } return out ;};template <class ContainerOut, class ContainerIn, class Condition>auto BackInsertTokenizeIf (ContainerIn const &in, typename ContainerIn::value_type delimiter, Condition condition) -> ContainerOut{ typedef typename ContainerOut::value_type Token ; ContainerOut out ; TokenizeIf <Token> (std::begin (in), std::end (in), std::back_inserter (out), delimiter, condition) ; return out ;}template <class ContainerOut, class ContainerIn>auto BackInsertTokenize (ContainerIn const &in, typename ContainerIn::value_type delimiter) -> ContainerOut{ typedef typename ContainerOut::value_type Token ; ContainerOut out ; Tokenize <Token> (std::begin (in), std::end (in), std::back_inserter (out), delimiter) ; return out ;}template <class ContainerOut, class CharT>auto BackInsertTokenize (const CharT *in, CharT delimiter) -> ContainerOut{ typedef typename ContainerOut::value_type Token ; ContainerOut out ; Tokenize <Token> (in, in + std::char_traits<CharT>::length (in), std::back_inserter (out), delimiter) ; return out ;}These are the test cases that I was interested in:#include <vector>int main (){ std::string const s1 = ,hello,5,cat,192.3, ; auto const t1 = BackInsertTokenize <std::vector <std::string>> (s1, ',') ; std::vector <char> v1 = {'S', '1', '\0', 'S', '2', 'I', 'N', '\0', 'S', '3', '\0', '\0'} ; auto const t2 = BackInsertTokenizeIf <std::vector <std::string>> (v1, '\0', [] (const std::string &s) { return !s.empty () ; }) ; auto const t3 = BackInsertTokenize <std::vector <std::string>> (C:\\Some\\Path\\To\\Nowhere, '\\') ; return 0 ;}
Templated Tokenizer Functions
c++;parsing
The code generally looks good to me. It is clear, complete and working. The naming and formatting are clear and consistent (although I prefer to read code that does not have the space before each statement-terminating semicolon) but I did see a few things that may help you improve your code.Consider using {} style initializersThere are a few places where a Token is constructed, such as this:Token token (current, next_) ;However, this might be misconstrued as a function call. Assuming that you're using C++11 or better, it may be worth considering using the {} style for the constructor:Token token {current, next} ;This can't be misconstrued as a function call and may be slightly less ambiguous.Consider alternative usageThe code works well for the use cases you've said you're interested in addressing. That's good, and it may be all you ever need, but when I first saw the code, I thought it might be useful to be able to use it like this:std::string const s2 = 55,33,1,7,42;auto const t4 = BackInsertTokenize <std::vector <int>> (s2, ',') ;The intent was to create a vector of integers from the const string, but this code doesn't actually compile. The problem is essentially this line:*out++ = Token (current, next) ;That works fine for any Token type that can be constructed from an iterator range like this, but not for a primitive type like int. One way to address that might be to provide another template that additionally takes an operator to explicitly perform this conversion with the given types.Omit return 0When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.
_unix.365909
I want a CentOS 6.6 environment to build release. But, Linode does not provide CentOS 6.6 image. So I tried to install virtualbox on Ubuntu 16.04 .The virtualbox installation does not work. The error message isLoading new virtualbox-5.0.40 DKMS files...First Installation: checking all kernels...dpkg: warning: version '4.9.15-x86_64' has bad syntax: invalid character in revision numberdpkg: warning: version '4.9.15-x86_64' has bad syntax: invalid character in revision numberIt is likely that 4.9.15-x86_64-linode81 belongs to a chroot's hostModule build for the currently running kernel was skipped since thekernel source for this kernel does not seem to be installed.Job for virtualbox.service failed because the control process exited with error code. See systemctl status virtualbox.service and journalctl -xe for details.invoke-rc.d: initscript virtualbox, action restart failed. virtualbox.service - LSB: VirtualBox Linux kernel module Loaded: loaded (/etc/init.d/virtualbox; bad; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2017-05-18 17:03:22 UTC; 5ms ago Docs: man:systemd-sysv-generator(8) Process: 29436 ExecStart=/etc/init.d/virtualbox start (code=exited, status=1/FAILURE)May 18 17:03:22 localhost systemd[1]: Starting LSB: VirtualBox Linux kernel module...May 18 17:03:22 localhost virtualbox[29436]: * Loading VirtualBox kernel modules...May 18 17:03:22 localhost virtualbox[29436]: * No suitable module for running kernel foundMay 18 17:03:22 localhost virtualbox[29436]: ...fail!May 18 17:03:22 localhost systemd[1]: virtualbox.service: Control process exited, code=exited status=1May 18 17:03:22 localhost systemd[1]: Failed to start LSB: VirtualBox Linux kernel module.May 18 17:03:22 localhost systemd[1]: virtualbox.service: Unit entered failed state.May 18 17:03:22 localhost systemd[1]: virtualbox.service: Failed with result 'exit-code'.Setting up virtualbox (5.0.40-dfsg-0ubuntu1.16.04.1) ...vboxweb.service is a disabled or a static unit, not starting it.Job for virtualbox.service failed because the control process exited with error code. See systemctl status virtualbox.service and journalctl -xe for details.invoke-rc.d: initscript virtualbox, action restart failed. virtualbox.service - LSB: VirtualBox Linux kernel module Loaded: loaded (/etc/init.d/virtualbox; bad; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2017-05-18 17:03:24 UTC; 7ms ago Docs: man:systemd-sysv-generator(8) Process: 29550 ExecStart=/etc/init.d/virtualbox start (code=exited, status=1/FAILURE)May 18 17:03:24 localhost systemd[1]: Starting LSB: VirtualBox Linux kernel module...May 18 17:03:24 localhost virtualbox[29550]: * Loading VirtualBox kernel modules...May 18 17:03:24 localhost virtualbox[29550]: * No suitable module for running kernel foundMay 18 17:03:24 localhost virtualbox[29550]: ...fail!May 18 17:03:24 localhost systemd[1]: virtualbox.service: Control process exited, code=exited status=1May 18 17:03:24 localhost systemd[1]: Failed to start LSB: VirtualBox Linux kernel module.May 18 17:03:24 localhost systemd[1]: virtualbox.service: Unit entered failed state.May 18 17:03:24 localhost systemd[1]: virtualbox.service: Failed with result 'exit-code'.Setting up virtualbox-qt (5.0.40-dfsg-0ubuntu1.16.04.1) ...
install virtualbox on Linode failed
virtualbox
null
_cs.19542
Short version: I want to know where the $-2$ comes from in the formula on p. 221 of CLRS 3rd edition.Long version: CLRS (3rd ed.) give an algorithm for $O(n)$ worst case arbitrary order statistic of $n$ distinct numbers. The algorithm is roughly:Input: an array of $n$ elements and $i$, the number of the order statistic to return from the elements.Divide the $n$ elements into $\lfloor n/5 \rfloor$ groups of 5 elements each along with an optional group containing $n\mod{5}$ elements (resulting in $\lceil n/5 \rceil$ groups.)Find the median of each of the groups by sorting.Recurse, using the $\lceil n/5 \rceil$ medians as the array and $\lfloor\lceil n/5 \rceil/2\rfloor$ as the order statistic, resulting in the median-of-medians.Partition the $n$ elements around the median-of-medians (using a quicksort-like $O(n)$ partitioning algorithm.Letting $k-1$ be the number of elements less than the median-of-medians, if $i = k$, return the median-of-medians. Otherwise recurse: if $i < k$ then recurse finding the $i$th order statistic of the $k-1$ elements less than the median-of-medians; if $i > k$, then recurse finding the $i-k$th order statistic of the $n-k$ elements greater than the median-of-medians.Output: the $i$th order statistic of the $n$ numbers.In the proof of the runtime, CLRS argue that the number of elements greater than the median-of-medians is at least:$$3 \bigg(\bigg\lceil \frac{1}2 \bigg\lceil{\frac{n}5} \bigg\rceil \bigg\rceil - 2\bigg)$$The reasoning is that half of the medians are greater than the median-of-medians, and each of those medians' groups has at least three elements greater than the median-of-medians (the median itself plus the two elements greater than the median.) That would result in $$3 \bigg(\bigg\lceil \frac{1}2 \bigg\lceil{\frac{n}5} \bigg\rceil \bigg\rceil\bigg)$$for the lower bound on the number of elements greater than the median-of-medians. But we must account for two things: the group containing the median-of-medians (the median-of-medians is not greater than itself) and the group that contains the modulo leftovers. To account for the group containing the median-of-medians, we subtract 1, resulting in:$$3 \bigg(\bigg\lceil \frac{1}2 \bigg\lceil{\frac{n}5} \bigg\rceil \bigg\rceil\bigg) - 1$$and I think that for the modulo leftovers group, we should subtract 4, because the least number of elements in the group is 1. So that would give:$$3 \bigg(\bigg\lceil \frac{1}2 \bigg\lceil{\frac{n}5} \bigg\rceil \bigg\rceil\bigg) - 5$$which can be transformed into $$3 \bigg(\bigg\lceil \frac{1}2 \bigg\lceil{\frac{n}5} \bigg\rceil \bigg\rceil - 2\bigg) + 1$$Why does my analysis lead to a lower-bound 1 greater than that given in CLRS?
Counting elements that are greater than the median of medians
algorithm analysis;combinatorics;discrete mathematics
In$$3 \bigg(\bigg\lceil \frac{1}2 \bigg\lceil{\frac{n}5} \bigg\rceil \bigg\rceil - 2\bigg)$$we are subtracting 2 in order to discard the group containing the median of medians and the group of leftovers. So, 2 is the number of groups we are discarding.First of all, note that there may not be a group of leftover elements: if $n$ is an exact multiple of 5 there will be no leftover group. We are interested in bounding from below the number of elements greater than the median-of-medians in the worst case, so suppose that a leftover group exists. Therefore, it will contain at least an element and no more than 4 elements. If you want to reason in terms of elements to be discarded and not in terms of groups, then we must discard exactly 3 elements for the group containing the median of medians (including the median of the medians), and at most 2 element from the leftovers group (if this group contains 1 or 2 elements you do not discard any element; if this group contains 3 or 4 elements, then you discard respectively 1 or 2 elements which are greater than the group's median). So, you discard in the worst case (leftover group with 4 elements) 3 + 2 elements:$$3 \bigg(\bigg\lceil \frac{1}2 \bigg\lceil{\frac{n}5} \bigg\rceil \bigg\rceil\bigg) - 5$$
_unix.388269
any idea?here is my code:#!/bin/sh. /etc/rc.commonstart on startuptaskexec /Applications/Chess.app
Execute shell script (contains running .app application) and add automatically on startup items mac
shell script;osx;autostart
null
_codereview.58321
I've created a lock-free job queue and with the tests I've written, which is also very fast.That makes me doubt my benchmark procedure, so I'm hoping the collective knowledge will shed some light on the validity of those.The test basically increments an atomic value (each job is a single increment) until the predefined value is met. In my mind, this test really shows the overhead that the queue imposes because the workload is so simple.I've tried to create a queue to which I can post jobs and pick up jobs from all threads, a true multiple read/write queue. The tests I've written try to test all use cases, including multi-read/multi-write.boostasio push/pop functions:T = function< void() >void push_back( T t ){ service_.post( t );}bool pop( T &t ){ t = [](){}; return service_.run_one();}mutex_queue:void push_back( const T &t ){ lock_guard< mutex > guard( lock_ ); data_.push_back( t );}bool pop( T &t ){ lock_guard< mutex > guard( lock_ ); if ( index_ == data_.size() ) { return false; } t = data_[ index_++ ]; return true;}For details on the lock-free push/pop, I suggest you look at GitHub, since it is a bit extensive to post here.For completeness, here's the test setup in full:#include <iostream>#include <functional>#include <thread>#include <sstream>#include <atomic>#include <vector>#include <chrono>#include <lock_free/fifo.h>#include <boost/asio/io_service.hpp>using namespace std;using namespace chrono;using namespace boost::asio;typedef function< void() >function_type;template < typename T >struct boostasio{ boostasio( size_t r = 1024 ) {} void push_back( T t ) { service_.post( t ); } bool pop( T &t ) { t = [](){}; return service_.run_one(); } io_service service_;};template < typename T >struct mutex_queue{ mutex_queue( size_t r = 1024 ) : lock_(), index_( 0 ), data_( r ) { data_.clear(); } void push_back( const T &t ) { lock_guard< mutex > guard( lock_ ); data_.push_back( t ); } bool pop( T &t ) { lock_guard< mutex > guard( lock_ ); if ( index_ == data_.size() ) { return false; } t = data_[ index_++ ]; return true; } mutex lock_; size_t index_; vector< T > data_;};template < typename T >T to( const string &str ){ T result; stringstream( str ) >> result; return result;}template < typename T >function_type get_producer( T &&t ){ return get< 0 >( t );}template < typename T >function_type get_consumer( T &&t ){ return get< 1 >( t );}template < typename T >function_type get_result( T &&t ){ return get< 2 >( t );}template < typename Q >void test( const string &testname, size_t count, size_t threadcount ){ auto create_producer_consumer_result = [=]( const string &name ) { high_resolution_clock::time_point t1 = high_resolution_clock::now(); auto data = make_shared< Q >( count ); function_type producer = [data]() { while ( data->producer_count++ < data->expected ) { data->queue.push_back( [data]() { ++data->consumer_count; } ); } if ( data->producer_count >= data->expected ) { --data->producer_count; } }; function_type consumer = [data]() { while ( data->consumer_count < data->expected ) { function_type func; while ( data->queue.pop( func ) ) { func(); } } }; function_type result = [=]() { high_resolution_clock::time_point t2 = high_resolution_clock::now(); duration< double > time_span = duration_cast< duration< double > >( t2 - t1 ); if ( data->expected != data->consumer_count ) { cout << \texpected: << data->expected << , actual: << data->consumer_count << endl; } cout << '\t' << name << took: << time_span.count() << seconds << endl; }; return make_tuple( producer, consumer, result ); }; high_resolution_clock::time_point teststart = high_resolution_clock::now(); cout << testname << :\n{\n; // single producer, single consumer { auto pcr = create_producer_consumer_result( single producer, single consumer ); get_producer( pcr )(); get_consumer( pcr )(); get_result( pcr )(); } // single producer, multi consumer { auto pcr = create_producer_consumer_result( single producer, multi consumer ); get_producer( pcr )(); vector< thread > threads; size_t c = threadcount; while ( c-- ) { threads.push_back( thread( get_consumer( pcr ) ) ); } for ( auto &t : threads ) { t.join(); } get_result( pcr )(); } // multi producer, single consumer { auto pcr = create_producer_consumer_result( multi producer, single consumer ); vector< thread > threads; size_t c = threadcount; while ( c-- ) { threads.push_back( thread( get_producer( pcr ) ) ); } for ( auto &t : threads ) { t.join(); } get_consumer( pcr )(); get_result( pcr )(); } // multi producer, multi consumer { auto pcr = create_producer_consumer_result( multi producer, multi consumer ); vector< thread > threads; size_t c = threadcount / 2; while ( c-- ) { threads.push_back( thread( get_producer( pcr ) ) ); threads.push_back( thread( get_consumer( pcr ) ) ); } for ( auto &t : threads ) { t.join(); } get_result( pcr )(); } duration< double > time_span = duration_cast< duration< double > >( high_resolution_clock::now() - teststart ); cout << \ttotal: << time_span.count() << seconds\n} << endl;}template < typename T >struct test_data{ test_data( size_t e ) : expected( e ), queue(), producer_count( 0 ), consumer_count( 0 ) { } const size_t expected; T queue; atomic_size_t producer_count; atomic_size_t consumer_count;};int main( int argc, char *argv[] ){ constexpr auto test_count = 1e6; const auto thread_count = argc > 1 ? to< size_t >( argv[ 1 ] ) : 16; test< test_data< boostasio< function_type > > >( boostasio, test_count, thread_count ); test< test_data< lock_free::fifo< function_type > > >( lock_free::fifo, test_count, thread_count ); test< test_data< mutex_queue< function_type > > >( mutex_queue, test_count, thread_count ); return 0;}Here are some results on a machine which has 8 cores (+8 HT) and running with 16 threads:boostasio:{ single producer, single consumer took: 0.711752 seconds single producer, multi consumer took: 5.03024 seconds multi producer, single consumer took: 4.16782 seconds multi producer, multi consumer took: 8.45779 seconds total: 18.3679 seconds}lock_free::fifo:{ single producer, single consumer took: 0.356197 seconds single producer, multi consumer took: 1.12591 seconds multi producer, single consumer took: 0.575264 seconds multi producer, multi consumer took: 1.24645 seconds total: 3.304 seconds}mutex_queue:{ single producer, single consumer took: 0.363318 seconds single producer, multi consumer took: 2.77809 seconds multi producer, single consumer took: 2.72058 seconds multi producer, multi consumer took: 5.11961 seconds total: 10.9818 seconds}
Testing a lock-free job queue
c++;performance;c++11;queue;lock free
null
_unix.51846
Is it possible to pass kernel parameters in the LILO boot prompt?
Is it possible to pass kernel parameters in the LILO boot prompt?
lilo
You can: type the parameters after the entry. In your case, would be Linux + the parameters (e.g. Linux root=/dev/sda1).To show:gives
_unix.185921
I have been trying to install mint 17.1, but all I can see is a blank screen with just mouse pointer. I had even tried to press Ctrl+Alt+F1, so I don't know which commands to enter from that spot. Can anyone please help!
Linux Mint 17.1 installation
linux mint;boot
null
_codereview.114991
I have written a small app that fetches news items from an endpoint and displays them in a grid.I used React to create components and use them throughout the app. This is the first thing I have built using ES6 - mainly for syntactic sugar.I tried to match the BBC News page style, so it should look very similar. It's responsive and should look good on any size screen.Overall, I'd mainly like feedback for my React and ES6, comments on best practices or what I could do better.Here is my React code:const Header = () => { return ( <div className=white-header> {/* Bootstrap nav */} <nav className=navbar> <div className=container-fluid> <div className=navbar-header> <button type=button className=navbar-toggle collapsed data-toggle=collapse data-target=#bs-example-navbar-collapse-1 aria-expanded=false> <span className=sr-only>Toggle navigation</span> <i className=fa fa-bars icon-bar></i> </button> <div className=navbar-brand href=#> <span className=fccLogo>F</span> <span className=fccLogo>C</span> <span className=fccLogo>C</span> </div> </div> <div className=collapse navbar-collapse id=bs-example-navbar-collapse-1> <ul className=nav navbar-nav> <li><a href=http://www.freecodecamp.com/>freecodecamp</a></li> <li><a href=http://www.bbc.co.uk/news>bbc news</a></li> <li><a href=http://github.com/alanbuchanan>github</a></li> </ul> </div> </div> </nav> <div className=red-header> <h1>NEWS</h1> </div> <div className=darkred-header> <h1></h1> </div> </div> );};const BigStory = (props) => { const {newsItems} = props; let {headline} = newsItems; headline = splitHeadlineAtUnwantedChar(headline); return ( <div className=big-story col-xs-12> <div className=col-sm-5> <h1><HeadlineLink headline={headline} link={newsItems.link}/></h1> <p>{newsItems.metaDescription}</p> <TimeAndLink time={newsItems.timePosted} author={newsItems.author.username}/> </div> <div className=col-sm-7> <img className=img-responsive src={newsItems.image} alt=/> </div> </div> );};const MediumStory = (props) => { const {newsItems} = props; newsItems.headline = splitHeadlineAtUnwantedChar(newsItems.headline); return ( <div className=medium-story col-sm-4 col-xs-6> <img className=img-responsive src={newsItems.image} alt=/> <h4><HeadlineLink headline={newsItems.headline} link={newsItems.link}/></h4> <p>{newsItems.metaDescription}</p> <TimeAndLink time={newsItems.timePosted} author={newsItems.author.username}/> </div> );};const SmallStory = (props) => { const {newsItems} = props; newsItems.headline = splitHeadlineAtUnwantedChar(newsItems.headline); return ( <div className=small-story> <h4><HeadlineLink headline={newsItems.headline} link={newsItems.link}/></h4> <TimeAndLink time={newsItems.timePosted} author={newsItems.author.username}/> </div> );};const DatedListNoPics = (props) => { const {items} = props; const list = items.map((e, i) => { return ( <li className=col-sm-6 key={i}> <h5><HeadlineLink headline={splitHeadlineAtUnwantedChar(e.headline)} link={e.link}/></h5> <TimeAndLink time={e.timePosted} author={e.author.username}/> </li> ); }); return ( <ul className=dated-list-no-pics> {list} </ul> );};const DatedListWithPics = (props) => { let {items} = props; items = filterForImages(items); const list = items.map((e, i) => { return ( <div className=col-lg-12 col-md-6 col-sm-6 key={i}> <div className=col-md-6 col-sm-6 col-xs-6> <img className=img-responsive src={e.image} alt=/> </div> <div className=col-md-6 col-sm-6 col-xs-6> <h4><HeadlineLink headline={splitHeadlineAtUnwantedChar(e.headline)} link={e.link}/></h4> <TimeAndLink time={e.timePosted} author={e.author.username}/> </div> </div> ); }); return ( <div className=dated-list-with-pics> {list} </div> );};// Helpers and mini componentsconst splitHeadlineAtUnwantedChar = (str) => str.indexOf() !== -1 ? str.split()[0] : str;const filterForImages = (arr) => arr.filter(e => e.image !== );const Loading = () => <div></div>;const HeadlineLink = (props) => { return ( <div className=headline-link> <a href={props.link}>{props.headline}</a> </div> );};const Main = React.createClass({ getInitialState () { return { newsItems: [] }; }, componentDidMount () { this.getNewsItems(); }, getNewsItems () { $.getJSON(http://www.freecodecamp.com/news/hot, (data) => { this.setState({newsItems: data}); }); }, render () { const {newsItems} = this.state; const loading = newsItems.length === 0; let listNoPics = []; let listWithPics = []; const storiesToShow = 25; // This is done in the render to avoid further ternary operators due to loading, as below // List 1 (no pics): for (let i = 6; i <= 11; i++) { listNoPics.push(newsItems[i]); } // List 2 (with pics): for (let i = 12; i <= storiesToShow; i++) { listWithPics.push(newsItems[i]); } return ( <div className=container> <Header /> <div className=main-content col-sm-12> <div className=left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12> {loading ? <Loading /> : <BigStory newsItems={newsItems[0]}/> } {loading ? <Loading /> : <MediumStory newsItems={newsItems[1]}/> } {loading ? <Loading /> : <MediumStory newsItems={newsItems[2]}/> } <div className=col-sm-4 col-xs-12> {loading ? <Loading /> : <SmallStory newsItems={newsItems[3]}/> } {loading ? <Loading /> : <SmallStory newsItems={newsItems[4]}/> } {loading ? <Loading /> : <SmallStory newsItems={newsItems[5]}/> } </div> {loading ? <Loading /> : <DatedListNoPics items={listNoPics}/> } </div> <div className=right-sided-lg-bottom-otherwise col-lg-4 col-md-12 col-sm-12 col-xs-12> {loading ? <Loading /> : <DatedListWithPics items={listWithPics}/> } </div> </div> </div> ); }});// Place right at the end because it messes up the colouring. const TimeAndLink = (props) => { return ( <p className=time-and-link> <span id=timeago><i className=fa fa-clock-o></i> {$.timeago(props.time).replace(/(about)/gi, )}</span> | <a href={`http://www.freecodecamp.com/${props.author}`}>{props.author}</a> </p> );};ReactDOM.render(<Main />, document.getElementById('root'));Here is a Codepen of the app.
React & ES6 news app
javascript;json;ecmascript 6;react.js
Ok, looks like a neatly written React. Let's see what I can do. <div className=main-content col-sm-12> <div className=left-sided-lg-top-otherwise col-lg-8 col-md-12 col-sm-12 col-xs-12> {loading ? <Loading /> : <BigStory newsItems={newsItems[0]}/> } {loading ? <Loading /> : <MediumStory newsItems={newsItems[1]}/> } {loading ? <Loading /> : <MediumStory newsItems={newsItems[2]}/> } <div className=col-sm-4 col-xs-12> {loading ? <Loading /> : <SmallStory newsItems={newsItems[3]}/> } {loading ? <Loading /> : <SmallStory newsItems={newsItems[4]}/> } {loading ? <Loading /> : <SmallStory newsItems={newsItems[5]}/> } </div> {loading ? <Loading /> : <DatedListNoPics items={listNoPics}/> } </div> <div className=right-sided-lg-bottom-otherwise col-lg-4 col-md-12 col-sm-12 col-xs-12> {loading ? <Loading /> : <DatedListWithPics items={listWithPics}/> } </div> </div>Instead of hard-coding news 1 to 5, consider making them lists too (even if they're just 1 story). Lists are easier to manage and is future-proof in a sense that if you want to add more, you'll probably just tweak some constant to have it load more. Which brings us to the next piece...// List 1 (no pics):for (let i = 6; i <= 11; i++) { listNoPics.push(newsItems[i]);}// List 2 (with pics):for (let i = 12; i <= storiesToShow; i++) { listWithPics.push(newsItems[i]);}An alternative way of building this (in a non-imperative way) is to use a range function, like the one from lodash and a map function to transform each value into another value. In this case, ranges into news lists. Recursive is ok, but with the overhead of building a recursive function (which is overkill).var storyMapper = (i) => newsItems[i];var bigStory = _.range(0, 1).map(storyMapper);var mediumStory = _.range(1, 3).map(storyMapper);var smallStory = _.range(3, 6).map(storyMapper);var listNoPics = _.range(6, 11).map(storyMapper);var listWithPics = _.range(12, storiesToShow).map(storyMapper);Now I mentioned earlier about a configurable list of things. You can put the range arguments in some constant somewhere in a config. This allows you to easily adjust the lists.If you want to create a range of your own, you can simply use Array.fill with array.map.function range(start, end){ return Array(end - start).fill(0).map((v,i) => start + i);}When your app becomes complex like this, naming becomes hard especially for CSS classes (and no, don't even consider inline styles). Check out BEM. It's an element naming convention that manages your CSS classes without having the styles stepping each other's feet. Take for example, your Main component.<div class=layout-classes main> ... <div class=layout-classes main__container> ... <div class=layout-classes main__small-stories {loading ? 'main__small-stories--loading' : ''}> ....main{...}.main__container{...}.main__small-stories{...}.main__small-stories--loading{display:none} // hides small stories until removedWith this naming convention, all your components will have a unique BEM name, essentially collision-free (be concise about the names though). Your CSS will all end up with a very low specificity of 0-1-0, making them easily overridable (goodbye !important). Besides, why would you override when you know they're unique to that component and can safely change them? (unless it's inherited from a parent)I see you're using React, thus Babel which tells me that you have a build phase. Consider doing the same for your CSS by using a preprocessor like SASS or LESS. That way, you can use mixins. For instance, your BEM-ified main__small-stories could look like:.main__small-stories{ // styles for small stories ON MOBILE @include medium-screens{ // styles for medium screens } @include large-screens{ // styles for large screens }}So in the above, it uses mixins and just inverts the definition of media queries. Instead of starting off with a media query, and duplicating selectors, you define the selector and default styles, and append what happens on different screens. Output CSS is still the same, but from an authoring perspective, it's much readable.
_softwareengineering.352605
General question regarding the STL. Do you guys think that the STL should be used for data structures or would you create custom code? In what scenario would you implement your own code for something that the Standard Library already does? What are your thoughts?
C++: STL or custom code for data structures?
c++;stl
null
_codereview.51939
What would be the best way to refactor this :@busy.each do |b| title = b.title @events << { :id => b.id, :title => title, :start => b.busy_start_time(b.start_date,b.start_time), :end => b.busy_end_time(b.end_date,b.end_time), :allDay => false, :recurring => false, :color => 'black', } @events is initialized as an empty array:@events = []And this busy statement is the SECOND of two pushes into @events.I think that I can use map here something like :@events = @events + @busy.map do |b| stuffendBecause I don't want to overwrite @events, I want to add stuff into it.But what I'm really searching for is a way to store the entire 'each' into a lambda and say something like :@events += @busy(&:create_busy_hash) And move all the hash creation into the Busy class as create_busy_hashI'm still grasping lambdas and procs
Refactor .each where each is redirected into a hash
ruby;ruby on rails
I think this is where you are trying to get to:class Busy def event_info { :id => id, :title => title, :start => busy_start_time(start_date, start_time), :end => busy_end_time(end_date, end_time), :allDay => false, :recurring => false, :color => 'black', } endend@events = @busy_items.map(&:event_info)Some additional notes:There is no need to initialize @events to an empty array, favor expressions over statements with side-effects (map, select, reduce and so on, instead of each).I renamed the variable to busy_items to emphasize it's a collection.Busy does not sound right for a class name. Classes are usually nouns, not adjectives. What's the nature of this class?
_unix.86947
So I have different installed kernel versions from the running kernel version, on my fedora 19 machine.To give a more clear idea, here is my terminal output: [user@home ~]$ uname -r 3.10.3-300.fc19.x86_64 [user@home ~]$ rpm -qa | grep kernel-devel kernel-devel-3.10.6-200.fc19.x86_64 kernel-devel-3.10.4-300.fc19.x86_64When I install Nvidia drivers, it gives me this error that the installed and the running versions are not the same. I want to remove the currently installed 3.10.6-200 and 3.10.4-300 versions, and install the running version ( 3.10.3-300)instead. I don't know how to go about doing it. Any help will be appreciated!!
Install kernel-devel of specific version in fedora 19
fedora;linux kernel
Ideally you should be able to run: yum install kernel-devel-3.10.3-300.fc19.x86_64No package kernel-devel-3.10.3-300.fc19.x86_64 available. But this packages is no longer available. It seems that you have been upgrading your system without actually rebooting it into a new kernel.On my running system: yum info kernel|grep -E Name|Version|ReleaseName : kernelVersion : 3.10.4Release : 300.fc19Name : kernelVersion : 3.10.5Release : 201.fc19Name : kernelVersion : 3.10.6Release : 200.fc19uname -r3.10.6-200.fc19.x86_64yum info kernel-develName : kernel-develVersion : 3.10.4Release : 300.fc19Name : kernel-develVersion : 3.10.5Release : 201.fc19Name : kernel-develVersion : 3.10.6Release : 200.fc19I advise you to do the following:Check what kernel you have installed. Check the grub configuration and reboot into the new kernel. After that recompile nvidia drivers.Unless there is a specific reason for you to stay with your current running kernel, then you will need to look for it. In the Fedora updates repo there is not such package anymore. You can check here
_unix.72036
I recently moved to Mac. I am missing my X11 copy-paste style.I can't find a way to exactly emulate X11 behavior select-to-copy, middle-click-to-paste globally on Mac OS X.I am aware that this issue has been around for a long time, yet I can't find any real killer solution.The best thing I found is in Can I copy by highlighting and paste by middle click on Mac OS X?. All suggested solutions try to find out a way to paste text from the clipboard with a middle click.Yet, nobody has a real solution for automatically copying the highlighted text.I am wondering if there can be a way to automate the copying of highlighted text. Even if I should write a daemon to do it. Any pointers on where to start thinking will be great.
A real non-better touch tools solution for select-to-copy on Mac OS X
x11;osx;mouse;copy paste
null
_softwareengineering.316036
I have a requirement for a service that does the following.Take a block of text and identify the server names in it (by name or ip address). So given:Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec libero felis, accumsan in nunc id, lacinia rutrum libero. Server1 Praesent iaculis consequat est quis elementum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos Server2 himenaeos. Cras aliquet nisl non tortor interdum semper. Nulla commodo dignissim justo, eu accumsan neque eleifend ut. Etiam malesuada volutpat dolor 192.168.0.2 laoreet placerat. Maecenas posuere ipsum mattis egestas elementum.The service would return:Server1Server2Server3 (which has ip Address 192.168.0.2)there are around 7,000 servers and addresses in my DB. So at the moment the only strategy I have is to take the text block as a string and loop through all the servers twice (name and ip) issuing a string.Contains().Issuing 14,000 Contains seems a bit brute force. Is there a more elegant way to achieve the same result.For context this is a rest service running on ASP.Net MVC and C#.
Most efficient strategy for search large text areas for multiple values
c#;asp.net mvc;strings;search
If your current code is simple and fast enough for your needs, do nothing. Just to optimize because it seems a bit brute force is not a good reason, it will mostly complicate things for no benefit. Do not fall into the trap of premature optimization.However, if your current code really is too slow for your purposes, first measure where the bottleneck is. Is it really calling 14.000 times string.Contains, or is it selecting the 14.000 server names / Ip addresses from your database? The first issue might be approached by splitting up the text into words which may be potentially a server name, and utilizing a hashset or a more sophisticated data structure. The second issue might be approached by splitting up the text the same way,using the words as a SELECT criteria, assumed your database is properly indexed. The latter one could increase the number of roundtrips, to avoid that, you could implement a stored procedure in your DB, pass the text once over the network and let the SP do the work.All of these solutions, however, will result in more complicated code than you have now, so make sure this is worth the hassle, otherwise you are probably sacrificing a maintainable solution for useless overcomplication.
_softwareengineering.222528
Which one is considered better:having a directive that interacts with services directlyorhaving a directive that exposes certain hooks to which controller may bind behaviour (involving services)?
Should angularjs directive directly interact with services or is it considered an anti-pattern?
design patterns;patterns and practices;angularjs
A directive is best (as a rule-of-thumb) when it's short (code-wise), (potentially) re-usable, and has a limited a scope in terms of functionality. Making a directive that includes UI and depends on a service (that I assume handles connection to the backend), not only gives it 2 functional roles, namely:Controlling the UI for display/entry of data for the widget.Submitting to the backend (via the service).but also making it less re-usable, as you then can't use it again with another service, or with a different UI (at least not easily).When making these decisions, I often compare to the built-in HTML elements: for example <input>, <textarea> or <form>: they are completely independent of any specific backend. HTML5 has given the <input> element a few extra types, e.g. date, which is still independent of backend, and where exactly the data goes or how it is used. They are purely interface elements. Your custom widgets, built using directives, I think should follow the same pattern, if possible.However, this isn't the end of the story. Going beyond the analogy with the built-in HTML elements, you can create re-usable directives that both call services, and use a purely UI directive, just like it might use a <textarea>. Say you want to use some HTML as follows:<document document-url='documents/3345.html'> <document-data></document-data> <comments></comments> <comment-entry></comment-entry></document>To code up the commentEntry directive, you could make a very small directive that just contains the controller that links up a service with a UI-widget. Something like:app.directive('commentEntry', function (myService) { return { restrict: 'E', template: '<comment-widget on-save=save(data) on-cancel=cancel()></comment-widget>', require: '^document', link: function (scope, iElement, iAttrs, documentController) { // Allow the controller here to access the document controller scope.documentController = documentController; }, controller: function ($scope) { $scope.save = function (data) { // Assuming the document controller exposes a function getUrl var url = $scope.documentController.getUrl(); myService.saveComments(url, data).then(function (result) { // Do something }); }; } };});Taking this to an extreme, you might not ever need to have a manual ng-controller attribute in the HTML: you can do it all using directives, as long as each directly has a clear UI role, or a clear data role.There is a downside I should mention: it gives more moving parts to the application, which adds a bit of complexity. However, if each part has a clear role, and is well (unit + E2E tested), I would argue it's worth it and an overall benefit in the long term.
_unix.182654
I use grep -r all the time to find occurrences of a string within files in a given directory:$ grep -r string app/assets/javascripts> app/assets/javascripts/my_file.js: this line contains my stringBut what if I want to recursively search through more than one subdirectory of my current directory? The only way I can think of is to run grep twice:$ grep -r string app/assets/javascripts> app/assets/javascripts/my_file.js: this line contains string$ grep -r string spec/javascripts> app/assets/javascripts/my_file.js: string appears here, too.How can I combine the above two grep commans into a single line? I don't want to search through every single file in ., and --exclude-dir isn't practical because there are too many other directories under . for me to explicitly exclude them all.Is this possible?
How can I recursively grep through several directories at once?
grep;search;recursive
You can specifiy multiple directories in grep:grep -r string app/assets/javascripts spec/javascriptsAlternatively - sometimes more useful is list files to grep by find, and then grep them, for examplefind app/assets/javascripts spec/javascripts -type f -print0 | xargs -0 grep stringor find app/assets/javascripts spec/javascripts -type f -exec grep -H string {} +
_unix.246187
I am trying to write a service with timers. But it is not being executed:example@host /etc/systemd/system/mbsync.service:[Unit]Description=Mailbox synchronisation service for user example[Service]Type=oneshotExecStart=/usr/bin/mbsync -aVUser=exampleStandardOutput=syslogStandardError=syslogexample@host /etc/systemd/system/mbsync.timer:[Unit]Description=Mailbox synchronisation timer[Timer]OnBootSec=10sOnCalendar=*:00/2[Install]WantedBy=default.targetI started the service like this:systemctl daemon-reloadsystemctl enable mbsync.timersystemctl start mbsync.timerBut I only get:systemctl list-timersNEXT LEFT LAST PASSED UNIT ACTIVATESMon 2015-11-30 11:50:00 CET 10s ago Mon 2015-11-30 11:50:07 CET 2s ago mbsync.timer mbsync.service
systemd service with timer as user
systemd
Your timer is executed, but it may not do what you expect.You should check logs with systemctl status -l mbsync.service and tune your .mbsyncrc accordingly.I found these resources helpful:https://wiki.archlinux.org/index.php/Isync#Automatic_synchronizationhttps://www.bostonenginerd.com/posts/notmuch-of-a-mail-setup-part-1-mbsync-msmtp-and-systemd/especially the second one, with user unit files, which is required when using PassCmd gpg ....
_scicomp.5380
I am currently trying to link a program against the Intel MKL 11.0 library instead of using NetLIB or OpenBLAS. Doing this I recognized the following error which I can not explain to my self at the moment. Consider the following C code example computing a complex scalar product using zdotc:#include <stdio.h>#include <stdlib.h>#include <complex.h>double complex zdotc_(int *n, double complex *X, int *incx, double complex *Y, int *INCY ); int main ( ) { int n = 5; int incx = 1, incy = 1; double complex x[5] = {1,I,2,2+I,3}; double complex y[5] = {I,3,I*3, 2+2*I, 9}; double complex ret; ret = zdotc_(&n,x,&incx,y,&incy); printf(n = %d\n, n); printf(ret = %lg + %lgi\n, creal(ret), cimag(ret)); return 0; }I compiled this example using the command line flags given by the MKL Advisor. I select GNU C/C++, 32 Bit Integer, Dynamic Linking, GNU OpenMP. The resulting command line is:gcc zdotc_test.c -o zdot_mkl_gcc -O2 -L$MKLROOT/lib/intel64 -lmkl_intel_lp64 -lmkl_gnu_thread -lmkl_core -ldl -lpthread -lm -fopenmp -m64 -I$MKLROOT/includeThe output of this program is: n = 0ret = 0 + 1.07933e+21iwhich is obviously wrong and especially why is n altered?If I select GNU Fortran instead of GNU C/C++, I have to replace -lmkl_intel_lp64 by -lmkl_gf_lp64 and then the correct output n = 5ret = 33 + 6iis produced. So my question is: where are the detailed differences between those to interfaces and why does the first one produced this error?
Intel MKL - Difference between mkl_intel_lp64 and mkl_gf_lp64
blas;compiling
The difference has to do with the calling convention (ABI) differences. ZDOTC is a problematic function because it returns a double complex, which is usually considered a struct rather than a simple data type. Thus, it can either be returned on the stack as a return value, or by reference as an implicit first argument to the C style function. I am guessing that what you are seeing here is that in the _intel_ case, it expects the return value to be an implicit first argument, so it returns the value and ends up modifying n, and the return value is then just completely wrong. In that case the correct declaration isvoid zdotc_(double complex *retval, int *n, double complex *X, int *incx, double complex *Y, int *INCY );It's stupid stuff like this that makes me implement everything in C++ if possible. In particular, I tend to implement BLAS level 1 in C++, where performance is limited by memory bandwidth anyways. For BLAS levels 2 and 3, I will call actual BLAS, which does not have functions with this problem.I believe I've seen benchmarks before comparing naive dot product implementations with optimized BLAS, and if you use __restrict type keywords, most optimizing compilers will produce code that's as fast as the optimized BLAS.My own version is located here, where you would need the corresponding source file to provide forwarding of higher level BLAS, located here. I would refer you to Eigen, but my code is slightly easier to port to C99 since it's less heavily templated.
_unix.6751
I would like to use some the functions given by libc at the boot loader stage itself. Is it possible to get them at that stage of loading?
Is it possible to use libc at the bootloader stage itself?
boot loader
You'll most likely have to write your own versions of the functions you want, though in some cases you may be able to use libc source code as a starting point. The functions in libc itself are written under all the assumptions of a UNIX userspace program, including:the presence of the kernel (or more specifically, the syscall interface to the kernel)a flat memory modela dynamic linking infrastructure (unless statically linked)and at the bootloader stage, you have none of these. Instead, (by default, under Intel) you've got the BIOS, a segmented memory model, no memory protection, and full reign of the machine.It's the same reason you see the custom printk() function in kernel code instead of printf() -- the assumptions that libc's printf() makes just don't apply in kernel space.
_scicomp.14452
I have calculated the temperature of the section of a cylinder, which is subjected to a heat flow on its upper surface. Getting the temperature distribution in the 2D section. As shown in the following image. From this temperature distribution would represent the upper part of the cylinder as in the picture below.
a circular plot from a vector which represents the temperature along the radius surface, which is the same for every radius
matlab;visualization
If I understand, what you want is to make a polar plot of your data presented in the first image. Where, I assume, the axis are the radius and angle. You need to make a change of coordinates from polar to Cartesian to do that. Matlab has a built-in function for that called pol2cart (documentation). See an example hereYou can do something liker = linspace(0,1,1000);th = linspace(0,2*pi,1000);[TH,R] = meshgrid(th,r);[X,Y] = pol2cart(TH,R);Z = besselj(0,20*R);figurecontourf(X,Y,Z); axis squarefiguresurf(X,Y,Z); shading interphere it is the contour plot (in Octave, though):and