id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.80060
I'm trying to get a chrooted Apache environment working running mod_fcgid with suexec.Looking at suexec log inside jail, the wrapper scripts are being executed with no problems, however, when I look at Apache's error log I'm seeing the errors below;suexec failure: could not open log filefopen: Permission deniedsuexec.log;[2013-06-20 01:15:39]: uid: (500/user) gid: (500/user) cmd: php-fcgi-starter[2013-06-20 01:16:30]: uid: (500/user) gid: (500/user) cmd: php-fcgi-starter[2013-06-20 01:16:39]: uid: (500/user) gid: (500/user) cmd: php-fcgi-starter[2013-06-20 01:18:07]: uid: (500/user) gid: (500/user) cmd: php-fcgi-starter[2013-06-20 01:22:21]: uid: (500/user) gid: (500/user) cmd: php-fcgi-starterWhen I strace both php and suexec, they do not complain about any missing library or file. The log says could not open log file but it obviously logs into the error log file inside the jail. What's wrong with this setup? What may trigger this error?edit : strace results;[pid 9912] rt_sigaction(SIGCHLD, {SIG_DFL, [], SA_RESTORER|SA_INTERRUPT, 0x7fca687fe500}, {SIG_DFL, [], 0}, 8) = 0[pid 9912] chdir(/var/www/username/cgi-bin/) = 0[pid 9912] execve(/usr/sbin/suexec, [/usr/sbin/suexec, 500, 500, php-fcgi-starter], [/* 1 var */]) = 0[pid 9912] brk(0) = 0x7f2d71e91000[pid 9912] fcntl(0, F_GETFD) = 0[pid 9912] fcntl(1, F_GETFD) = 0[pid 9912] fcntl(2, F_GETFD) = 0[pid 9912] access(/etc/suid-debug, F_OK) = -1 ENOENT (No such file or directory)[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715f2000[pid 9912] access(/etc/ld.so.preload, R_OK) = -1 ENOENT (No such file or directory)[pid 9912] open(/etc/ld.so.cache, O_RDONLY) = 3[pid 9912] fstat(3, {st_mode=S_IFREG|0644, st_size=13704, ...}) = 0[pid 9912] mmap(NULL, 13704, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f2d715ee000[pid 9912] close(3) = 0[pid 9912] open(/lib64/libc.so.6, O_RDONLY) = 3[pid 9912] read(3, \177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\360\355\1\0\0\0\0\0..., 832) = 832[pid 9912] fstat(3, {st_mode=S_IFREG|0755, st_size=1916568, ...}) = 0[pid 9912] mmap(NULL, 3745960, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f2d71041000[pid 9912] mprotect(0x7f2d711cb000, 2093056, PROT_NONE) = 0[pid 9912] mmap(0x7f2d713ca000, 20480, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x189000) = 0x7f2d713ca000[pid 9912] mmap(0x7f2d713cf000, 18600, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f2d713cf000[pid 9912] close(3) = 0[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715f9000[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715ed000[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715ec000[pid 9912] arch_prctl(ARCH_SET_FS, 0x7f2d715ed700) = 0[pid 9912] mprotect(0x7f2d713ca000, 16384, PROT_READ) = 0[pid 9912] mprotect(0x7f2d715f3000, 4096, PROT_READ) = 0[pid 9912] munmap(0x7f2d715ee000, 13704) = 0[pid 9912] brk(0) = 0x7f2d71e91000[pid 9912] brk(0x7f2d71eb2000) = 0x7f2d71eb2000[pid 9912] getuid() = 48[pid 9912] socket(PF_FILE, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 3[pid 9912] connect(3, {sa_family=AF_FILE, path=/var/run/nscd/socket}, 110) = -1 ENOENT (No such file or directory)[pid 9912] close(3) = 0[pid 9912] socket(PF_FILE, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 3[pid 9912] connect(3, {sa_family=AF_FILE, path=/var/run/nscd/socket}, 110) = -1 ENOENT (No such file or directory)[pid 9912] close(3) = 0[pid 9912] open(/etc/nsswitch.conf, O_RDONLY) = 3[pid 9912] fstat(3, {st_mode=S_IFREG|0644, st_size=1688, ...}) = 0[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715f1000[pid 9912] read(3, #\n# /etc/nsswitch.conf\n#\n# An ex..., 4096) = 1688[pid 9912] read(3, , 4096) = 0[pid 9912] close(3) = 0[pid 9912] munmap(0x7f2d715f1000, 4096) = 0[pid 9912] open(/etc/ld.so.cache, O_RDONLY) = 3[pid 9912] fstat(3, {st_mode=S_IFREG|0644, st_size=13704, ...}) = 0[pid 9912] mmap(NULL, 13704, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f2d715ee000[pid 9912] close(3) = 0[pid 9912] open(/lib64/libnss_files.so.2, O_RDONLY) = 3[pid 9912] read(3, \177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\360!\0\0\0\0\0\0..., 832) = 832[pid 9912] fstat(3, {st_mode=S_IFREG|0755, st_size=65928, ...}) = 0[pid 9912] mmap(NULL, 2151824, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f2d70e33000[pid 9912] mprotect(0x7f2d70e3f000, 2097152, PROT_NONE) = 0[pid 9912] mmap(0x7f2d7103f000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xc000) = 0x7f2d7103f000[pid 9912] close(3) = 0[pid 9912] mprotect(0x7f2d7103f000, 4096, PROT_READ) = 0[pid 9912] munmap(0x7f2d715ee000, 13704) = 0[pid 9912] open(/etc/passwd, O_RDONLY|O_CLOEXEC) = 3[pid 9912] fcntl(3, F_GETFD) = 0x1 (flags FD_CLOEXEC)[pid 9912] fstat(3, {st_mode=S_IFREG|0644, st_size=952, ...}) = 0[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715f1000[pid 9912] read(3, root:x:0:0:root:/root:/bin/bash\n..., 4096) = 952[pid 9912] close(3) = 0[pid 9912] munmap(0x7f2d715f1000, 4096) = 0[pid 9912] open(/etc/passwd, O_RDONLY|O_CLOEXEC) = 3[pid 9912] fstat(3, {st_mode=S_IFREG|0644, st_size=952, ...}) = 0[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715f1000[pid 9912] read(3, root:x:0:0:root:/root:/bin/bash\n..., 4096) = 952[pid 9912] close(3) = 0[pid 9912] munmap(0x7f2d715f1000, 4096) = 0[pid 9912] socket(PF_FILE, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 3[pid 9912] connect(3, {sa_family=AF_FILE, path=/var/run/nscd/socket}, 110) = -1 ENOENT (No such file or directory)[pid 9912] close(3) = 0[pid 9912] socket(PF_FILE, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0) = 3[pid 9912] connect(3, {sa_family=AF_FILE, path=/var/run/nscd/socket}, 110) = -1 ENOENT (No such file or directory)[pid 9912] close(3) = 0[pid 9912] open(/etc/group, O_RDONLY|O_CLOEXEC) = 3[pid 9912] fstat(3, {st_mode=S_IFREG|0644, st_size=520, ...}) = 0[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715f1000[pid 9912] read(3, root:x:0:root\nbin:x:1:root,bin,d..., 4096) = 520[pid 9912] close(3) = 0[pid 9912] munmap(0x7f2d715f1000, 4096) = 0[pid 9912] open(/var/log/httpd/suexec.log, O_WRONLY|O_CREAT|O_APPEND, 0666) = 3[pid 9912] fstat(3, {st_mode=S_IFREG|0644, st_size=17043, ...}) = 0[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715f1000[pid 9912] fstat(3, {st_mode=S_IFREG|0644, st_size=17043, ...}) = 0[pid 9912] lseek(3, 17043, SEEK_SET) = 17043[pid 9912] gettimeofday({1371690955, 897472}, NULL) = 0[pid 9912] open(/etc/localtime, O_RDONLY) = 4[pid 9912] fstat(4, {st_mode=S_IFREG|0644, st_size=2102, ...}) = 0[pid 9912] fstat(4, {st_mode=S_IFREG|0644, st_size=2102, ...}) = 0[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715f0000[pid 9912] read(4, TZif2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\4\0\0\0\4\0\0\0\0..., 4096) = 2102[pid 9912] lseek(4, -1337, SEEK_CUR) = 765[pid 9912] read(4, TZif2\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\4\0\0\0\4\0\0\0\0..., 4096) = 1337[pid 9912] close(4) = 0[pid 9912] munmap(0x7f2d715f0000, 4096) = 0[pid 9912] write(3, [2013-06-20 03:15:55]: uid: (500..., 77) = 77[pid 9912] setgid(500) = 0[pid 9912] open(/proc/sys/kernel/ngroups_max, O_RDONLY) = -1 ENOENT (No such file or directory)[pid 9912] open(/etc/group, O_RDONLY|O_CLOEXEC) = 4[pid 9912] fstat(4, {st_mode=S_IFREG|0644, st_size=520, ...}) = 0[pid 9912] mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f2d715f0000[pid 9912] lseek(4, 0, SEEK_CUR) = 0[pid 9912] read(4, root:x:0:root\nbin:x:1:root,bin,d..., 4096) = 520[pid 9912] read(4, , 4096) = 0[pid 9912] close(4) = 0[pid 9912] munmap(0x7f2d715f0000, 4096) = 0[pid 9912] setgroups(1, [500]) = 0[pid 9912] setuid(500) = 0[pid 9912] getcwd(/var/www/username/cgi-bin, 4096) = 22[pid 9912] chdir(/var/www) = 0[pid 9912] getcwd(/var/www, 4096) = 9[pid 9912] chdir(/var/www/username/cgi-bin) = 0[pid 9912] lstat(/var/www/username/cgi-bin, {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0[pid 9912] lstat(php-fcgi-starter, {st_mode=S_IFREG|0755, st_size=128, ...}) = 0[pid 9912] close(3) = 0[pid 9912] munmap(0x7f2d715f1000, 4096) = 0[pid 9912] execve(php-fcgi-starter, [php-fcgi-starter], [/* 1 var */]) = -1 ENOENT (No such file or directory)[pid 9912] open(/var/log/httpd/suexec.log, O_WRONLY|O_CREAT|O_APPEND, 0666) = -1 EACCES (Permission denied)[pid 9912] write(2, suexec failure: could not open l..., 40) = 40[pid 9912] write(2, fopen: Permission denied\n, 25) = 25[pid 9912] exit_group(1) = ?the last ~20 lines is where the server throws the error.
suexec with chrooted environment
permissions;apache httpd;php;chroot;suexec
null
_unix.112143
I would like to know if my desktop computer supports USB 3.0, but from the output below this seems unlikely.I get the following output from lspci: root@liv-HP-Compaq-dc7900:/home/liv# lspci -v | grep -i usb00:1a.0 USB controller: Intel Corporation 82801JD/DO (ICH10 Family) USB UHCI Controller #4 (rev 02) (prog-if 00 [UHCI])00:1a.1 USB controller: Intel Corporation 82801JD/DO (ICH10 Family) USB UHCI Controller #5 (rev 02) (prog-if 00 [UHCI])00:1a.2 USB controller: Intel Corporation 82801JD/DO (ICH10 Family) USB UHCI Controller #6 (rev 02) (prog-if 00 [UHCI])00:1a.7 USB controller: Intel Corporation 82801JD/DO (ICH10 Family) USB2 EHCI Controller #2 (rev 02) (prog-if 20 [EHCI])00:1d.0 USB controller: Intel Corporation 82801JD/DO (ICH10 Family) USB UHCI Controller #1 (rev 02) (prog-if 00 [UHCI])00:1d.1 USB controller: Intel Corporation 82801JD/DO (ICH10 Family) USB UHCI Controller #2 (rev 02) (prog-if 00 [UHCI])00:1d.2 USB controller: Intel Corporation 82801JD/DO (ICH10 Family) USB UHCI Controller #3 (rev 02) (prog-if 00 [UHCI])00:1d.7 USB controller: Intel Corporation 82801JD/DO (ICH10 Family) USB2 EHCI Controller #1 (rev 02) (prog-if 20 [EHCI])And from lsusb: root@liv-HP-Compaq-dc7900:/home/liv# lsusb Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubBus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubBus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubBus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubBus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubBus 008 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubBus 001 Device 002: ID 0cf3:9271 Atheros Communications, Inc. AR9271 802.11nBus 004 Device 002: ID 046d:c52b Logitech, Inc. Unifying ReceiverBus 002 Device 004: ID 090c:1000 Silicon Motion, Inc. - Taiwan (formerly Feiya Technology Corp.) 64MB QDI U2 DISKFollowing All USB ports detected as USB 1.0, not USB 2.0, I'm also posting output of lsusb -t:root@liv-HP-Compaq-dc7900:/home/liv# lsusb -t/: Bus 08.Port 1: Dev 1, Class=root_hub, Driver=uhci_hcd/2p, 12M/: Bus 07.Port 1: Dev 1, Class=root_hub, Driver=uhci_hcd/2p, 12M/: Bus 06.Port 1: Dev 1, Class=root_hub, Driver=uhci_hcd/2p, 12M/: Bus 05.Port 1: Dev 1, Class=root_hub, Driver=uhci_hcd/2p, 12M/: Bus 04.Port 1: Dev 1, Class=root_hub, Driver=uhci_hcd/2p, 12M |__ Port 2: Dev 2, If 0, Class=HID, Driver=usbhid, 12M |__ Port 2: Dev 2, If 1, Class=HID, Driver=usbhid, 12M |__ Port 2: Dev 2, If 2, Class=HID, Driver=usbhid, 12M/: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=uhci_hcd/2p, 12M/: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/6p, 480M |__ Port 5: Dev 6, If 0, Class=stor., Driver=usb-storage, 480M/: Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/6p, 480M |__ Port 3: Dev 2, If 0, Class=vend., Driver=ath9k_htc, 480MDo I understand correctly that only two slots support USB 2.0? And if so, how can I pinpoint exactly which physical slot supports USB 2.0?
Which USB slot is 2.0 or 3.0? How do I know?
usb
There are a number of questions.To the first bunch of questions, your computer's chipset doesn't support USB3. You could add a plugin card that provides USB3 ports - in that case, only the ports provided on the card are USB3, while your existing ports remain USB2.See http://www.newegg.com/Product/Product.aspx?Item=N82E16815166026 (for a laptop) or http://www.newegg.com/Product/Product.aspx?Item=N82E16839314014 (for a desktop computer) as example.As to your last question, which ports are USB1 and which are USB2: All ports are both.The USB1 (UHCI) controllers are called companion controllers in the USB standard. By default, all ports are routed there (for compatibility with operating systems without EHCI driver), but in a way that the USB2 (EHCI) controller can take over if the USB driver detects a USB2 device.This means that when you attach a USB1 device (eg. a keyboard) and a USB2 device (eg. a thumb drive) to the same port, they will appear at different locations in the lsusb output. The USB2 device will end up at an EHCI controller while the USB1 device ends up at an UHCI controller. There is no 1:1 relation between physical ports and controllers.You can determine the mode a device is operating under in lsusb in the device line itself: Port 2: Dev 2, If 0, Class=HID, Driver=usbhid, 12M, 12M means 12MBit/s = USB1, 480M = 480MBit/s = USB2, 5000M = 5000MBit/s = USB3.It's different with USB3 since it comes with a different port design - 9 lines in two rows instead of 4 in one, and many devices come with dedicated USB3 ports and some additional USB2 ports (since they're cheaper).To easily identify them, the USB3 standard mandates that USB3 ports must have a blue insert.
_softwareengineering.126469
I am not much familiar with documenting/System designing stuff.I have to maintain an application written in C# - working as windows service.However there is no documentation for this system which makes it really pathetic to find where some problem (conceptually) occurred.I would like to know the best way to design/document it (using current code) manually or preferably automatically so that I can identify the exact problems.Like I feel as if sequence diagram won't much help probably.Also, please guide me if I am taking it on wrong side?
Design Document From Code
documentation;maintenance;design
null
_unix.67099
I have to disable Visual Effects (system -> preferences-> appearance -> visual effects -> none) because I get a terrible flicker/blinking when it is enabled, but I'd really like to use compiz window grid shortcuts. They only work w/ visual effects set to extra. Is there any way to specifically enable compiz grid functionality without turning on everything else that seems to bog down the grapics?Thanks.
Enable compiz window grid with visual effects set to none. Ubuntu 10.04
ubuntu;window manager;compiz
null
_unix.271289
I downloaded a subtitle from subscene http://subscene.com/subtitles/the-5th-wave/english/1298314 and it contains some coding such as :<i> and </i> which is not being decoded by my player mpv . As can be seen the subtitle is in .srt (Subrip Text) format. https://matroska.org/technical/specs/subtitles/srt.html Here's a full dialog so that it may make sense. 2800:03:37,080 --> 00:03:39,280CASSIE:<i> I miss the Cassie I was.</i>I want to fix this so that the codes are not visible during play but don't know how. Can somebody help. I am on Debian testing and using mpv [$] mpv --version (null) requires an argumentmpv 0.14.0 (C) 2000-2015 mpv/MPlayer/mplayer2 projects built on UNKNOWNffmpeg library versions: libavutil 54.31.100 libavcodec 56.60.100 libavformat 56.40.101 libswscale 3.1.101 libavfilter 5.40.101 libswresample 1.2.101ffmpeg version: 2.8.6-1+b2Look forward to how this can be fixed. Those codes are throughout the whole .srt file so its a bit disconcerting at best.
What does :<i> code stand for in subtitles?
text processing
Looks like someone tried to use HTML tags for the subtitles and tried to make the fonts italic. In my limited HTML knowledge, &lt; stands for less than sign, i.e. < and &gt; stands for >. So CASSIE:&lt;i&gt; I miss the Cassie I was.&lt;/i&gt;can be visualized as CASSIE:<i> I miss the Cassie I was.</i>as you can easily see this is Italic code and the video player doesn't understand html tags. I am pretty sure they can be removed by few select sed/awk combinations, something likesed 's/\&lt\;i\&gt\;//; s+\&lt\;/i\&gt\;++' somefile.srt >somefile-nohtml.srt
_softwareengineering.329488
So I'm coding a way to send events to multiple clients, and then having the clients decide how they want to handle it. I'll exclude the bits that don't lend themselves to explaining the situation.class Event_Beacon def add_event_eater( self, ee ): self.event_eaters.add( ee ) def broadcast_event( self, e ): for e in self.event_eaters: e.receive_event( e )Now, with the above, I can create an instance of an Event_Beacon and pass it around. I'm thinking I should stop future me from possibly abusing all that access to the Event_Beacon. For example, say, I have an Event_Maker. It makes sense for this Event_Maker to have access to the broadcast_event method, but not really add_event_eater. If I just passed it the event beacon instance, I could on some future extension of this particular event maker, haphazardly hack in an add_event_eater inside the event maker.So, is it good practice to create a limiting interface so that I only give another object exactly what it needs and nothing more? Something like:class Event_Beacon_Broadcast_Remote def __init__( self, event_beacon ): self.beacon = event_beacon def broadcast_event( self, e ): self.beacon.broadcast_event( e ) # note the lack of add_event_eater in this interface
Is it good practice to create interfaces that limit usage?
programming practices;interfaces
It is a good idea if you really have the explicit requirement for two different interfaces. That is typically the case when you have to stop others from possibly abusing your existing interface, and you are designing a reusable component or library which needs to provide different access from outside of the component than from inside.However, creating such interfaces just in case, for some hypothetical (or superstitous) scenario is a violation of the YAGNI principle, it will only add unnecessary, boilerplate code which makes your software harder to be maintained and evolved. (For example, for you or your team it may be mostly sufficient to add a comment like do not use remotely above the add_event_eater method.)You have to decide by yourself if in the shown situation to stop future you from abusing the interface falls into the first or the second category. It can be the one or the other, but one has to know the use cases and requirements of your system, the clients of the API and the environment to make a decision, so that is nothing we can decide for you.
_unix.23916
I have some problems with my system performance. As I was adviced here, I used sar: $sar -u 5and found out that the problems are caused by a low HDD performance, as I supposed (high %iowait). My disk is Western Digital AV-25, WDC WD5000BUDT-63G8FY0. Vendor specification can be found here. /etc/fstab:# <file system> <dir> <type> <options> <dump> <pass>devpts /dev/pts devpts defaults 0 0shm /dev/shm tmpfs nodev,nosuid 0 0/dev/sda2 / ext4 defaults,noatime,data=writeback,barrier=0,nobh,errors=remount-ro 0 1/dev/sda3 /home ext4 defaults,noatime,data=writeback,barrier=0,nobh,errors=remount-ro 0 1/dev/sda4 swap swap defaults 0 0The problem is that from time to time some application (Minecraft game, Chromium browser, Eclipse) hangs up, my processor activity LED turns on, iowait goes to some 50% or more (I have dual core processor) and stays like this for a couple of seconds. Similar things happen when I use applications for the first time after reboot. The worst situation ever was forcing the system to use the swap partition (by some stress tool), the system went unusable.What can i do now to determine the exact cause of the performance problems? Is it the low hardware performance, some problems with linux io scheduler, application specific problems or something else?EDIT:Output of hdparm -t -T /dev/sda under no load:/dev/sda: Timing cached reads: 6244 MB in 2.00 seconds = 3129.13 MB/sec Timing buffered disk reads: 230 MB in 3.01 seconds = 76.33 MB/sec
GNU/Linux, IO performance problems
linux;performance;disk usage;io
null
_codereview.98733
I have two links in my header:RegisterLoginI am not creating it dynamically. If the user clicks on login, the login form will be visible, similarly for the register form.My registration:<?php include 'configdb.php'; global $connection; if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['email']) && !empty($_POST['password'])) { /* *Get Details From User Table To Check Whether User Is Registered Already *Used Prepare Statement To Avoid SQL Injection */ if($getUserData = mysqli_prepare($connection,SELECT emailID FROM users WHERE emailID = ?)) { mysqli_stmt_bind_param($getUserData,s,$_POST['email']); mysqli_stmt_execute($getUserData); mysqli_stmt_store_result($getUserData);/*It Is Required To Get Number Of Rows By stmt_num_rows Method */ //mysqli_stmt_fetch($getUserData); } /* *Check Whether ResultSet Is Empty *If Not Empty, Return This JSON Error Message */ if (mysqli_stmt_num_rows($getUserData) > 0) { mysqli_stmt_close($getUserData); die( '{ status:1, message:Email Already Exists }' ); } else { $email = htmlentities($_POST['email'], ENT_QUOTES, UTF-8); $password = password_hash(htmlentities($_POST['password'], ENT_QUOTES, UTF-8), PASSWORD_DEFAULT); $com_code = md5(uniqid(rand())); /* It Will Be Used Later For Confirmation-link*/ if($insertData = mysqli_prepare($connection, INSERT INTO users (emailID, password, com_code) VALUES(?,?,?))) { mysqli_stmt_bind_param($insertData, sss, $email, $password, $com_code); mysqli_stmt_execute($insertData); //print_r($insertData); - Handle error by checking num_rows in the object insertdata } else { print_r(Prepared statement error); } //$_SESSION['username'] = $_POST['email']; die('{ status:0, message:Registration Successful }'); } } ?>My Ajax method/*** * @param form* * AJAX METHOD FOR REGISTER*/function callAjaxRegisterSubmitMethod(form){ $.ajax({ type: POST, url: lib/registration_validate.php, data: $(#id_registerForm).serialize(), dataType: 'json', beforeSend: function() { $(.cls_register_login_error label, .cls_register_login_error .error_link).text(''); }, success: function(response,status,jqXHR) { //Show homepage if(response.status == 1) { $(.cls_register_login_error .cls_register_login_error_message).text(response.message+. Try); $(.cls_register_login_error .error_link).text(login); $(.cls_register_login_error .error_link).addClass(enable_login); $(.cls_register_login_error .error_link).removeClass(enable_register); $(.cls_registerForm input[type='password']).val(''); } else if(response.status == 0) { console.log(Registered Successfully); alert(Registered Successfully); //$(.body_content).load(,function(){}); } else { console.log(Common Success Error Page); } }, error:function(jqXHR,status,error) { console.log(Common Error Page); }, complete:function(response) { } });}Please let me know of any problems with this approach.And I am planning to use load method to load my homepage into contnets div because I have fixed header and footer which is common for all the pages.
Website register functionality
javascript;php;jquery;html
htmlentities is used to protect against XSS, and should be used when echoing data, not when inserting it into the database. Your approach leads to bad data (for example, now you always have to use htmlentities when checking a password, as it will otherwise be wrong), and weak security (using htmlentities before inserting data leads to it not being used when echoing - because it's already been encoded - which leads to data being forgotten, because nobody can remember what was encoded and what was not).MiscFunctions: I would extract code blocks to functions. It makes those blocks reusable and leads to more readable code. Possible functions are eg getUserByEmail and insertUser.rename $com_code to $confirmationCode, so it's clear what it is without reading the comments.always use camelCase or always use snake_case for variables, don't mix this.uniqid and rand are not good at creating random values. Even though a confirmation token isn't that sensitive, I would still use something like openssl_random_pseudo_bytes instead.be more consistent with your spacing (eg after ,).your error handling could be more consistent. Eg sometimes you handle the else case of mysqli_prepare, and sometimes you don't; you never check the result of mysqli_stmt_execute. It is possible that the user will get the following error message: Prepared statement error [...] Registration Successful.your comments are mostly not necessary. And those that are - eg the one about confirmation - would not be with better variable names and code extracted to well named functions (which could then have proper PHPDoc type comments). Having too many comments that don't add any new information is not good, because after a while a reader will just ignore all your comments, even the important ones.
_webmaster.98392
I have three different cases in mind. One is a company website, other is a blog and the other one shop.How to handle support for many languages? How this affect SEO positioning?BlogIn the case of blog I guess the best way is to create parent categories per language (in case you are writing some articles in example in Spanish or English only) and add google translate toolbar maybe?ShopIf you point to a global market I guess you have all in English and local language if different?CompanyHere is where I have most doubts, in example a marketing company which scope is global, should they create subdomains en.company.com? es.company.com? or company.com/es, how they handle articles in their blog?Thanks for all ideas in advance.
How to handle a website with different languages
seo;duplicate content;content;multilingual
null
_unix.269603
I've been having a problem loading software that use xcb, such as vlc and plasma desktop. Vlc gives the following error:[0000000000ddc148] core libvlc: Running vlc with the default interface. Use 'cvlc' to use vlc without interface.This application failed to start because it could not find or load the Qt platform plugin xcb.Available platform plugins are: linuxfb, minimal, minimalegl, offscreen, wayland-egl, wayland.Reinstalling the application may fix this problem.AbortedI have libxcb1 and libx11-xcb1 installed; reinstalling them and vlc didn't fix the problem.
Unable to find or load Qt platform plugin xcb on debian strech
debian;vlc;qt
On what system? From the tags I'm assuming you are running Debian?On debian jessie and testing, the xcb plugin is in the libqt5gui5 package, but vlc depends on it. On some older versions of qt5 packaging, the package containing the qpa plugin used to be libqt5xcbqpa5.
_unix.186557
I'm planning to follow the steps described in this answer to have a different password to log in and sudo. The reason is that I want a high security password to access my account or unblock the screensaver, but I don't want to type it every time I need to sudo something.My questions: is there any security issue I should be aware of by making this change? Will my protection be weaker than having the same super-secure password for everything (for example, root can log in with the insecure password)? Is there any better way to archive this?Please consider even the worst-case scenario, ie, the attacker has physical access to my computer (logged out from my account).Some details probably worth mentioning: No other user account in my computer is sudoer (nor will be). home directory encrypted.
Different password for login and sudo - security concerns
security;sudo;login;password
null
_codereview.151237
I'm a .NET (C#/VB) developer who knows a little C and happens to need to write a native C++ Windows DLL.Please have a look at the following code and tell me if the string operations are idiomatic C++:int dpi;void __stdcall FooEntryPoint(ENTRY_INFO* inEntryInfo){ dpi = *reinterpret_cast<int *>(inEntryInfo->UserData); OutputDebugStringW((std::wstring(LUser Data supplied: ) + std::to_wstring(dpi)).c_str()); FARPROC address = GetFooAddress(); if (address == NULL) { OutputDebugStringW(LFoo address not found.\n); return; } NTSTATUS result = FrobnicateFoo(address); if (FAILED(result)) { OutputDebugStringW((std::wstring(LFailed to frobnicate foo: ) + RtlGetLastErrorString() + L\n).c_str()); }}My thoughts on the matter:As a .NET developer, I'm used to Unicode is default unless there's a very good reason against it, and, thus, I just use L... string literals and ...W API methods without giving it further thought.(std::wstring(...) + ... + ...).c_str() seems to be the simplest way in C++ to do string concatenations of wchar arrays (denoted as ...) without having to worry about memory allocations. I could use wostringstream, but it would just make the code more complicated.I know that failing silently is bad practice, but the signature of FooEntryPoint is part of the interface contract I'm given, so this is by design.Does that make sense or am I violating any good C++ practices here?Note: The code does not need to be portable.
Simple string operations in C++
c++;strings;windows
Some thoughts:It is good that you explicitly annotated the function's definition with its required calling convention. Make sure that you do the same thing for the declaration in the public C++ header, and for the P/Invoke declaration (if applicable) in your .NET application.Calling convention mismatches are a common source of bugs, and you don't want to rely on the correct compiler flags (specifying the default calling convention) having to be specified in order for the code to work correctly.This line:dpi = *reinterpret_cast<int *>(inEntryInfo->UserData);hoists a giant red flag, for at least a couple of reasons:Why is dpi a global (module-scoped?) variable? It looks to me like it just needs to be a local variable. I'm assuming that you raised its scope so it would be usable within the GetFooAddress and/or FrobnicateFoo functions? If so, you should pass it as a parameter to these functions. Always keep the scope of variables to the minimum level necessarythis is the same rule as in C#/VB.NET, of course.That reinterpret_cast business is dicey. Reinterpretation casts are always a bit dicey, and this one especially, since it doesn't have a reassuring comment nearby that explains how it is safe. :-) You didn't show us the definition of the ENTRY_INFO type, so it's hard to confirm whether or not this actually is safe, but there really aren't that many cases where you can legitimately reinterpret a pointer to one primitive type as a pointer to another primitive type. If I had to guess, I'd say that UserData is a void*? If at all possible, you should just change it to be the int* that you ultimately want. The only advantage of a void* would be to achieve something akin to VB's Variant, but that requires some way to determine what the actual type is. Your code doesn't have that, it just assumes that the pointer is actually to an int. Lots of different ways that can go wrong. Hard to say exactly how you should fix this without more information, but definitely know that this smells funny and very likely hides a bug.Beyond the question of the cast, you are potentially dereferencing a null pointer, which is undefined behavior and definitely a bug. You need to be checking this explicitly, just like you are all of the other error conditions, unless you can guarantee that the caller will never pass you a null pointer (in which case, verify that assumption using an assert).As a .NET developer, I'm used to Unicode is default unless there's a very good reason against it, and, thus, I just use L... string literals and ...W API methods without giving it further thought.This is completely correct. In fact, this doesn't have anything to do with .NET; it is more precisely a Windows thing. The Windows operating system uses Unicode internally (at least, all versions of NT do, which means everything modern and semi-modern), and there is no reason to ever use narrow/ANSI strings unless you need the code to run on Windows 9x. Therefore, your adopted practices make very good sense.(std::wstring(...) + ... + ...).c_str() seems to be the simplest way in C++ to do string concatenations of wchar arrays (denoted as ...) without having to worry about memory allocations.Indeed, the + operator is the simplest way to concatenate strings in C++. However, it is not necessarily the most efficient. Use of the + operator is creating a bunch of temporaries, which the compiler may or may not be able to optimize out. In general, you should prefer the += operator to help stave off the proliferation of temporary objects (or the append member function, which is slightly less terse, but may be easier to reason about because there are no operator precedence concerns).Also, not having to worry about memory allocations may be a curse disguised as a blessing. In general, pre-allocating the required amount of space (using the reserve member function) will net you better performance than letting the library code do incremental allocations as-needed, assuming of course that you have some idea in advance of how much space you will need.That said, neither of these things matter if the code you're writing is not performance-sensitive. And obviously this isn't, since it's calling OutputDebugString, which is a very slow function.We're talking about a few bytes here. Isn't that a case of premature optimization? Or is it generally good practice in C++ to worry about such things?Yes, it is probably good practice in C++ to worry about such things. A major reason for people to write code in C++ is because they care about efficiency.I could use wostringstream, but it would just make the code more complicated.Well, that is arguable, and I see that already made the argument. This is ultimately up to you: either will work, and since debug output is not performance-sensitive, there isn't a clear case to be made either way as far as I'm concerned. However, on the readability front, you can actually get a similar effect by using the += operator (which I'd recommended anywaysee code below).I do want to quibble slightly with one thing said, thoughor at least, my interpretation of what he said While it is, in general, completely true that more lines of code do not make a program slower or more complicated, using stream output probably is going to be slower than simple string concatenation. I would only resort to streams if I needed to format the output in some way.Also, speaking of OutputDebugString, this is almost certainly a function that you only want to call in debugging builds. It won't be conditionally compiled out like the equivalent Debug functions in .NET; you have to do this manually. The simplest way is to use a preprocessor conditional, something like:#ifdef DEBUG OutputDebugStringW(...)#endif // DEBUGAnother alternative would be to write your own TRACE macro (MFC and other commonly used C++ libraries have one included) that either expands to a call to OutputDebugString or to a no-op, depending on the build settings. For example:#ifdef DEBUG #define TRACE(str) OutputDebugStringW(str)#else #define TRACE(str) (void)(str)#endif // DEBUGThere are all sorts of ways to make this more complicated, more flexible, and more useful. In fact, you might not decide that you don't want to base it on the definition of a DEBUG preprocessor symbol at all, since you might want this debug trace available in an instrumented but otherwise optimized build. However, I would not recommend spewing a bunch of debug info in a shipping build. It is slow and unhelpful to the typical user.If you really need this information for remote debugging, you should almost certainly be writing it into a log file, instead, since OutputDebugString is effectively an expensive no-op if there is no debug listener attached! Investigate a logging framework for C++, or write your own if you have unlimited time on your hands. Either way, make it so that this verbose mode can be enabled as a run-time option at the request of your technical support staff.One last point about OutputDebugString: I personally believe that any string you pass to it should always end with a trailing new-line character. It doesn't get inserted automatically, so multiple back-to-back calls to OutputDebugStringeven in completely different moduleswill result in cluttered and unreadable output otherwise. A TRACE macro could certainly automatically append this \n, though.I know that failing silently is bad practice, but the signature of FooEntryPoint is part of the interface contract I'm given, so this is by design.Fair enough, but I have to again agree with that you should be using an assert here for ease of debuggingunless that is, failure is an expected scenario.You should be aware, though, that idiomatic C++ would use exceptions for things like this that cannot reasonably be handled by the callee, just like idiomatic C#/VB.NET code. This wouldn't affect the signature (the function would still return void), but it would certainly affect the interface, so I realize that may not be an option for you.Instead of the NULL macro that you would use in C code, modern C++ code should prefer to use nullptr for a variety of reasons. You can basically use it as a drop-in replacement, with the advantage that it is a distinct type so it won't ever be ambiguous with the integer literal 0.I also like to obsessively make every local variable that I'm not going to change in subsequent code const. Although this doesn't really enable any additional optimizations, it makes it easier for me to reason about the code and increases the likelihood that the compiler will catch bugs. In fact, I'm of the opinion that const should have been the default for locals, and you should have had to explicitly mark them as mutable if you wanted that. As a case in point, I would make the address and result variables explicitly const.My last observation is almost purely stylistic, and probably at least somewhat controversial, but I would format the code differently to ensure only a single exit point. I'm not at all dogmatic about this, but I think in this particular case it is clearer to think about the operations you're doing in a chain or hierarchy, so it is natural to format them as a series of nested blocks:const FARPROC address = GetFooAddress();if (address != nullptr){ const NTSTATUS result = FrobnicateFoo(address); if (FAILED(result)) { #ifdef DEBUG std::wstring str = (LFailed to frobnicate foo: ); str += RtlGetLastErrorString(); str += L\n; OutputDebugStringW(str.c_str()); #endif // DEBUG }}else{#ifdef DEBUG OutputDebugStringW(LFoo address not found.\n);#endif // DEBUG}I'm neutral on whether the error condition (address == NULL) should come first, or whether the success condition should come first. There are readability arguments both ways. I tend to prefer putting the success condition first to increase the likelihood of successful static branch prediction, but that's becoming a non-issue on current generations of processors that don't simply assume not taken for all forward conditional jumps. I just wrote a crazy-long answer about this that ultimately concludes it doesn't matter.
_unix.116719
Is there any way to amalgamate days of sysstat logs, so one could view a whole week in kSar for example?Currently I can only see individual days, loaded one at a time, or in separate windows.
Is there any way to view several days of sysstat logs in kSar?
logs;sysstat
null
_webapps.103384
I've setup case management in my application. Now I would like to load the selected case's id into the Calculate Condition of one of my hidden variables. How do I do that?
How do you load a case_id into a form
commcare
You can use the session instance path to get the currently selected case's case_id (see CommCare Session Instance help page):instance('commcaresession')/session/data/case_idThe link above also describes the syntax to load other session user or device data.
_codereview.110966
I have the following class for Quicksorting.import java.util.Random;public class QuickSorter { public static void main(String[] args) { Random random = new Random(); int[] randoms = new int[10000]; for(int i = 0; i < randoms.length; i++) randoms[i] = random.nextInt(10000); quickSort(randoms, 0, randoms.length); System.out.println(Arrays.toString(randoms)); } /** Same as {@link #quickSort(int[], int, int)}, but assumes the whole array should be sorted. */ public static void quickSort(int[] in) {quickSort(in, 0, in.length);} /** Sorts an array of integers using the Quicksort algorithm, in the range [{@code start}, {@code end}). * @param in The full array to sort * @param start The starting index, inclusive * @param end The ending index, exclusive * @see #quickSort(int[]) */ public static void quickSort(int[] in, int start, int end) { int pivot = (start + end) / 2; /* Temporary array containing the ordered sub-list */ int[] sub = new int[end - start]; int left = 0, right = sub.length; /* Populate the sub-list */ for(int i = start; i < end; i++) { if(i == pivot) continue; if(in[i] < in[pivot]) { sub[left++] = in[i]; } else { sub[--right] = in[i]; } } /* Add in the original pivot in its new position */ sub[left] = in[pivot]; /* Copy back into the original array */ for(int k = start; k < end; k++) { in[k] = sub[k - start]; } /* Translate new pivot position into full list index */ left += start; if(left - start > 0) quickSort(in, start, left); /* The start of the right branch should not include the pivot */ left++; if(end - left > 0) quickSort(in, left, end); }}Is this the most efficient way to Quicksort? I feel as if copying the values from sub back into in can be done better somehow.And of course, I know this won't cause any huge issues with arrays of size 10000. But, I'd like this to hold up all the way up to 2^31-1 (to the limits of max array size).
A simple quicksort implementation
java;quick sort
Integer overflowSince you said you cared about array sizes up to the max size, you should know that this line could cause an overflow with two large indices, meaning that pivot could become negative: int pivot = (start + end) / 2;You can fix this by using the following expression instead: int pivot = start + (end - start) / 2;Skip subarrays of length 1You can do slightly better by ignoring subarrays of length 1, since they are already sorted. In other words, this line: if(left - start > 0) quickSort(in, start, left);could be: if(left - start > 1) quickSort(in, start, left);The same goes for the right subarray.In-place version should be fasterAlthough there is nothing incorrect with your version, it allocates a temporary array and copies elements back and forth. If you switched to an in-place algorithm, you will reduce your array writes by 50%. This means that the in-place version should be faster than your current version, assuming you use a proper version that swaps elements from both ends working inwards.
_cs.48931
Which general machine-learning methods are there that try to learn or interpolate a smooth multivariate function and which get to actually choose the points at which the function is evaluated during the learning process (exploration)?The idea would be that each function evaluation is more or less costly and the algorithm learns to explore the regions of space where the gain of knowledge is greatest (vs. the cost of evaluating the function). The function may be non-analytic (e.g. with kinks) in the most interesting cases.My background is physics, and I am sure that such methods exist, but despite some searching I could not find something that is directly relevant, possibly because I do not know the right terms to look for. I only know that more broadly speaking 'reinforcement learning' is the area of AI dealing with exploration and rewards, so maybe the methods I am asking for represent some special case of that.For clarification, here is an example: You might want to get the phase diagram of a substance, i.e. the density as a function of pressure p and temperature T. So we are dealing with a (mostly) smooth function of two variables (p,T). Its evaluation at any given point (p,T) requires an expensive Monte-Carlo simulation (lots of CPU time; how much even depends on where in the p,T-space you are). The ideal algorithm would judiciously pick points (p,T) at which to evaluate the density, trying to go towards regions where the function has the most salient features (e.g. phase transition lines, i.e. non-analyticities). Then afterwards, when you ask the algorithm for the density at any other point (p,T), it provides the best possible interpolation/extrapolation that it can come up with, given all the information it has acquired during its exploratory phase.
Exploring and interpolating a function using machine-learning?
machine learning;artificial intelligence
I would look into the field of optimal experimental design in bayesian inverse problems, particularly the recent work of Alen Alexandrian.http://arxiv.org/abs/1410.5899http://www4.ncsu.edu/~aalexan3/research.htmlEssentially, one has an inner inverse problem for approximating the function based on point measurements of derived quantities, hosted within an outer optimization problem for choosing the points based on minimizing a combination of the error and the variance.Furthermore, you don't need to do a full inner-outer solve procedure. Rather, you can use the KKT conditions for the inner problem as the constraint for the outer problem, and formulate a meta KKT system for the combined problem.It is formulated in the language of PDE-constrained inverse problems, but would also apply to simpler situations like your problem (the PDE becomes the identity matrix..)
_unix.127071
I have to load a few additionals modules. One of them generates /dev/knem file. I have to set the permission to 0666, so a basic chmod 0666 /dev/knem works, but I would like to assign it directly at boot time.Where shall I write the config so that it is directly set by the kernel when it loads the module?Thanks in advance
set permission 0666 on /dev files at boot time
linux;kernel;kernel modules
I might be wrong, but can't you use udev rules, to assign 0666 permissions when /dev/knem is mounted ?http://www.reactivated.net/writing_udev_rules.html#syntaxControlling permissions and ownershipudev allows you to use additional assignments in rules to control ownership and permission attributes on each device.The GROUP assignment allows you to define which Unix group should own the device node. Here is an example rule which defines that the video group will own the framebuffer devices: KERNEL==fb[0-9]*, NAME=fb/%n, SYMLINK+=%k, GROUP=videoThe OWNER key, perhaps less useful, allows you to define which Unix user should have ownership permissions on the device node. Assuming the slightly odd situation where you would want john to own your floppy devices, you could use: KERNEL==fd[0-9]*, OWNER=johnudev defaults to creating nodes with Unix permissions of 0660 (read/write to owner and group). If you need to, you can override these defaults on certain devices using rules including the MODE assignment. As an example, the following rule defines that the inotify node shall be readable and writable to everyone: KERNEL==inotify, NAME=misc/%k, SYMLINK+=%k, MODE=0666A step-by-step on creting UDEV rules can be found in this post: http://ubuntuforums.org/showthread.php?t=168221
_unix.378266
How can i move everything but the last n files, n=2?. The files are sorted by date, and their names are yyyymmddhhmmss.txt and yyyymmddhhmmss.txt_aux. The last two files are always being appended, until they got filled, and then new files are created. The creation last 10 minutes aprox. I currently do this, which is a rough approximation; moving everything older than 60 minutes, which leaves about 12 files stored. find /dir/aux1/ -name '*.txt*' -mmin +60 -type f -exec mv {} /dir/aux2/ \;
How to move everything but the last files?
find;timestamps;mv
null
_webmaster.58
Are there any services that will monitor a web site and report if it gets hacked and defaced? Which are reputable and recommended? How does the service notify you when your site is having problems?
Services to monitor if site is hacked and defaced?
service;monitoring;content
null
_unix.279205
name ,lastname,phonenumberHace, Apoio, 703-2101 Yoliot, Apostolos, 4222-1124Jenny,Thano,105-4122 Aeriom,Koun, 510-4122 Dekon, Atolo, 502-2522 Feow, R,685-3431I did this but doesnt worked and I have no idea how it can be : [A|R]
only regular expressions : i want the lastnames that start with A or R
regular expression
null
_cstheory.9881
I am referring to the Iterative Rounding technique used by Kamal Jain for Steiner Network problem to obtain $2$ approximation factor algorithm. Is there any example where this technique is used for vertex weighted graphs? I have only seen examples for weighted edges or edge connectivity problems that use this paradigm. The nearest i have seen is degree bounded networks that use this paradigm. Also, i would like to get some intuition that when is this method probably applicable (or what could be the underlying difficulty that it is not yet applied to vertex weighted scenarios).
Is there a example of Iterative Rounding in Approximation Algorithms for vertex weighted Graphs?
graph algorithms;approximation algorithms;linear programming;iterated rounding
The simplest node-weighted network design problem is the node-weighted Steiner tree problem. Klein and Ravi considered this problem and obtained an $O(\log k)$-approximation (here $k$ is the number of terminals). They also showed that the Set Cover problem reduces to it in an approximation preserving fashion and hence we should not expect any better approximation. It is not hard to show that iterated rounding is not helpful for the Set Cover problem. Consider the following example. We have $n$ elements $\{e_1,\ldots,e_n\}$ and $n$ sets $S_1,\ldots,S_n$ where $S_i$ contains all elements except $e_i$. If you look at the natural LP with a variable $x_i$ for set $S_i$ then a basic feasible optimal solution is to set $x_i = 1/(n-1)$ for each $i$. From this one can see that iterated rounding in the plain vanilla fashion won't give a good bound. Note that the integrality gap of the LP is $O(\log n)$. This example for Set Cover can be extended to the node-weighted Steiner tree problem.
_unix.21785
How can I install fresh versions of these apps on Scientific-Linux 6.1/64bit?:VLC player (it's not in the default repositories and all I can find is an outdated VLC in rpmforge)Chromium/Google ChromeFlash PlayerVirtualBoxA Microsoft Paint alternative
To-do's after installing Scientific-Linux 6.1 for Desktop purposes
scientific linux
null
_codereview.151972
I solved this problem. Problem StatementGiven a string, sort it in decreasing order based on the frequency of characters.Example 1Input: treeOutput: eertExplanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore eetr is also a valid answer.Example 2:Input: cccaaaOutput: cccaaaExplanation: Both 'c' and 'a' appear three times, so aaaccc is also a valid answer. Note that cacaca is incorrect, as the same characters must be together. Example 3:Input: AabbOutput: bbAaExplanation: bbaA is also a valid answer, but Aabb is incorrect. Note that 'A' and 'a' are treated as two different characters.I solved this problem using heaps(since it was tagged under this category). I feel my solution is a bit verbose which includes building a vector from a map and so on.Can you think of any redundancies that can be removed from this solution or any better way of doing it.class CompareHeap { public: bool operator()(const std::pair< char, int> &A, const std::pair< char , int > &B ) { return (A.second < B.second); } }; class Solution { public: string frequencySort(string input) { std::string answer = ; std::map<char, int> freq; for(auto it = input.begin(); it!= input.end(); ++it) { if(freq.find(*it) != freq.end()) { freq[*it] += 1; } else { freq[*it] = 1; } } std::vector<std::pair<char, int >> v; std::transform(freq.begin(), freq.end(), std::back_inserter(v), [](std::pair<char , int > kv) {return kv;}); std::make_heap(v.begin(), v.end(), CompareHeap()); while(v.size() > 0) { std::pop_heap(v.begin(), v.end(), CompareHeap()); answer += std::string(v.back().second,v.back().first); v.pop_back(); } return answer; } };
Sort Characters By Frequency
c++;programming challenge;c++11;vectors;heap
Shorter:There are possibilities to make the code shorted without making it less correct/clear.for(auto it = input.begin(); it!= input.end(); ++it)Range loop could be used for this purpose. if(freq.find(*it) != freq.end()) { freq[*it] += 1; } else { freq[*it] = 1; }map zero initializes built in types when it creates the key-value pair. Source. So the check can be removed, and ++ used instead of +1. The change may also improve performance, but I don't think it will be much of a deal. std::vector<std::pair<char, int >> v; std::transform(freq.begin(), freq.end(), std::back_inserter(v), [](std::pair<char , int > kv) {return kv;});std::vector has a constructor which takes iterator pair and constructs the container from that. std::make_heap(v.begin(), v.end(), CompareHeap()); while(v.size() > 0) { std::pop_heap(v.begin(), v.end(), CompareHeap()); answer += std::string(v.back().second,v.back().first); v.pop_back(); }In my opinion sort would be a better fit (making a heap is sorting too, but I think std::sort have potential to perform better), then do range for loop with the last 2 lines of the code inside of it. Currently intentions are less clear, though still good.Style:I think that having operator() in the outside class is confusing. If the clarity is really wanted, named lambda could be made, then passed to std::sort() or make_heap().Theoretically input.length() can be bigger than maximum value of int, so std::size_t should be used, just to be nerd that cares about standard compliance.Usage of map:I think that map is the most clear solution for this problem. It lifts a lot of burden from the programmer. There are also possibilities that compiler vendor did some small map optimization (so everything will be in the automatic storage).Copying the map into vector will probably cost nothing, since everything is POD, so it will decay into std::memset() or something similar (in case the map is small map, it will be even faster). Sorting a vector should be fast as well, since char on the platform has theoretical maximum of 256 values.The only thing that could be slightly sped up is putting the data into the result. reserve(input.length()) can be called on the result string so that it won't perform any additional memory allocations.Performance:The algorithm should be fast enough for most of the systems, unless insane blazing performance is needed (e.g. Facebook or similar).
_cs.40791
I would like to prove that any context free language over a 1 letter alphabet is regular. I understand there is Parikh's theorem but I want to prove this using the work I have done so far:Let L be a context free language. So, $L$ satisfies the pumping lemma. Let $p$ be $L$'s pumping constant. Let $L = L_1 \cup L_2$ where $L_1$ consists of $w$ where $|w| < p$ and and $L_2$ consists of $w$ where $|w| >= p$. We have a single letter alphabet and since $L_1$ has a restriction on the length of its words, $L_1$ is a finite language. Finite languages are regular so $L_1$ is regular. If I can show that $L_2$ is regular, I can use the fact that the union of regular languages is regular. But I am struggling on showing that $L_2$ is regular. I know that since $w \in L_2$ has to satisfy $|w| >= p$, by the pumping lemma, $w$ can be written as $w = uvxyz$ where $|vxy| <= p$, $|vy| > 0$ and $\forall t >= 0$, $uv^txy^tz \in L$. Since we have a single letter alphabet (say the letter is $a$), $uv^txy^tz = uxz(vy)^t = uxz(a^{|vy|})^t \in L$. Now what?
Proving that any CF language over a 1 letter alphabet is regular
formal languages;regular languages;context free
You have shown that for any given $w = uvxyz = a^{|uxz|+|vy|}$ there is a regular language $L_w = a^{|uxz|+|vy|\cdot t} \subset L_2$. Now you need to show that $\bigcup L_w = L_2$ and that this can be a finite union. Note that $|vy| \leq p$ and that $a^{(|uxz|+|vy|)+|vy|\cdot t} \subset a^{|uxz|+|vy|\cdot t}$ so not all values of $|uxz|$ matter.
_cs.69507
Given an alphabet $ = \{a, b, c\}$, I have the following grammar:$$ S -> aSb | aAb $$$$ A -> aaA | aBb $$$$ B -> Bbb | c $$Which method should I use to write the definition of the language?
How do I define a language from a grammar?
formal languages;formal grammars
This one is very simple because it has a very downward flow to it. For example, $S$ has non-terminals $S$ and $A$, and once you go to $A$, you can never get back to $S$. So we use this fact to just work through incrementally.Our language started with $a^nXb^n$ for S where X is some other language, then we got to A and get $a^n(aa)^mXb^n$, then finally $a^n(aa)^{m+1}c(bb)^sb^{n+1}=a^{n+2m+1}cb^{n+2s+1}$ where $n,m,s \in \mathbb{N} \setminus{0}$
_unix.369683
using ubuntu 16.4Linux db2 4.4.0-78-generic #99-Ubuntu SMP Thu Apr 27 15:29:09 UTC 2017 x86_64 x86_64 x86_64 GNU/Linuxverified if systemd is startup process :okcreated a file /etc/systemd/system/db2fmcd.service with[Unit]Description=db2 fault monitor coord daemon[Service]ExecStart=/opt/IBM/db2/V11.1/bin/db2fmcd --file=/tmp/db2fmcd.logRestart=alwaysType=simpledidsystemctl daemon-reloadsystemctl enable db2fmcd.servicesystemctl start db2fmcd.service (no message)systemctl status db2fmcd.service db2fmcd.service - db2 fault monitor coord daemon Loaded: loaded (/etc/systemd/system/db2fmcd.service; static; vendor preset: enabled) Active: inactive (dead)Jun 07 10:09:21 db2 systemd[1]: db2fmcd.service: Service hold-off time over, scheduling restart.Jun 07 10:09:21 db2 systemd[1]: Stopped db2 fault monitor coord daemon.Jun 07 10:09:21 db2 systemd[1]: Started db2 fault monitor coord daemon.Jun 07 10:09:21 db2 systemd[1]: db2fmcd.service: Service hold-off time over, scheduling restart.Jun 07 10:09:21 db2 systemd[1]: Stopped db2 fault monitor coord daemon.Jun 07 10:09:21 db2 systemd[1]: Started db2 fault monitor coord daemon.Jun 07 10:09:21 db2 systemd[1]: db2fmcd.service: Service hold-off time over, scheduling restart.Jun 07 10:09:21 db2 systemd[1]: Stopped db2 fault monitor coord daemon.Jun 07 10:09:21 db2 systemd[1]: db2fmcd.service: Start request repeated too quickly.Jun 07 10:09:21 db2 systemd[1]: Failed to start db2 fault monitor coord daemon.process db2fmcd is not startedany idea how to debug this problem ?
autostart process in ubuntu
ubuntu;autostart
null
_softwareengineering.96524
I find that when someone asks what is the best way to learn how to program, people usually provide them with references to a bunch texts written by various authors.However I don't believe many people at all learn to program from books. I find that they are usually faced with a challenge and then use programming as a tool to overcome it.For example I 'got into' programming because I wanted to start a server for a game I was playing, so I googled and read through the support for that particular server and now I am a employed software engineer, using only the skills I developed (and then further developed) by coding C# scripts for a not very popular server package.So my question is, do people generally find it easier to learn from these books? I know I have looked at a few of them and found them far too 'dry' to encourage me to finish it.
Why do people use programming books?
books;methodology
Here's how I learn, generally speaking:Buy a bookDon't read it cover to cover but know where everything can be foundFind a pet project to work onLearn from experience, but use the book as a referenceWhere the book fails, there is always googleNote: the third point sometimes comes first.Edit: To answer the question Why?Google is great to find out how to do something, but it's not great for finding out what you don't know. Why would you ever google C# delegates, if you didn't first know that C# has a concept called delegates and that it might be useful to solve a problem you're working on?Also, the signal-to-noise ratio can be a bit high sometimes. If you have a rough idea in your head how something is done then you can easily confirm whether the article you are reading is correct. But if you've no clue... you can end up in a bigger mess.
_unix.55624
I haven't had much luck finding an answer to my problem, but maybe I'm not asking for it correctly.I have a process I startup like the following:nohup ping 127.0.0.1 > log.txt >2>&1 &Pretty simple command, send all the stdout to log.txt. Only problem is that the command I'm running sends data every nth second to log.txt. I'd like to output just one line to my log.txt file instead of appending it and running the risk of filling my drive up.Is there a way to just output one line to log.txt that continuously gets overwritten?
Limit stdout from a continuously running process
bash;shell;text processing;output
Here is a quick and dirty solution to only keep the last line of output in the log file:ping localhost | while IFS= read -r line; do printf '%s\n' $line > log.txt; doneBeware that you now probably have all kinds of race conditions when trying to access the file for reading. Locking the file from mutual access might help. For more information about locking this question on stackoverflow might be a good start: How do I synchronize (lock/unlock) access to a file in bash from multiple scripts?
_codereview.156533
Just completed a /r/dailyprogrammer challenge. Challenge #238 to be precise. A Github repository with the wordbank.txt is available here.import randomdifficulty = {1: [4, 5, 6], 2: [7, 8], 3: [9, 10, 11], 4: [12, 13], 5: [14, 15] }#Keys are the various word lengths for each difficulty (1-5).acceptedWord = []#Start a blank list, used in getWords()def getWords(): while True: try: level = int(input(What difficulty would you like? (1,2,3,4,5) )) break except (ValueError, KeyError): print(That is not a number) #Take a numerical input from the user, attempt to parse it, if it fails, carry on the loop. num = random.choice(difficulty[level]) #num (used to store word lengths) is a random choice from the available lengths for the selected difficulty. with open('wordbank.txt', 'r') as file: #Open the file containing word-bank for x in map(str.upper, map(str.strip, file.readlines())): #loop over the stripped down words if len(x) == num: acceptedWord.append(x) #If length of word is equal to random choice from suitable lengths, add it to a list. #Random index from total number of items in list. answers = random.sample(acceptedWord, num) #picks a selection of the available words. Amount of words = word length. trueWord = answers[random.randint(0, len(answers)-1)] #trueWord = answer. Random item of the shortlisted avaliable words print('\n'.join(answers)) #Prints hints. game(trueWord)def game(trueWord): for x in range(0,5): #The user has 5 guesses print(Guesses Left: , 5-x) userInput = input(Guess: ).upper() #All guesses/inputs are parsed to uppercase. userList = list(userInput) #List of the letters the user inputed trueList = list(trueWord) #List of letter of if userInput == trueWord: print(Well done, you guessed correctly) getWords() #If the user enters the correct word, quit the program correctGuess = 0 for item in list(userList): #for each letter the user inputed if item == trueList[userList.index(item)]: #if the letter is in the same position as the answer correctGuess += 1 #increment the correct amount of letters by 1 print(correctGuess, out of , len(trueList), correct.) print(Bad luck! The answer was: , trueWord) getWords()getWords()
Worded Mastermind game in Python
python;programming challenge;python 3.x;game
Some obvious changes that I'd make:rename all the variables / methods such that they follow the snake_case conventionremove all the obvious comments and rather add a docstrings into each function insteadadd only one space before and after any operator (except if we're passing some arguments into a function / class)after , you should have a spacethe acceptedWord list should be defined within the getWords() function (the same goes for the difficulty dictionary). (or better yet, remove its declaration completely and use list comprehension instead)you should add if __name__ == '__main__'user_list is already a list so you don't have to specify the exact same thing here: for item in list(user_list).use string formatting when you print something: this: print(correct_guess, out of , len(true_list), correct.) will become this: print({} out of {}.format(correct_guess, len(true_list)))when you use with to open a file in read mode, you can omit r as that's passed by default.Reviewed code:import randomdef get_words(): Docstring goes here difficulty = {1: [4, 5, 6], 2: [7, 8], 3: [9, 10, 11], 4: [12, 13], 5: [14, 15]} while True: try: level = int(input(What difficulty would you like? (1,2,3,4,5) )) break except (ValueError, KeyError): print(That is not a number) num = random.choice(difficulty[level]) with open('wordbank.txt') as file: accepted_word = [x for x in map(str.upper, map(str.strip, file.readlines())) if len(x) == num] answers = random.sample(accepted_word, num) true_word = answers[random.randint(0, len(answers) - 1)] print('\n'.join(answers)) game(true_word)def game(true_word): Docstring goes here for x in range(0, 5): print(Guesses Left: {}.format(5 - x)) user_input = input(Guess: ).upper() user_list, true_list = list(user_input), list(true_word) if user_input == true_word: print(Well done, you guessed correctly) get_words() correct_guess = 0 for item in user_list: if item == true_list[user_list.index(item)]: correct_guess += 1 print({} out of {}.format(correct_guess, len(true_list))) print(Bad luck! The answer was: {}.format(true_word)) get_words()if __name__ == '__main__': get_words()More, I'd split the get_words() methods into two methods: get_user_level() and get_words():def get_user_level(): Docstring goes here difficulty = {1: [4, 5, 6], 2: [7, 8], 3: [9, 10, 11], 4: [12, 13], 5: [14, 15]} while True: try: level = int(input(What difficulty would you like? (1,2,3,4,5) )) break except (ValueError, KeyError): print(That is not a number) return random.choice(difficulty[level])def get_words(): Docstring goes here num = get_user_level() with open('wordbank.txt') as file: accepted_word = [x for x in map(str.upper, map(str.strip, file.readlines())) if len(x) == num] answers = random.sample(accepted_word, num) true_word = answers[random.randint(0, len(answers) - 1)] print('\n'.join(answers)) game(true_word)
_unix.58537
I'm using Cacti in Centos 6.3 and I would like to get the list of the top 10 memory consuming processes, with a memory graph, so that if server fails I can easily find the processes behind that.It is possible with a plugin or template?
Get list of top 10 memory consuming processes with graph using Cacti in Centos 6.3
centos;cacti
null
_softwareengineering.151206
The JavaBeans Specification describes a JavaBean as A Java Bean is a reusable software component that can be manipulated visually in a builder toolSince the majority of the lines of code that are written seem to have nothing to do with being manipulated visually in a builder tool, why has the JavaBean specification been the way to write object oriented code?I would like to forgo the traditional getter/setter in favor of Fluent Interfaces all throughout the code, not just in builders but fear doing so since this is traditionally not the way way object oriented code is written in Java.
Why has the accessor methods from the JavaBean specification become the standard for Java development?
java;history
JavaBean style accessors have proven to be a good match for all kinds of scenarios that are similar to the original builder tool scenario in one core point: components are being passed around and manipulated by generic containers and tools as well as application code. In an app server you have service components to which an EJB or Spring container adds transactions and dependency injections, persistent domain models to which an ORM adds lazy loading and change detection, and which can be serialized to XML by a library without any specific code.Accessors provide a common API that is very flexible in how the component can be used - it does not proscribe an order of operations. Each accessor call is independant of others and they all follow the same pattern, so you can easily add generic layers that add functionality without disrupting the intended usage pattern.In contrast, fluent interfaces are often designed for one-shot use: the object is created, a chain of methods is called that ends with a method that produces a final result, and the object is then abandoned. There is much less flexibility (mostly in methods being optional) and genericality, but this is exactly the advantage: the interface forces you into an intended usage pattern, making it very easy to use.So JavaBeans and fluent interfaces have advantages in different scenarios, and which you should use depends. And you could even combine both.
_webmaster.15575
I'm trying to use one install of Kohana to manage two separate sites rather than just duplicate the install. I have directories like this:applications/ app1/ app2/The .htaccess I have looks like this:RewriteEngine onRedirectMatch app1/(.*)$ http://app1.example.com/$1RewriteCond %{REQUEST_FILENAME} !.*applications/app1.*RewriteRule .* applications/app1/index.php/$0 [PT]When I go to app1.example.com I get a 500 infinite redirect and the URL is app1.example.com/index.php/index.php/index.php/...What I need is for it to look like it's going to app1.example.com but behind the scenes it is redirecting to document_root/applications/app1/index.php.I also need this to work for app2 in the same way, but I imagine once I have it working for app1 it will essentially be identical.If you want to throw in any tips on managing multiple sites with one Kohana install that would help too.
Apache Redirect based on directory name
php;apache;mod rewrite;redirects;kohana
Looks like Kohana supports multiple sites from one installation, according to the docs:http://docs.kohanaphp.com/installationPut the system folder somewhere on your server, preferably outside of your webserver's document root.Delete the system folder in your current application.For your application's index.php file, change the $kohana_system variable to the relative or absolute path of where you put the system folder.You can now point all of your applications to this one system folder for easy upgrades. This makes your life a whole lot easier when you have 10+ kohana sites on your server.
_softwareengineering.216647
I'm trying to create a rails app that allows users to submit information about their pets. I've come to a point where my knowledge is limited and I don't know enough about what/how this could be done so I'm hoping this will be relatively easy to answer.At the moment I have a model called Pet, this model currently stores basic information like name, picture etc but it also holds more specific data like type, breed, date of birth etc. What I would like to be able to do is create a page that can match various records without having to be manually categorized if that makes sense so a users pet could be matched to other pets with the same breed, age etc.I've read about nested models as I understand this information could be submitted to 2 models in one form but I am not sure whether this could be done directly in a separate controller which would only be visible to users with pets in these matched groups if that makes sense. So in essence is it best practice to use 1 table to store all the information and just use a controller to match pets based on rows having the same values or would it be far simpler to have a form with a nested model and link 2 tables together?The main feature needs to be matching without a user having to create a group or categorize pets so the second model would need to add id's to an array instead of just creating more and more rows.
model association or controller?
ruby on rails
I've used both one table and two tables. The nice thing about two tables is you can perform additional queries on the details of the pets table and, say pet_details - plus, it keeps the tables smaller and easier to manage.With a nested model, you wouldn't necessarily create a new controller unless you wanted to directly manipulate the data through the web or an API for your nested model. The parent model Pet would handle all the manipulation of that data. TL;DR - it basically just keeps it more organized.
_computerscience.1830
Suppose i have a 400*300 gray scale image.Now I want to scan each line horizontally and make the average of that line 128,such that the values get scaled as per their difference from mean(128) which will not cause any distortion to image.
Average intensity of an gray image
image processing
null
_codereview.135521
I'm implementing the Two-sample Kolmogorov-Smirnov test in MATLAB. I must admit I know very little of formal statistics and was simply trying to implement the description in wikipedia's page.Right now I take as input the two vectors to be compared x1 and x2, and optionally the p-value that the check will run on. It outputs 1 if the vectors pass the test and 0 if they do not.A couple of questions I have:Is there a better way to compute the empirical distribution functions? Right now I evaluate the empirical distribution function at the points defined in the vector t. In my naive approximation, I made it go from the smallest value of the vectors to the largest, using twice as many points as the vector with the most points. I have no idea is this is the best way to compute it, and suspect the vector doesn't have to be nearly as dense.Can I vectorize the search through the t vector?Right now I have a for loop that goes through every value of tand computes the empirical distribution function in that way. It seems that there might be a way to vectorize this operation further and get rid of the for loop. Haven't figured out a good way to do it however.And of course, any other suggestions are welcome!My code is below:function [OUT] = k_stest(x1,x2,p)% Set default p-value if nargin == 2 p = 0.05; end % Compute lenghts N1 = length(x1); N2 = length(x2);% Set vector t over which the empirical distribution function will be computed. t = linspace(min(min([x1 x2])),max(max([x1 x2])),2*max([N1 N2]));% Initialize the statistic, negative values guarantees it will be overwritten by first call. D = -1; % Set c from tabulated values if p == 0.10 c = 1.22; elseif p == 0.05 c = 1.36; elseif p == 0.025 c = 1.48; elseif p == 0.01 c = 1.63; elseif p == 0.005 c = 1.73; elseif p == 0.001 c = 1.95; else disp('Invalid p-value. Only p = 0.10 0.05 0.025 0.01 0.005 0.001 are supported') return end% Search though the vector t, computing the empirical distribution function for each t, % and overwriting the statistic if a higher value is found. for i = 1:length(t) F1 = sum(x1<=t(i))/N1; F2 = sum(x2<=t(i))/N2; if abs(F2-F1) > D D = abs(F2-F1); end end% Compare the statistic to determine if the samples pass or fail. if D == -1; disp('Error, invalid input vectors') return elseif D > c*sqrt((N1+N2)/(N1*N2)); OUT = 0; else OUT = 1; endend
Vectorizing Two Sample Kolmogorov-Smirnov test
statistics;matlab;vectorization
I'll take this in chronological order, from the top down. I think I have covered all aspects of the code =)function [OUT] = k_stest(x1,x2,p)This looks nice, but it would be better if you had spaces between the input arguments. Also, k_stest is not a very good name, as it's hard to understand what it does just be looking at the name. I read in another review that You don't need the brackets around the output variable, but you should always include it. I don't necessarily agree, I usually omit them, but that's just a matter of personal preferences.% Set default p-value if nargin == 2 p = 0.05; end This is OK. Depending on how you call the function you might add some additional checks. Is p a scalar? Are x1 and x2 vectors? This is not necessary, but can be useful if you want to use this function a long time from now and don't remember the specifics. assert can be very useful here.% Compute lenghts N1 = length(x1); N2 = length(x2);numel (number of elements) is better than length. It's more robust and a lot faster for long vectors.% Set vector t over which the empirical distribution function will be computed. t = linspace(min(min([x1 x2])),max(max([x1 x2])),2*max([N1 N2]));This is dangerous, and a bit messy.[x1 x2] assumes both x1 and x2 are row-vectors, i.e. horizontal vectors. A lot of functions in Matlab returns vectors as column-vectors i.e. vertical vectors by default, including the colon operator (:). If you happen to call this function with two vertical vectors instead of two horizontal vectors, this would fail (due to [x1 x2]).Instead, you should do:x12 = [x1(:); x2(:)]; t = linspace(min(x12), max(x12), 2*max([N1, N2]));This way you're converting x1 and x2 to vertical vectors, and concatenate them vertically, prior to the linspace call. Now you only need one call to max and min.The way you're initializing D is OK!% Set c from tabulated values if p == 0.10 c = 1.22; elseif p == 0.05 c = 1.36; ...Comparing floating point values using == is dangerous. For instance 0.1 + 0.2 == 0.3 will return false. Instead, you should compare the values with the desired value, but with some tolerance (for instance eps). if abs(p - 0.10) < eps c = 1.22; elseif abs(p-0.05) < eps c = 1.36;If two values are closer to each other than +/- eps then they are essentially equal.% Search though the vector t, computing the empirical distribution function for each t, % and overwriting the statistic if a higher value is found. for i = 1:length(t) F1 = sum(x1<=t(i))/N1; F2 = sum(x2<=t(i))/N2; if abs(F2-F1) > D D = abs(F2-F1); end endYou are right, vectorization is the way to go! Use bsxfun to create a logical matrix where each element that satisfy the condition x1 <= t(ii) are true and the others are false. Then sum the entire mask, and take the maximum difference.mask1 = bsxfun(@le, x1(:), t);mask2 = bsxfun(@le, x2(:), t);s1 = sum(mask1) / N1;s2 = sum(mask2) / N2;D = max(abs(s1 - s2));% Compare the statistic to determine if the samples pass or fail. if D == -1; disp('Error, invalid input vectors') return elseif D > c*sqrt((N1+N2)/(N1*N2)); OUT = 0; else OUT = 1; end endThe check for invalid input vectors should be in the start of the function. I can't see a reason why you want it in the end instead. And as far as I can tell it will never fail (if the input is invalid then you will get an error further up).Instead of the if and elseif, you can simply do:OUT = D <= c*sqrt((N1+N2)/(N1*N2));To sum it all up, your function can be written like this. I've omitted the comment for simplicity. You should include them in your code.function OUT = k_stest(x1, x2, p)if nargin == 2 p = 0.05;end% Add check for invalid input vectors!N1 = numel(x1);N2 = numel(x2);x12 = [x1(:); x2(:)]; t = linspace(min(x12), max(x12), 2*max([N1, N2]));if abs(p - 0.10) < eps c = 1.22; elseif abs(p-0.05) < eps c = 1.36;% Continue with the rest of the values%endmask1 = bsxfun(@le, x1(:), t);mask2 = bsxfun(@le, x2(:), t);s1 = sum(mask1) / N1;s2 = sum(mask2) / N2;D = max(abs(s1 - s2));OUT = D <= c*sqrt((N1+N2)/(N1*N2));end
_unix.232826
The following command is working correctly for copying only files matching Mem*rsync -uvma '--include=*/' '--include=**/Mem*' '--exclude=*' ../srcdir/ /targdirI would like to also exclude a certain pattern *.class. Here is the attempted addition: '--exclude=**/*.class' And the full command is rsync -uvma '--include=*/' '--include=**/Mem*' '--exclude=*' '--exclude=**/*.class' ../srcdir/ /targdirThe addition has no effect. The command does copy *.class files:./target/classes/com/blazedb/sparkperf/MemBattery$$anonfun$3.class./target/classes/com/blazedb/sparkperf/MemBattery$$anonfun$4.class./target/classes/com/blazedb/sparkperf/MemBattery$$anonfun$5.class./target/classes/com/blazedb/sparkperf/MemBattery$$anonfun$6.class./target/classes/com/blazedb/sparkperf/MemBattery.class sent 67536 bytes received 510 bytes 136092.00 bytes/sec total size is 67080 speedup is 0.99So then how should that exclude pattern be formed?
Exclude pattern not working for rsync
rsync
null
_cstheory.37565
It is known that $\textbf{AM}[O(1)] = \textbf{AM}$. Since $\textbf{IP}=\textbf{PSPACE}$ we have $\textbf{AM}[poly(n)] = \textbf{PSPACE}$.Can we say something about $\textbf{AM}[ f(n)]$, where $f$ is a function between $O(1)$ and $poly(n)$?(For example, $f(n) = \log n$.)
What can we say about AM[log n]?
cc.complexity theory;complexity classes;interactive proofs
null
_datascience.12279
There are many instances of quotes and texts where the true author may be disputed. Are there data science or machine learning techniques which may be useful to establish the authorship?
Can data science be applied to establishing the author of a text?
data mining
null
_codereview.85313
Any suggestions?#include<iostream>using namespace std;class node { friend class linked; private: int data; public: node *link; node() { data=0; link=NULL; }};class linked{ public: node *start=NULL; node *ptr; node *temp=NULL; void append(int item); void traverse();};void linked::append(int item){ ptr = new node(); ptr->data=item; if(start==NULL) { start=ptr; ptr->link=NULL; temp=start; } else { while(temp->link!=NULL) { temp=temp->link; } temp->link=ptr; ptr->link=NULL; } }void linked::traverse(){ node *trav=start; while(trav!=NULL) { cout<<trav->data<<endl; trav=trav->link; }}int main(){ int i; linked box; for(i=0;i<10;i++) { box.append(i); } box.traverse(); }
Implementing a linked list using C++
c++;beginner;linked list
Starting at the top//any suggestionsYes, plenty. But don't add that to the code.using namespace std;Nearly every beginner includes this (and it's understandable because this is what they do in books).In actual practice this is a bad idea. Never include this line in real code. The reason books include it is to save space (because each printed page costs extra). When writing real code, this will create bad habits that will bite you in the end so it is a habit you should break now.see: Why is using namespace std; considered bad practice?node classprotection levelThere is no need to make the node class public. This is internal to your linked list so you should hide its implementation from other people by making it a private member class of the linked class.styleclass Node { friend class linked; private: int data; public: Node *link; Node() { data=0; link=NULL; }};Small note on vertical spacing: there is way too much here. It's a small class so it does not stand out. But if you do the same thing on a bigger class it becomes hard to read. Now don't take this to the extreme and completely eliminate vertical space-- break things up into logical units.Since we are making this class a private member of linked there's no need for friendship; just make everything public.But we can improve the code by having a constructor that takes the data value and the link (if you look at your code you could use both at the same time. When writing constructors, it's preferred to use the initializer list syntax to initialize members: Node(int data, Node* link) : data(data) , link(link) {}You will notice here that everything is lower case. It is relatively common to define user-defined types with an initial capital letter, while objects have an initial lower case letter. This allows you to quickly see the difference between types and objects (an important distinction in C++).So, following this style, your code should look like this:class Linked{ struct Node { int data; Node* next; Node(int data, Node* next) : data(data) , next(next) {} }; ....linked classclass linked{ public: Node *start=NULL; Node *ptr; Node *temp=NULL; void append(int item); void traverse();};Not sure what all the pointers are for? OK start marks the start of the list (usually called head). But what are the others supposed to represent? If they are really just things you use a throw away then they can be local to the function methods and not part of the class.You call new in your code. For every call to new there must be a corresponding call to delete. Otherwise you will leak memory (and resources). So the best place to do this is in the destructor.Also you are missing a constructor. This means that all you member variables are likely to be undefined (this means they have random values in them. C++ (unlike Java and other languages at this level) does not do automatic initialization of variables.see: Why aren't pointers initialized with NULL by default?So lets add the constructor and destructorclass Linked{ struct Node { int data; Node* next; Node(int data, Node* next) : data(data) , next(next) {} }; Node* head; Linked(): head(nullptr) {} ~Linked() { Node* tmp; for(;head;head = tmp) { tmp = head->next; delete head; } } ...If we look at append. You get the correct test for adding an element to an empty list. But it starts to go wrong in the second half where you are using a loop.The member temp is not initialized. It is also public -- this means it could have been altered since last time you used it. So it is best to use a local variable that you initialize to head.Note: you can also use the new constructor for node to reduce code in this function.void Linked::append(int item){ if (head == nullptr) { head = new Node(item, nullptr); } else { // First find a pointer to the last item in the chain. Node* last = head; while(last->next) { last = last->next; } // Now just add the node. last->next = new Node(item, nullptr); // Notice this loop happens each time you add an element. // This makes adding an element relatively expensive. // To avoid this a lot of implementation keep two pointers // in the list a `head` and a `tail`. That way data elements // can be quickly added to the tail. // When you start adding things like delete. // It becomes useful to know your previous element. // So it is also very common for the node object to have // two pointers `next` and `prev` }Note: we always seem to place nullptr as the second argument. So we could potentially remove it. But if you try to implement an insert function then it becomes useful:void Linked::insert_at_head(int value){ head = new Node(item, head); // See very useful.}Not sure what your traverse is doing. void linked::traverse(){ Node *trav=start; while(trav!=NULL) { cout<<trav->data<<endl; trav=trav->link; }}I would just name that print; traverse implies going through a tree. One way to improve the functionality and modularity of traverse would be for it to take a parameter of a function that should be applied to all the nodes (but I think that is a bit beyond this exercise). So a couple of things here:Rename to printMark the function as constIt does not alter the state of the object. So it is safe to call on a const version of the object.Printing in C++ is usally done by operator<<so create one of these that calls your print method.Like this:void Linked::print(std::ostream& str = std::cout) const // Note const{ Node *trav=start; while(trav!=NULL) { // Added space here so yo can see the << // and what they are applied too. // // Also prefer \n to std::endl (especially in here) // The std::endl forces a buffer flush. Doing this // after printing every integer becomes very inefficient. str << trav->data << \n; trav=trav->next; }}std::ostream& operator<<(std::ostream& str, Linked const& data){ data.print(str); return str;}I think we have now covered enough in one review. I would have another bash at this example. Once you have done that post the code for review again and we can go into some other details.
_softwareengineering.309822
Most Github repositories I'm aware of use the following workflow for pull requests: one or several users with contributor privilege review the suggested changes and then one of them merges the pull request which most of the time requires just two clicks - merge and then confirm merge. Here's an example in CoreFX repo - one of contributors merged the changes.However there's OpenCV repository with pull requests like this where one of the contributors reviews the changes and then approves them by posting a thumbs up! comment which causes a dedicated user opencv-pushbot to merge the changes. It looks like no contributor ever merges the changes himself in that repository - they are all merged by the push bot user.What's the use of that? It takes the same amount of labor to post a thumbs up comment as it takes to merge the pull request. It also makes it a bit harder to track who approved which merge because now all changes are merged by the same user.What advantages does the push bot approach have?
Why use a dedicated pushbot user which automatically merges approved pull requests?
version control;git;github;collaboration;pull requests
The push bot also interfaces with a continuous integration server, which you can see if you click on the View Details next to its merges. That means there are two conditions for a merge: the thumbs up and a passed set of automated tests. Having the bot do the merge means the maintainer doesn't have to wait for the tests to finish, worry about accidentally merging a pull request with failing tests that he will have to back out later, or have to manually check the test results each time. He just focuses on reviewing the code.On a well-functioning team with a good set of tests, knowing who approved a particular merge does not usually matter that much.
_webapps.90453
Within Zoho Email, IMAP Access is disabled by default. I can enable this for each account individually, but I'd like to enable it for all accounts instead of selecting them one-by-one. How can I do this?I may also want to disable POP Access for all accounts at once, or enable ActiveSync Access. Over a few dozen email addresses this gets really tedious without a bulk update feature.
Enable / Disable IMAP / POP Access on all Zoho email accounts
email;zoho
null
_unix.162989
I'm using Kali linux on vmware in windows7. I've been trying to crack my wpa password and noticed that when I leave the system running (in process of cracking password) and leave the laptop on and go away for about 10-15 minutes, Kali linux goes to sleep and I am not sure if the cracking process with reaver is still running or not. When I click onto the page a box comes up prompting me to type in my username and password. When I type that in it logs me back on but my screens that were left open cracking the password are no longer there and everything starts freezing up a lot. The mouse is freezing and if I try to click on anything there is a massive delay before anything happens or nothing at all.Also there was no option prevent screen going in an inactive state infinitely..(lock and brightness-maximum time 1 hour)I've since had to switch back to backtrack to do my cracking and has been running perfectly and does not go to sleep when left for long periods.Now what I'd like to know is how can I prevent kali linux from goingto sleep and closing my work that's in progress?Any help on this issue would be appreciated.
How to get Kali Linux to not go to sleep?
gnu screen;kali linux;screensaver;screen lock
null
_unix.198552
As an another countermeasure against security threats I wrote a little script that computes MBR and boot checksum and then compare it to the old one. As long as the computer is running this is OK, but when I restart it, the checksum is changed.QUESTION -- what is the cause of changing and how to prevent it?Details: openSUSE 13.2, noatime for /boot set, boot parition is a separate partition (it is not just a directory in root filesystem), the partition is unmounted right after I log in and it is the first step before the computation of the checsum.The script:#!/bin/shsudo umount /boot# MBRsudo dd if=/dev/sda bs=512 status=noxfer count=1 | sha1sum | diff bootcheck_mbr.sha1 -MBR_RES=$?# boot partitionsudo dd if=/dev/sda1 bs=1M status=noxfer | sha1sum | diff bootcheck_boot.sha1 -BOOT_RES=$?if [[ $MBR_RES -ne 0 ]] || [[ $BOOT_RES -ne 0 ]]then kdialog --sorry WARNING:\nBoot disk is changed. --title BOOT CHECK --geometry 0x0++300+400else kdialog --title Boot check --passivepopup The disk is unchanged. 25 --geometry 0x0++300+400fi
What changes my boot partition and how to prevent it?
boot;security;checksum
null
_cstheory.8211
Let $f(x_1,\dots,x_n)$ be a degree $d$ polynomial in $n$ variables over $\mathbb{F}_2$, where $d$ is constant (say 2 or 3). I would like to find the smallest formula for $f$, where formula and formula size are defined in the obvious way (eg. the smallest formula for the polynomial $x_1 x_2 + x_1 x_3$ is $x_1(x_2+x_3)$).What is the complexity of this problem - is it NP-hard? Does the complexity depend on $d$?[ More formally, a formula (aka arithmetic formula) is a rooted binary tree, each of whose leaves is labelled with either an input variable or the constant 1. All the other vertices of the tree are labelled with $+$ or $\times$. The size of the formula is the number of leaves used. The formula computes a polynomial recursively: $+$ vertices compute the sum of their children over $\mathbb{F}_2$, $\times$ vertices compute the product. ]
Complexity of minimising polynomial formula size
cc.complexity theory;formulas
null
_softwareengineering.335050
I understand what increment and decrements operators are (++ and --) and the difference between post and pre (i++ vs ++i) but should they be avoided as they do increase the difficulty of reading the code? After reading the answers to the question Are assignments in the condition part of conditionals a bad practice? it seems like code readability is of the utmost importance. I had a prof who told us not to use increment or decrement operators unless you know exactly what you're doing (but this prof usually gave poor advice).In my opinion, i++ is easier red than i = i + 1, however I wouldn't do this in side other statements, such as arr[i++] or arr[++i], I would break these over two lines.In summaryis it ok to use ++ and -- when they are the only operations on the line?is it ok to use ++ and -- when they are combined with other operations and operator presidency has to be considered?
Do increment and decrement operators decrease readability?
java;c++;language agnostic;readability;operators
null
_computerscience.4761
I often use a 2D Perlin noise texture to displace a grid in the vertex shader (e.g. terrain, ocean). However, every time I google the method to calculate post-displacement normals there is a slight difference. For example, the value to place in the Y-component varies depending on the source. In this example, they place a '1' in the Y-component prior to normalization:https://software.intel.com/en-us/articles/real-time-parametric-shallow-wave-simulationWhereas in these codes, the value '2' is chosen:http://www.dian-xiang.com/blog/2What gives? Is there a definitive source for calculating normals from a height map? Might this be related to unprojecting mouse clicks? It always bothered me that you could throw a '0.5' in the Z-component, as mrdoob mentioned here:https://stackoverflow.com/questions/11036106/three-js-projector-and-ray-objectsOr use a '1' in the Z-component as Anton does here:http://antongerdelan.net/opengl/raycasting.htmlIs there a connection between calculating normals from height maps and unprojecting mouse clicks?The second part of my question concerns choosing an epsilon to sample the height map. Before I learned about height maps, I read about getting the normal from an implicit surface as in this link:http://www.iquilezles.org/www/articles/terrainmarching/terrainmarching.htmIt seems like the epsilon number is just made up though. In my projects, I typically just fudge the value until it looks good. Is there a definitive source, or at least a good rule of thumb?
Correct post-displacement normal calculation (Y-component and epsilon)
maths;real time;procedural generation
null
_codereview.169262
require_relative '../price_entry_class.rb'require_relative '../exceptions.rb'require 'spec_helper'describe PriceEntry do it throws expection on invalid date format do expect { described_class.date_from_input_to_storage(20010101) }.to raise_error(InvalidInputData) expect { described_class.date_from_input_to_storage(za) }.to raise_error(InvalidInputData) expect { described_class.date_from_input_to_storage(nil) }.to raise_error(InvalidInputData) expect { described_class.date_from_input_to_storage(-19_199) }.to raise_error(InvalidInputData) endendIs it OK to have multiple expectations in a single Rspec test? rubocop-rspec claims that it would be preferable to separate this test into 4:spec/price_entry_class_spec.rb:14:2: C: Example has too many expectations [4/1].Claim that it is always better to have single assert in every unit test is quite surprising for me. Is there a good reason to split test like this into four separate ones?This test is testing only one thing at a time (is obviously malformed input resulting in exceptions).I can imagine rewriting it to[20010101, za, nil, -19_199].each do |malformed_input| expect { described_class.date_from_input_to_storage(malformed_input) }.to raise_error(InvalidInputData)endbut I am not convinced that it is improving readability, maintainability or anything else.
Rspec test to confirm rejection of four invalid dates
ruby;datetime;unit testing;error handling;rspec
The reason is that if this test fails, you'll have to separately determine which of the 4 sub-expectations has failed.Depending on the output of your test reporter, this may or may not be a practical problem.This test is testing only one thing at a time (is obviously malformed input resulting in exceptions).Actually, you're testing:invalid digits raise an errornon-date characters raise an errornil raises an errornegative numbers raise an errorThat said, if you're essentially doing manual fuzzing and don't care about those distinctions -- though I'd say they seem useful in this particular case -- then I don't see an issue with this. Testing rules and best practices are helpful, but don't get too bogged down in them. If you know your own testing goals, and understand why it might be ok to depart from a best practice, by all means do so.
_softwareengineering.133500
For example, Process P is listening to events E(A) and E(B), but to process either of the events, P needs the other event available too. Naively, when P receives either of the events, it will check if the other event is already received. If not, it can wait. But 1) this does not sound very efficient, especially when each process has many different types of events to process. 2) Also as the number of distributed processes increases to a large number, events are more tangled between processes, processes dies/restarts, etc. all these make the events handling more complicated.So I would like to know if there are any reference doc / model/ implementations for events handling under such a distributed computing environment?
Any reference doc /model/ implementation of enforcing events dependency/ordering in distributed computing?
distributed computing
null
_softwareengineering.234873
The build server at our company sucks. The build agents (there are a dozen of them, each is a separate VM, and apparently they are all living on their own ESX server) are SLOW. The web interface is SLOW and is running on a Windows VM, also on ESX. Everything is SLOW, SLOW, SLOW. Artifact upload sometimes fails for unknown reasons. Sometimes the web interface reports in the UI that it has run out of memory and it seizes up then crashes. It seems like IT is rebooting it at least once every day. Today they are rolling back a minor update because it has caused problems.Currently IT owns the hardware that the build servers run on and we have zero visibility into that. We do have admin control over the software. We (the developers) are constantly complaining about it but nothing seems to really improve. Does it make sense for developers to own the build server(s)? IT doesn't really have as much incentive to make them reliable and fast as developers do. In order to get IT to fix the problems we have to complain to our managers and then they have to talk to their managers who then tell IT to fix it. We can report problems to IT directly but that just doesn't seem to work to get things fixed because IT has lots of other things they need to deal with. Also, the developers are the ones who are actually using the build system and are probably a lot more familiar with it than IT.How does it work at other companies?We are about a 150 person company. So probably half of that is engineering, but a third of that is probably hardware, so we have maybe 40 or so devs.
Should developers own the build server(s)?
continuous integration;build system
null
_codereview.69798
I attempted (incorrectly) to implement foldTree here.Recently, I updated it per Petr's help:treeFold :: (b -> [b] -> b) -> (a -> b) -> Tree a -> btreeFold f g tree = f (g (rootLabel tree)) (map (treeFold f g) (subForest tree))I implemented toList:toList :: Tree a -> [a]toList = treeFold (\x y -> x ++ (foldr (++) [] y)) (\x -> [x])Testghci> stringTreeNode {rootLabel = foo, subForest = [Node {rootLabel = bar, subForest = []}, Node {rootLabel = bippy, subForest = []}, Node {rootLForest = []}]}ghci> toList stringTree[foo,bar,bippy,baz]I'm not sure if it's idiomatic to include the foldr call. Nor am I sure if I like the usage of ++. Please review this code.
Implementing `concat` using `foldTree` on Rose Tree
haskell
null
_unix.336387
Our recently deceased guru compiled a version of openssh for Scientific Linux in 2012 that allows us to lock users into their home directories in a really cool way.For example, we make their home dir (like) /u/sftpdir/./username. When they login, all they see is /username. If we modify that to /u/sftpdir/username/./, upon sftp login they only see /. They cannot go 'up' the tree from there; effectively, the dot is root. Now, I need to update our openssh, and I am not sure what he did to make that work. We are not chrooting, and that would require way too much reconfiguration and many continual man-hours to convert to. Any ideas?
Openssh home dir mods
linux;directory;sftp;openssh;account restrictions
null
_unix.294716
I am pretty new to Linux bash. I am trying to mirror two folders using lsyncd command. Here are the steps I followed.Install the lsyncd package Run the following code: sudo lsyncd /home/dxterity1/NGSNAS1/Screen Shots /home/dxterity1/DataStore/ScreenshotsI am getting an error: There can only be one config file in command line.
lsyncd Error: There can only be one config file in command line. Ubuntu
ubuntu;synchronization
The lsyncd documentation shows this synopsis:lsyncd [OPTIONS] CONFIG-FILElsyncd [OPTIONS] -rsync SOURCEDIR TARGET ...So your command should probably be something like:sudo lsyncd -rsync '/home/dxterity1/NGSNAS1/Screen Shots' /home/dxterity1/DataStore/Screenshots(The first path should be quoted since it contains white space.)
_unix.57570
Possible Duplicate:How to connect two computers via internet with ssh? I'm in LAN running an SSH deamon on one of the Linux machines.I use it to connect from my PC. Now the problem is I can connect to SSH in LAN using internal IP address. How to connect to that SSH in LAN from outside LAN?
Connect to SSH from outside LAN
ssh
null
_datascience.8194
I am a first year PhD student in statistics. During this year I have analyzed the scopes of interest of my scientific advisor and found them unpromising. He is majored in mixtures with varying concentrations models for which I have not found any references to authoritative sources.Now I want to change my PhD theme, however, there are no other scientific advisors in my university which majored in statistics. Therefore, I have 2 questions:Is it possible to write at least 5 articles together with a PhD thesis without scientific adviser? If yes, what is a proper way to do this? Here I mean how to choose a theme, where ask for a help and so on.Is it possible to find a remote adviser to consult with? If yes, how and where can I find him?Also I have no much time for the search. I am interested in statistics, especially in machine learning. I would like my PhD thesis to be of practical value, not pure research one which is popular in my department. Also I have commercial experience in programming (C/C++, R, Python) if that can help.Thanks in advance for any help!
PhD program in statistics
machine learning;statistics;education
Certain ingredients are needed to give you the best chance of a successful PhD. One of the important ones is that you and your supervisor have mutual interests.A second important ingredient, in my opinion, is that you immerse yourself in that environment. It's important to develop a network of colleagues. It helps to spread ideas, start collaborations, get help when needed, and to explore unthought of opportunities.From what you have said, I think you will be missing out on these two important ingredients if you continue in the same place or if you work remotely.What is also important is what you to do after the PhD. PhD is required for academic position. But I think you will be in a weak position to get to the next step (fellowships, faculty positions, etc.) if you do what you proposed. In certain industrial positions it can be looked on favourably, not necessarily for the topic you pursued, but because it says something about your personally. Basically that you can get things gone, rise to a challenge, work independently, work as a team, communicate difficult topics and can bring creativity to solving a problems. My advice would be to find a machine learning research group and apply for PhDs. If this is not possible why not consider following the topic of your supervisor and keep machine learning as a hobby? You will become and expert in statistic and so you will find manny concepts will translate between the various statistical disciplines. But only do this if you get along with her/him, and you can see yourself studying this topic.Finally you could try a compromise? Are there applications for mixing statistics in machine learning? Can you find one? Is there an unexplored opportunity to do something new?As a side note I find it ridiculous that PhD supervisor ask the student for topics. This always leads to problems because the student doesn't really have a clue about the research field. There is room for flexibility but often this hides supervisor laziness.
_cs.13107
I have an algorithmic problem.I have a set of different polygons in the 2D space. Each polygon is represented according to its vertex representation (x and y coordinates) and may contain up to N different vertices. Assuming I have a set of N polygons, then for a new polygon k, how do I determine whether or not k overlaps with each one of the N polynomials in the set AND what is the overlapping reign percentage?This is a purely algorithmic question but I plan on writing the algorithm in parallel using the CUDA platform, therefore any highly parallel solution would be preferred.
How to find polygons overlap reign
algorithms;graphs;computational geometry
null
_unix.20604
I am running Java NetBeans 6.9 jdk 6 on SUSE Linux (a newbie on linux) and I currently need to get the path of the weblogic domain of my Java application.I have read that I can directly access the environment variable by using this :System.getenv(DOMAIN_HOME)The problem is I couldn't find the DOMAIN_HOME environment variable (actually I have no idea on setting up the env. variable in linux). I found instructions on the internet telling me that I could set this up by setting :Export DOMAIN_HOME = /desired_path_to_domainFollowing several instructions found on the internet, I have already tried the following resolutions :I wrote this on my home's .profile : export DOMAIN_HOME=$DOMAIN_HOME:/path_to_domainI also wrote that on my home's .bashrc and on /etc/bash.bashrcI executed this on the konsoleprintenv... and as expected I saw the list of all the environment variables. At first, I thought it was pointed to .profile but it wasn't. It was displaying an entirely different value from what was defined on .profile when I executed the lineecho #PATH... so I concluded that my environment variables weren't defined on .profileThe question is, where exactly is that printenv (environment variables) defined and how can I modify it to include my DOMAIN_HOME variable. Guys, I really need this. I came up posting on forums because none of the solutions above or anywhere else could solve my problem. DOMAIN_HOME remains null (even after restarting my linux server).
How to set up the DOMAIN_HOME environment variable in SUSE Linux
java;linux;domain;weblogic
null
_codereview.60846
A Magic Fraction for N is one that has the following properties:It is a proper fraction (the value is < 1)It cannot be reduced further (the GCD of the numerator and the denominator is 1)The product of the numerator and the denominator is factorial of N. i.e. if a/b is the fraction, then a*b = N!Examples of Magic Fractions are:1/2 [ gcd(1,2) = 1 and 1*2=2! ]2/3 [ gcd(2,3) = 1 and 2*3=3! ]3/8 [ gcd(3,8) = 1 and 3*8=4! ]2/12 for example, is not a magic fraction, as even though 2*12=4!, gcd(2,12) != 1And Magic Fractions for number 3 are: 2/3 and 1/6 (since both of them satisfy the above criteria, are of the form a/b where a*b = 3!)Now given a number N, you need to print the total number of magic fractions that exist, for all numbers between 1 and N (include magic fractions for N, too).Note:The number N will be in the range [1, 500]. (1 and 500 inclusive) You'll have to read the input from STDIN, and print the output to STDOUT Examples:Input: 1 Output: 0Explanation: There is no fraction < 1 whose numerator * denominator = 1!Input: 3 Output: 3Here is my code:#include <stdio.h>int fact(int no){ int res = 1; while(no != 1){ res = res *no; no--; } return res;} int gcd(int x,int y) { int m,i; if(x>y) m=y; else m=x; for(i=m;i>=1;i--){ if(x%i==0&&y%i==0){ // printf(\nHCF of two number is : %d,i) ; break; }}return i;}int main(){ int n,i,j,k,cnt = 0,fa;scanf(%d,&n);for(i = 2; i <= n; i++){ fa = fact(i); printf(%d\n,fa); for(j = 1; j <= (fa/2); j++) { // printf(%d\n,j); for(k=2; k <= fa ; k++) { if(j >k ) { if(((j*k) == fa) && (gcd(j,k) == 1)) { cnt ++; // printf(inside\t j = %d k = %d\n,j,k); } } } }}cnt = cnt + (n-1);if(n >1) printf(%d,cnt);else printf(0);return 0;}Please help me in optimizing this code.
Magic Fraction finder
c;programming challenge;complexity;rational numbers
You have taken a very literal, brute-force approach to solving the problem. As @ChrisWue points out, trying to compute 500! will kill you many times over. Instead of multiplying the numbers out, try factoring instead. Here is an outline of a solution that might work:For every \$n = 2, 3, \ldots, N\$, find the prime factorization of \$n!\$. This is not as nasty as it sounds: if you know that the prime factorization of \$n!\$ is$$n! = \prod_i p_i^{e_i}$$then the prime factorization of \$(n + 1)!\$ is simply that and the prime factorization of \$n + 1\$. For example,$$\begin{alignat*}{4}4! &= 2 \cdot 3 \cdot 4 &&= 2^3 \cdot 3 \\5! &= 4! \cdot 5 &&= (2^3 \cdot 3) \cdot 5 &&= 2^3 \cdot 3 \cdot 5 \\6! &= 5! \cdot 6 &&= (2^3 \cdot 3 \cdot 5)(2 \cdot 3) &&= 2^4 \cdot 3^2 \cdot 5\\\end{alignat*}$$Next, you need to partition \$n!\$ into factors \$a\$ and \$b\$. To ensure that \$a\$ and \$b\$ have no common factors, you simply have to ensure that each prime factor \$p_i\$ is attributed to either \$a\$ or \$b\$, along with all of its exponents \$e_i\$. For example, \$4!\$ can be partitioned as$$\begin{alignat*}{3}(a, b) &= (1&&,\ 2^3 \cdot 3) \\(a, b) &= (3&&,\ 2^3)\end{alignat*}$$but not as$$(a, b) = (2 \cdot 3,\ 2^2)$$since 2 appears in both \$a\$ and \$b\$, making \$\frac{a}{b}\$ reducible.So, the problem reduces to counting the power sets of the distinct prime factors of \$n!\$. Half of those partitions will meet the requirement that \$a < b\$, and half will fail.
_unix.296776
Since I move around, I need to be to change time-zones frequently. I'm on Arch/Xfce. How can I do that? I've tried right click on the watch on the top panel -> properties -> time settings -> time zone. It didn't work. When I type a time-zone, it's not auto-completing and not showing suggestions. When I enter it, nonetheless and press Ok, the time doesn't change according to a new time-zone. What's the proper way to do that?
How can I easily change my time-zone in Arch/Xfce?
arch linux;xfce;timezone;settings
null
_webmaster.105664
This question originates from my post on MyBB support forum. It's been a few days so I figured I should ask somewhere else too.I want to prevent the search engines from offering the Cached version of my pages and I want the code to work across the entire MyBB forum which is using 1.8.10. I found this at HTMLGoodies.com: <meta name=robots content=noarchive>It's very very old so do we need to change it at all to use it in 2017? I found this at WillMaster.com:<meta http-equiv=cache-control content=max-age=0>http://www.willmaster.com/library/web-content-prep/preventing-browser-cache.phpand supposedly it will work across all browsers which sounds way better than the first code. Lastly I found this at Tech-FAQ.com:<meta http-equiv=Pragma content=no-cache>http://www.tech-faq.com/prevent-caching.htmlBut they mention it's for web hosts and is a server-side solution. So I don't know if they mean this code is intended for say, HostGator, or if it's for anyone who has access to their site's code.Which of these should I use? Where is the code I have to change located and can you show a screenshot of the code before and after the changes? I found headerinclude in Ungrouped Templates but there is no <head> tag anywhere.Edit: Only the first line of the last two codes was showing up here so I added a link to where you can see the entire code.Edit 2: Giant embarrassing typo in the title. Fixed.
What do I use to tell search engines not to offer a Cached version of my MyBB forum pages and where is the code I need to alter?
google search;cache;headers;google cache
null
_vi.8670
By default, Vim will fold everything it can if folding is enabled. This can be useful from big complicated files, but it tends to get in the way for smaller, simpler files.For example, if I open a code file that contains just one class, it makes no sense to have that class folded.I think a reasonable metric for whether folding should happen, is the length of a file. If the file is much bigger than the terminal you're viewing it in, folding is probably beneficial. If it would (nearly) fit on a page unfolded, folding is probably more of a hindrance than a help.Is there a way to make Vim only enable folding only if the file you're opening is longer than some size?
How can I enable folding only for files longer than a certain length?
vimrc;folding
You can use the line() function to fold or unfold your file: In your vimrcif line('$') > 20 set foldlevel = 1endifline('$') returns the line number of the last ($) line of your document.Of course, this is executed only when you are launching Vim, so you can use a autocommand like so:autocmd! BufReadPost * :if line('$') > 20 | set foldlevel=1 | endif
_unix.145136
I have MD5 file which lists filename and MD5 sum in the following way:MD5 (file14n0001.xml.gz) = 04eb2524d271077ec8f1a0021779b171MD5 (file14n0002.xml.gz) = 07e2b29645e9211cce9daf1ae27e7b99MD5 (file14n0003.xml.gz) = c31cca187a32743441868822b02d83aaI need to parse out only filename and MD5 sum; for example, the desired output is:file14n0001.xml.gz 04eb2524d271077ec8f1a0021779b171file14n0002.xml.gz 07e2b29645e9211cce9daf1ae27e7b99file14n0003.xml.gz c31cca187a32743441868822b02d83aaMy tr (augmented with sed) expression is:tr -d 'MD5() ' | sed 's/=/ /g'But tr part of the expression also delete all 5s in lines so the output isfile14n0001.xml.gz 04eb224d271077ec8f1a0021779b171file14n0002.xml.gz 07e2b2964e9211cce9daf1ae27e7b99file14n0003.xml.gz c31cca187a32743441868822b02d83aaI kindly ask for a pointer how to proceed.
Tuning tr and sed expression
bash;sed;tr
Command:sed -r 's/MD5 .(.*). = (.*)/\1 \2/' filenameOutput:file14n0001.xml.gz 04eb2524d271077ec8f1a0021779b171file14n0002.xml.gz 07e2b29645e9211cce9daf1ae27e7b99file14n0003.xml.gz c31cca187a32743441868822b02d83aa
_unix.14686
If you have a web-server (e.g. nginx) often you use a fast-cgi server or another application-http-server for dynamic content. That means in both cases you have a nice process separation between the web-server process and the fast-cgi (or application-http-server process - in the following called slave). The web-server is configured such that fast-cgi goes over a socket or http request are proxied.Creating different users for the slave and the web-server you can protect filesystem locations, if there is a security problem in the slave process.But how do I jail the slave process even more under Linux?(Such that it cannot access the net, send mails etc.)I can think of following routes:SELinuxLinux system namespaces ('containers', cgroups)What is the most convenient way on a current distribution like e.g. Debian? How to do it in practice? Any configuration examples?
How to jail a fastcgi server (or a web-proxied server)?
cgroups;jails
Under Ubuntu, another way of jailing is apparmor!It is a path based mandatory access control (MAC) Linux Security Module (LSM). In Ubuntu 10.04 it is enabled by default for selected services.The documentation is quite fragmented. The Ubuntu documentation could be ... better. Even the upstream documentation does not give a good introduction. The reference page states:WARNING: this document is in a very early stage of creation it is not in any shape yet to be used as a reference manual However, getting started is relatively easy. An AppAmor profile matches a executable path, e.g. /var/www/slave/slave. The default rule of a profile is deny (which is great), if nothing else matches. Profile deny-rules match always before allow-rules. An empty profile denies everything.Profiles for different binaries are stored under /etc/apparmor.d. apparmor_status displays what profiles are active, what are in enforce-mode (good), or only in complain mode (only log messages are printed).Creating a new profile for /var/www/slave/slave is just:aa-genprof /var/www/slave/slaveStart in another terminal /var/www/slave/slave and do a typical use case. After it is finished press s and f in the previous terminal.Now /etc/apparmor.d contains a profile file var.www.slave.slave. If the slave does some forking the profile is only very sparse - all the accesses of the childs are ignored.Anyway, the profile is now active in enforce mode and you can just iteratively trigger actions in the slave and watch tail -f /var/log/messages for violations. In another terminal you edit the profile file and execute aa-enforce var.www.slave.slave after each change. The log displays then:audit(1308348253.465:3586): operation=profile_replace pid=25186 name=/var/www/slave/slaveA violation looks like:operation=open pid=24583 parent=24061 profile=/var/www/slave/slave requested_mask=::r denied_mask=::r fsuid=10004 ouid=10000 name=/var/www/slave/configA profile rule like:/var/www/slave/config r,would allow the access in the future.This is all pretty straight forward.AppAmor supports coarse grained network rules, e.g.network inet stream,Without this rule no internet access is possible (including localhost), i.e. with that rule you can use iptables for finer-grained rules (e.g. based on slave uid).Another documentation fragment contains something about sub profiles for php scripts.The var.www.slave.slave profile skeleton looks like:#include <tunables/global>/var/www/gapapp/gap.wt { #include <abstractions/base> network inet stream, /var/www/slave/config r, /var/www/slave/exehelper/foo ix, /var/www/slave/db/* rw, ...}With such a profile the slave is not able anymore to call utilities like mail or sendmail.
_unix.82647
#!/bin/bashwhile read server <&3; do #read server names into the while loop if [[ ! $server =~ [^[:space:]] ]] ; then #empty line exception continue fi echo Connecting to - $server#ssh $server #SSH login while read updatedfile <&3 && read oldfile <&4; do echo Comparing $updatedfile with $oldfile if diff $updatedfile $oldfile >/dev/null ; then echo The files compared are the same. No changes were made. else echo The files compared are different. # copy the new file and put it in the right location # make a back up of the old file and put in right location (time stamp) # rm the old file (not the back up) #cp -f -v $newfile mv $oldfile /home/u0146121/backupfiles/$oldfile_$(date +%F-%T) fi done 3</home/u0146121/test/newfiles.txt 4</home/u0146121/test/oldfiles.txtdone 3</home/u0146121/test/servers.txtThis is my whole scriptmv $oldfile /home/u0146121/backupfiles/$_$(date +%F)This moves the file correctly but it removes the actualy file name and just adds the date. I want to keep the original file name and add the current date to the file name.
Adding a time stamp when moving a file in bash
bash;rename;filenames;variable substitution
null
_unix.277932
I've noticed HP-UX swinstall can install two different versions, or releases of the same program.But if I want to upgrade a program?Usually I do:swremove NAMEOFPRODUCTswinstall NAMEOFPRODUCTIs there an upgrade option like Linux (upgradepkg, rpm -Uvh, etc..)on HP-UX?
How do I upgrade a program on HP-UX?
hp ux;swinstall
Is possible to upgrade using option Match What Target Hasusing the gui,i don't know if is possible even with cli. Software Distributor Administration Guide: HP-UX 11i v1, 11i v2, and 11i v3 > Chapter 2 Installing Software Match What Target Has examines your current Installed Product Database to match your existing filesets with new filesets (those with the same names) that you are going to install. This feature is most helpful when you are updating a system to newer versions of the same software. This option can be set from the Options Editor. If multiple targets are specified, the first target in the list is used as the basis for selections.
_unix.254131
There are some strange directories appearing in /home (so far, maybe in other locations too).These directories do not show up in ls but do with bash's tab autocomplete, when doing things like cd.The exact name of this mystery directory is .directory.ls and cd fail on these directories.P.S. There was more than one in /media, but they seem to have disappeared now.UPDATE: Output of ls -la /home:total 12drwxr-xr-x 3 root root 4096 Jan 3 11:28 .drwxr-xr-x 23 root root 4096 Jan 3 11:32 ..drwxr-xr-x 25 bharadwaj bharadwaj 4096 Jan 8 22:58 bharadwajlrwxrwxrwx 1 root root 44 Jan 3 11:13 .directory -> /etc/kubuntu-default-settings/directory-home
Strange directories in /home
bash;files;ls;autocomplete;directory structure
They should be files not directories. They are created by the dolphin file browser in order to support per directory behavior of the file browser.See Here
_cstheory.22098
I am interested in two super-objects problems from computational biology.The first problem, dubbed Shortest Common Supersequence ($SCSy$), takes a family of sequences $s_1,\ldots,s_k$, and seeks a common supersequence of minimum length.The second problem, dubbed Shortest Common Supertree ($SCSx$, introduced here), takes a family of p-trees $t_1,\ldots,t_k$, and seeks a common supertree of minimum length.I have some issues ascertaining the fixed-parameter tractability or $\mathsf{W[1]}$-hardness of the following parameterizations:(i) $SCSy$ parameterized by the number of sequences $k$: the problem is claimed to be $\mathsf{W[1]}$-hard in M. Hallett's thesis without proof;(ii) $SCSx$ and $SCSy$ parameterized by the number of duplications of the super-object: in the above mentioned paper, the first problem is claimed to be FPT and the second is claimed to be $\mathsf{W[1]}$-hard, but I couldn't convince myself whether this is correct.Any people from the FPT scene willing to help?
Fixed-parameter tractability of SCS: finding the missing proof(s)
reference request;parameterized complexity
null
_unix.38495
I'm doing on one open-source application. Now I'm choosing it's license and I'm thinking about GPL.But there I've got few questions:Is anyone allowed to share modified program using same name? Do I have any ownership on software?Do I take any responsibility for program usage, unexpected behavior,...?
Does GPL mean that whole software is public?
licenses;gpl
Is anyone allowed to share modified program using same name?It depends; the GPL doesn't really specify that, since names aren't copyrighted. They are, however, obligated to clearly state it's not the same:The work must carry prominent notices stating that you modified it, and giving a relevant date.To control the name itself, you need a trademark, and you can certainly deny anyone the use of such trademark for forks of the program, even if it's GPL licensed. As an example, Firefox is distributed as Free Software (including GPL), yet you can't call modified versions Firefox, due to Mozilla's trademark policy.Do Ii have any ownership on software?You, as the developer of the software? Yes, you are the copyright owner/holder; in fact, that's why you can license the software as GPL. As the copyright holder you are also not subject to the license yourself, and may distribute it in the future under a different license (although you cannot revoke the GPL licenses of versions previously distributed under it).As an example, MySQL AB (one of the previous owners of MySQL) used to distribute MySQL as both GPL and sell commercial licenses to people or companies who didn't want to become subject to its restrictions.But you should be careful: if you accept contributions from others and they don't assign their copyright to you, you are not the owner of such code; although you can still use it under the terms of the GPL, you can not re-license it.Do i take any responsibility for program usage, unexpected behavior,...?Not because of the GPL; it even includes sections disclaiming warranty and liability. However, a copyright license doesn't supersede the law, so you may still be liable. You should check with a lawyer to know the relevant legislation on that matter.
_softwareengineering.228095
In Java and other high-level languages, a reference leads to an object.In C++, as far as I know, a pointer can also lead to an object.So what's the difference between a reference leading to an object, and a pointer leading to an object?
Difference between a pointer and a reference?
pointers;low level;reference;object;high level
null
_webapps.106334
I need to sort cells randomly, but not only values but their formats too (for example cells with data validation).This code can shuffle values but not formats.Actually, the main question is how to swap cells.function shuffleRange(range) { range.setValues(shuffleArray(range.getValues())); } function shuffleArray(array) { var i, j, temp; for (i = array.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); temp = array[i]; array[i] = array[j]; array[j] = temp; } return array;}
Sort cells randomly in a Google Script
google spreadsheets;google apps script
You can use get* methods to get the attributes and formats for the cells you wish to shuffle, then reorder the cells all in a consistent random way, and then use the set* method to assign after reordering.There are a lot of get* methods: various font attributes, data validation rules, text alignment, cell backgrounds, etc. In the example below I only work with font weights (like bold), font styles (like italic), and data validation rules. function shuffleRange(range) { var height = range.getHeight(); var indexArray = new Array(height); for (var i = 0; i < height; i++) { indexArray[i] = i; } indexArray = shuffleArray(indexArray); // indexArray holds numbers 0, 1, 2, 3 ... in random order range.setValues(range.getValues().map(reorder)); range.setFontWeights(range.getFontWeights().map(reorder)); range.setFontStyles(range.getFontStyles().map(reorder)); range.setDataValidations(range.getDataValidations().map(reorder)); // add more such lines using get* and set* methods of Range object function reorder(x, i, arr) { return arr[indexArray[i]]; }}An alternative is to use the copyTo method which can carry all the attributes at once, but then one would have to copy cell by cell, which is probably a lot slower when you have a large range.
_unix.266866
When I want to stop tail -f I press CTRL+C and return to prompt.But when I run ssh connection the CTRL+C breaks the connection. (meanings of flags described here)ssh -t svf cd ~/w/logs; tail -f some_file.log; exec $SHELL -lthis post does not describes how to prevent remote shell to exit for ssh -t remotehost command args ...How to stop command (in this example tail -f) with CTRL+C and do not break ssh connection?
How to prevent CTRL+C to break ssh connection?
bash;ssh
null
_unix.325039
I can't find anything on ask_detect in any of the man pages for setupcon and almost all my search results are examples of preseed files with it set to false; nothing useful at all.What does it actually do?
What does `console-setup/ask_detect` in a preseed config do?
preseed;setuptools
Finally found an answer via some Ubuntu docs. It disables the dialogue asking whether the installer should attempt to (sort of) automatically detect your keyboard code by making you press a few random keys.
_webapps.95218
I want to make my form give a custom error when someone attempts to place an order for a zip code/postal code outside of our delivery area. I tried entering all the zip codes we deliver to in the RecipientAddress.PostalCode is not portion of Show custom error when page, but it doesn't seem to work whenever there is more than one.
Cognito Forms: Custom Error for Multiple Zip Codes
cognito forms
null
_codereview.36182
I have an assignment as follows:Write a program which reads from the keyboard two integers n and m, and a character c from the keyboard. This program should dene and call a function: print rectangle(n, m, c) which prints a rectangle of size n x m consisting of the character cMy solution is:n=int(input(Enter the lenght of the rectangle: ))m=int(input(Enter the width: ))c=cdef print_rect(n, m, c): for a in range(m): print (n*c)print_rect(n, m, c)input(Press enter to close)I am sure there are alternative ways to do this assignment. How would you code this assignment? Do you think my solution is OK?
Printing a rectangle
python;homework;python 3.x;console
I think the assignment wants you to read the character from input as well. When you are printing the input you are composing the string m times. More optimal solution is if you do that 1 time and output it m times: def print_rect(n, m, c): row=n*c for a in range(m): print (row)I would even do it with this oneliner: print((n * c + '\n') * m, end=)
_unix.266141
I'm not too much experienced within Gentoo portage, When I tried to install Nodejs # emerge --ask monit nginx nodejs into my gentoo and i get an error message like:[ebuild N ] net-libs/http-parser-2.6.1 USE=-static-libs ABI_X86=(64) -32 (-x32) [ebuild R ] dev-libs/openssl-1.0.2f USE=-bindist* [ebuild N ] dev-libs/libuv-1.8.0 USE=-static-libs ABI_X86=(64) -32 (-x32) [ebuild N ] app-admin/monit-5.16.1 USE=pam ssl -libressl [ebuild N ] www-servers/nginx-1.9.10-r3 USE=http http-cache http2 ipv6 pcre ssl -aio -debug -libatomic -libressl -luajit -pcre-jit -rtmp (-selinux) -threads -vim-syntax NGINX_MODULES_HTTP=access auth_basic autoindex browser charset empty_gif fastcgi geo gzip limit_conn limit_req map memcached proxy referer rewrite scgi split_clients ssi upstream_ip_hash userid uwsgi -addition -ajp -auth_ldap -auth_pam -auth_request -cache_purge -dav -dav_ext -degradation -echo -fancyindex -flv -geoip -gunzip -gzip_static -headers_more -image_filter -lua -memc -metrics -mogilefs -mp4 -naxsi -perl -push_stream -random_index -realip -secure_link -security -slice -slowfs_cache -spdy -sticky -stub_status -sub -upload_progress -upstream_check -xslt NGINX_MODULES_MAIL=-imap -pop3 -smtp NGINX_MODULES_STREAM=-access -limit_conn -upstream [ebuild N ] net-libs/nodejs-5.6.0-r1 USE=npm snapshot ssl -debug -doc -icu {-test} CPU_FLAGS_X86=sse2 PYTHON_TARGETS=python2_7 !!! Multiple package instances within a single package slot have been pulled!!! into the dependency graph, resulting in a slot conflict:dev-libs/openssl:0 (dev-libs/openssl-1.0.2f:0/0::gentoo, ebuild scheduled for merge) pulled in by>=dev-libs/openssl-1.0.2f:0=[-bindist] required by (net-libs/nodejs-5.6.0-r1:0/0::gentoo, ebuild scheduled for merge) ^^^^^^^^ (dev-libs/openssl-1.0.2f:0/0::gentoo, installed) pulled in by>=dev-libs/openssl-0.9.8f:0[bindist=] required by (net-misc/openssh-7.1_p2-r1:0/0::gentoo, installed) ^^^^^^^^ dev-libs/openssl:0[bindist=] required by (dev-qt/qtnetwork-5.5.1:5/5::gentoo, installed) ^^^^^^^^ It may be possible to solve this problem by using package.mask toprevent one of those packages from being selected. However, it is alsopossible that conflicting dependencies exist such that they areimpossible to satisfy simultaneously. If such a conflict exists inthe dependencies of two different packages, then those packages cannot be installed simultaneously. You may want to try a larger value ofthe --backtrack option, such as --backtrack=30, in order to see ifthat will solve this conflict automatically.For more information, see MASKED PACKAGES section in the emerge manpage or refer to the Gentoo Handbook.After that, I try emerge --sync and emerge -u world but not fine.Some topic said I should remove ssl but I'm not sure it's a real way to solve it.
An issue that use Emerge to install package
gentoo;emerge
null
_webapps.108282
Often I have gigantic spreadsheets that has many cells that I need to update. But I also like to use the keyboard as much as possible (i.e. using keyboard shortcuts) and avoid using the mouse to be more efficient. A common situation I have where I have to switch between keyboard/mouse is when I search for a term, and it finds it, but then I have to click on that cell with my mouse first before I go back to the keyboard.Is there a way to select that cell directly using the keyboard?
How to select the cell that matches a search on Google Sheets
google spreadsheets;keyboard shortcuts
null
_cs.72459
For NP completeness proofs/reductions, I need to establish that the problem is a search problem...However, the definitions seem to be somewhat vague. If the definition of the search problem is: Search problem is a problem which has the following input/output form: Given instance I (graph G), we are asked to find a solution if one exists and if no solution exists we output No. Aditionally, solution must be verifiable in polynomial time. The part bracketed between the H-lines is where I am confused. Is this definition for a requirement for a non-deterministic polynomial time algorithm stating that the algorithm actually knows when the search has been completed? In other words, what guarantee is there that the solution exists at all, and that the solution has been found?Take for example an infinite search space. No matter how many random guesses I make, there is still a chance that I never discover the solution, never know that the search space has been comprehensively searched, and never return NO. So: two questions: how does one include the word exist in the definition--this seems like something that cannot be proven...And: How does the non-deterministic search problem search the infinite (unbounded) search space? Why do I not also have to establish that the space is also finite? (incidentally, all the search spaces I have encountered in Dasgupta's book are, in fact, finite: TSP, Knapsack, Clique, etc. So I'm really confused by the use of these words, and the lack of assumptions surrounding this definition. How does it actually work?
NP Completeness: definition of search problem: Existence and Infinite Search space
np complete;reductions;np;search problem
null
_webapps.6283
I'm looking for something like lorem ipsum for images.I found this http://dummyimage.com/ but it's not what I'm looking for.I'm a coder and I have to test forms with images uploads. So I need some pleasant-looking dummy images, scenery or something. Is there something like this? If not, I'm gonna make one.Thanks.
Lorem Ipsum for images
webapp rec;images
Google - Advanced Image SearchAll required parameters are availableSearch keyword input - Scenery, Model, Vehicle etc Content Types SizeExact Size Aspect RatioFile Types - Jpg, Gif, Png and Bmp ColorationDomain - try flickr or picassa if you want images from specific domainUser Rights - you might want to choose labeled for commercial reuse Safe Search
_unix.28503
There are some commands which filter or act on input, and then pass it along as output, I think usually to stdout - but some commands will just take the stdin and do whatever they do with it, and output nothing.I'm most familiar with OS X and so there are two that come to mind immediately are pbcopy and pbpaste- which are means of accessing the system clipboard.Anyhow, I know that if I want to take stdout and spit the output to go to both stdout and a file then I can use the tee command. And I know a little about xargs, but I don't think that's what I'm looking for.I want to know how I can split stdout to go between two (or more) commands. For example:cat file.txt | stdout-split -c1 pbcopy -c2 grep -i errorsThere is probably a better example than that one, but I really am interested in knowing how I can send stdout to a command that does not relay it and while keeping stdout from being muted - I'm not asking about how to cat a file and grep part of it and copy it to the clipboard - the specific commands are not that important.Also - I'm not asking how to send this to a file and stdout - this may be a duplicate question (sorry) but I did some looking and could only find similar ones that were asking about how to split between stdout and a file - and the answers to those questions seemed to be tee, which I don't think will work for me.Finally, you may ask why not just make pbcopy the last thing in the pipe chain? and my response is 1) what if I want to use it and still see the output in the console? 2) what if I want to use two commands which do not output stdout after they process the input?Oh, and one more thing - I realize I could use tee and a named pipe (mkfifo) but I was hoping for a way this could be done inline, concisely, without a prior setup :)
How can I send stdout to multiple commands?
shell;command line;io redirection
You can use tee and process substitution for this:cat file.txt | tee >(pbcopy) | grep errorsThis will send all the output of cat file.txt to pbcopy, and you'll only get the result of grep on your console.You can put multiple processes in the tee part:cat file.txt | tee >(pbcopy) >(do_stuff) >(do_more_stuff) | grep errors
_ai.240
I've noticed that a few questions on this site mention genetic algorithms and it made me realize that I don't really know much about those.I have heard the term before, but it's not something I've ever used, so I don't have much idea about how they work and what they are good for. All I know is that they involve some sort of evolution and randomly changing values.Can you give me a short explanation, preferably including some sort of practical example that illustrates the basic principles?
What exactly are genetic algorithms and what sort of problems are they good for?
genetic algorithms
Evolutionary algorithms are a family of optimization algorithms based on the principle of Darwinian natural selection. As part of natural selection, a given environment has a population of individuals that compete for survival and reproduction. The ability of each individual to achieve these goals determines their chance to have children, in other words to pass on their genes to the next generation of individuals, who for genetic reasons will have an increased chance of doing well, even better, in realizing these two objectives. This principle of continuous improvement over the generations is taken by evolutionary algorithms to optimize solutions to a problem. In the initial generation, a population composed of different individuals is generated randomly or by other methods. An individual is a solution to the problem, more or less good: the quality of the individual in regards to the problem is called fitness, which reflects the adequacy of the solution to the problem to be solved. The higher the fitness of an individual, the higher it is likely to pass some or all of its genotype to the individuals of the next generation.An individual is coded as a genotype, which can have any shape, such as a** bit vector (genetic algorithms) or a vector of real (evolution strategies). Each genotype is transformed into a phenotype when assessing the individual, i.e. when its fitness is calculated. In some cases, the phenotype is identical to the genotype: it is called direct coding. Otherwise, the coding is called indirect. For example, suppose you want to optimize the size of a rectangular parallelepiped defined by its length, height and width. To simplify the example, assume that these three quantities are integers between 0 and 15. We can then describe each of them using a 4-bit binary number. An example of a potential solution may be to genotype 0001 0111 01010. The corresponding phenotype is a parallelepiped of length 1, height 7 and width 10.During the transition from the old to the new generation are called variation operators, whose purpose is to manipulate individuals. There are two distinct types of variation operators:the mutation operators, which are used to introduce variations within the same individual, as genetic mutations;the crossover operators, which are used to cross at least two different genotypes, as genetic crosses from breeding.Evolutionary algorithms have proven themselves in various fields such as operations research, robotics, biology, nuance, or cryptography. In addition, they can optimize multiple objectives simultaneously and can be used as black boxes because they do not assume any properties in the mathematical model to optimize. Their only real limitation is the computational complexity.
_codereview.172693
So I have a grid with data and above that grid 2 comboboxes, the grid will be filled with data based on the selected values from the comboboxes. This works but can you do it way easier like I did?if (_InitialDataGridPersonList != null){ if (GetSelectedComboBoxPersonStateText() == - && GetSelectedComboBoxPersonLanguageText() != -) { var dataGridPersonQuery = _InitialDataGridPersonList .Where(w => w.Language.Equals(GetSelectedComboBoxPersonLanguageText())); foreach (var person in dataGridPersonQuery) { _DataGridPersonList.Add(person); } } else if (GetSelectedComboBoxPersonStateText() != - && GetSelectedComboBoxPersonLanguageText() == -) { var dataGridPersonQuery = _InitialDataGridPersonList .Where(w => (w.PersonState.Equals(GetSelectedComboBoxPersonStateText()))); foreach (var person in dataGridPersonQuery) { _DataGridPersonList.Add(person); } } else if (GetSelectedComboBoxPersonStateText() == - && GetSelectedComboBoxPersonLanguageText() == -) { foreach (var person in _InitialDataGridPersonList) { _DataGridPersonList.Add(person); } } else if (GetSelectedComboBoxPersonStateText() != - && GetSelectedComboBoxPersonLanguageText() != -) { var dataGridPersonQuery = _InitialDataGridPersonList .Where(w => (w.PersonState.Equals(GetSelectedComboBoxPersonStateText())) && (w.Language.Equals(GetSelectedComboBoxPersonLanguageText()))); foreach (var person in dataGridPersonQuery) { _DataGridPersonList.Add(person); } }Imagine there are like 10 comboboxes. So what I'm asking is, if there is a easier way with less code?PS. I'm using MVVM so no code behind.
Filter a list based on some ComboBoxes
c#;wpf
You have a lot of code duplication. As a first step, your code should be rewritten somehow like that:if (_InitialDataGridPersonList != null){ var personState = GetSelectedComboBoxPersonStateText(); var personLanguage = GetSelectedComboBoxPersonLanguageText(); var personStateSpecified = personState != -; var personLanguageSpecified = personLanguage != -; if (!personStateSpecified && personLanguageSpecified) { AddPersons(_InitialDataGridPersonList .Where(w => w.Language.Equals(personLanguage))); } else if (personStateSpecified && !personLanguageSpecified) { AddPersons(_InitialDataGridPersonList .Where(w => w.PersonState.Equals(personState))); } else if (!personStateSpecified && !personLanguageSpecified) { AddPersons(_InitialDataGridPersonList); } else if (personStateSpecified && personLanguageSpecified) { AddPersons(_InitialDataGridPersonList .Where(w => w.PersonState.Equals(personState) && w.Language.Equals(personLanguage))); }}private void AddPersons(IEnumerable<Person> persons){ foreach (var person in persons) { _DataGridPersonList.Add(person); }}As a second step, you can place all comboboxes in a map where you'll link each combobox with property selector:public enum PropertyType{ State, Language}private static readonly Dictionary<PropertyType, Func<Person, object>> _propertySelectors = new Dictionary<PropertyType, Func<Person, object>> { [PropertyType.State] = p => p.PersonState, [PropertyType.Language] = p => p.Language }private void PopulatePersons(){ if (_InitialDataGridPersonList != null) { var propertyValues = Enum.GetValues(typeof(PropertyType)) .Cast<PropertyType>() .ToDictionary(t => t, t => GetComboBoxText(t)); AddPersons(_InitialDataGridPersonList.Where(p => { return propertyValues.All(v => v.Value == - || _propertySelectors[v.Key](p).Equals(v.Value))); }); }}private void AddPersons(IEnumerable<Person> persons){ foreach (var person in persons) { _DataGridPersonList.Add(person); }}private string GetComboBoxText(PropertyType propertyType){ switch (propertyType) { case PropertyType.State: return GetSelectedComboBoxPersonStateText(); case PropertyType.Language: return GetSelectedComboBoxPersonLanguageText(); ... } return -;}This approach allows you to add another comboboxes without a pain.
_webapps.11913
Is there any way to: given a tweet, view all its replies?I would prefer to do it from twitter.com, but if there is any other 3rd party service that helps, it's acceptable.
Looking for responses to one specific tweet
twitter
null
_unix.86439
I'ma bit of a network newbie, so apologies for the inaccurate vocabulary.Say I have a device connected by IP over USB to my computer (running Ubuntu), that connects to 10.0.0.1. I configured my Ubuntu's Wifi over USB so that my computer's IP on that connection is 10.0.0.1, but I would actually like to redirect all traffic (on all ports) to another server, and just use my computer as a proxy.I played around with some solutions, but my lack of familiarity with network concepts is slowing me down (I spend too much time looking stuff up, and the documentation is often a bit lacking). I'm not even sure if I want to set up a proxy, a firewall (I don't think so), or use the routing tables. What I want to do sounds pretty simple (redirect anything coming from IP over USB to that server over there). So is there a standard way of doing that? iptables? squid? ufw?
Redirecting all IP over USB traffic to a fixed address
linux;networking;iptables
null
_reverseengineering.8983
i think its pretty easy to find the OEP when the packer runs from a different section. there are many tricks, such as running a trace until you hit the codesection, or breaking on writes to the IAT, and putting a bp on the codesection after the last write to the IAT.but what about packer code that runs in the original code codesection? what are some tips and tricks to find the OEP, since the packer is running from the same section,and jumps to the OEP in the same section?
how to find OEP when packer runs from original code section?
ollydbg;oep
null
_codereview.46146
I need to further simplify this solution to auto-format a text-box field intended only for the user to enter their college Grade Point Average (GPA). Here is my code:<label for=collegeGPA>GPA:</label><input type=text name=collegeGPA id=collegeGPA maxlength=4 style=width:45px; onpaste=return false; autocomplete=off ><script type=text/javascript>//<!-- When executed this script [BELOW] auto-formats a Grade Point Average (GPA) field given the element ID [BEGIN] -->function formatGPA(gPAElementID) { var rE = /\D/g; // remove any characters that are not numbers var originalGPA = document.getElementById(gPAElementID); var originalGPAVal = originalGPA.value; var gPAVal = originalGPA.value.replace(rE,); var gPAValFirstCharacter = gPAVal.charAt(0);if ( ( ( parseFloat(originalGPAVal) ) > 4 ) && ( ( parseFloat(originalGPAVal) ) < 5 ) ) { originalGPA.value = 4.00; }else { if ( ( gPAVal >= 0 ) && ( gPAValFirstCharacter < 5 ) ) { gPALen = gPAVal.length; if ( gPALen > 1 ) { gPAa=gPAVal.slice(0,1); gPAb=gPAVal.slice(1); originalGPA.value = gPAa + . + gPAb; } else if ( gPALen == 1 ) { originalGPA.value = gPAVal + .; } else { originalGPA.value = gPAVal; }; } else { originalGPA.value = ; }; };};//<!-- When executed this script [ABOVE] auto-formats a Grade Point Average (GPA) field given the element ID [END] -->document.getElementById('collegeGPA').onblur = function (e) { formatGPA(this.id); };document.getElementById('collegeGPA').onfocus = function (e) { formatGPA(this.id); };document.getElementById('collegeGPA').onkeypress = function (e) { formatGPA(this.id); };document.getElementById('collegeGPA').oninput = function (e) { formatGPA(this.id); };document.getElementById('collegeGPA').onchange = function (e) { formatGPA(this.id); };</script>...and here is my JSFiddle: http://jsfiddle.net/JamesAndersonJr/kxaBJ/1/ I'm looking for a simpler way to format the GPA input dynamically (i.e. as the user types it in). The format should be:1st Character: any digit 0-42nd Character: Always a Period (should also be auto-inserted after user types a valid first digit)3rd Character: any digit4th Character: any digit
Auto-Format GPA while typing : REVISED
javascript;validation
null
_unix.170439
I want to search some empty alternation with ls but nothing is working.I have a list of files: foo.txt foouubar.txt fooubbar.txt fooubar_1.txt foounix.txtI want to have only foo.txt and foouubar.txt I tried:ls foo\(*ubar\|\(\)\).txt but the result is empty. Is there a mistake in my command line?I am in tcsh
How to search empty alternation with tcsh
shell;tcsh
null
_cs.4905
In my Computing Theory course, a lot of our problems involve using induction on the length of the input string to prove statements about finite automata. I understand mathematical induction, however when strings come into play I get real tripped up. I'd really appreciate it if someone would go through the process of making such a proof step by step.Here's an example problem (Exercise 2.2.10 from Hopcroft and Ullman 3rd Edition):Consider the DFA with the following transition table: 0 1 ________-> A | A B *B | B AInformally describe the language accepted by this DFA, and prove by induction on the length of an input string that your description is correct.This is an answered problem in the book, so I'm not looking for someone to do my homework. I just need someone to explain it to me straight.Book's Answer:(taken from here)The automaton tells whether the number of 1's seen is even (state A) or odd (state B), accepting in the latter case. It is an easy induction on |w| to show that dh(A,w) = A if and only if w has an even number of 1's. Basis: |w| = 0. Then w, the empty string surely has an even number of 1's, namely zero 1's, and -hat(A,w) = A.Induction: Assume the statement for strings shorter than w. Then w = za, where a is either 0 or 1.Case 1: a = 0. If w has an even number of 1's, so does z. By the inductive hypothesis, -hat(A,z) = A. The transitions of the DFA tell us -hat(A,w) = A. If w has an odd number of 1's, then so does z. By the inductive hypothesis, -hat(A,z) = B, and the transitions of the DFA tell us -hat(A,w) = B. Thus, in this case, -hat(A,w) = A if and only if w has an even number of 1's.Case 2: a = 1. If w has an even number of 1's, then z has an odd number of 1's. By the inductive hypothesis, -hat(A,z) = B. The transitions of the DFA tell us -hat(A,w) = A. If w has an odd number of 1's, then z has an even number of 1's. By the inductive hypothesis, -hat(A,z) = A, and the transitions of the DFA tell us -hat(A,w) = B. Thus, in this case as well, -hat(A,w) = A if and only if w has an even number of 1's.I understand how to prove things like $\sum_{i=0}^{n}i = \frac{n(n+1)}{2}$ using induction. I'm just confused by how this works with building strings. I'm confused by the bolded parts. I don't understand how they are come up with/how it actually proves what is accepted/how it is inductive.-hat is the extended transition function, by the way.
How do I write a proof using induction on the length of the input string?
automata;finite automata;proof techniques;reference question;induction
As it is unclear where your problem lies, I'll start at the very beginning.Mathematical induction works like the game of Chinese whispers (in the ideal case, i.e. all communication is lossless) or (perfectly set up) dominoes: you start somewhere and show that your every next step does not break anything, assuming nothing has been broken till then.More formally, every induction proof consists of three basic elements:Induction anchor, also base case: you show for small cases that the claim holds.Induction hypothesis: you assume that the claim holds for a certain subset of the set you want to prove something about.Inductive step: Using the hypothesis, you show that the claim holds for more elements.Of course, the step has to be tuned such that it covers the whole base set (in the limit).Important note: people who are confident of their induction skills often gloss over the anchor and leave the hypothesis implicit. While this is fine when presenting your work to an expert audience (e.g. a paper), this is not recommended when doing proofs yourself, especially as a beginner. Write down everything.Consider a simple example over $(\mathbb{N},\leq)$; we want to show that $\sum_{i=0}^{n} i = \frac{n(n+1)}{2}$ holds for all $n \in \mathbb{N}$.Anchor: For $n=0$, $\sum_{i=0}^{n} i = 0 = \frac{n(n+1)}{2}$ clearly holds.Hypothesis: Assume that $\sum_{i=0}^{k} i = \frac{k(k+1)}{2}$ holds for an arbitrary, but fixed $n \in \mathbb{N}$.Step: For $n+1$, compute the sum:$\qquad \displaystyle \sum_{i=0}^{n+1} i = (n+1) + \sum_{i=0}^{n} i \overset{\text{IH}}{=} n+1 + \frac{n(n+1)}{2} = \frac{(n+2)(n+1)}{2}$So the identity holds for $n+1$. (We note that we only needed a tiny part of the hypothesis, namely for $k=n$. That often happens.)The inductive principle now assures us that the claim indeed holds: we have directly shown it for $0$. The step says, if it holds for $0$, it also holds for $1$; if it holds for $1$, it also holds for $2$; and so on.Let's have a look at another example, this time on $(2^\mathbb{N}, \subseteq)$. The claim we want to prove is: for every finite subset $A$ of $\mathbb{N}$, the size of the power set $2^A$ of $A$ is $2^{|A|}$. We perform our induction over $(\mathbb{N}, \leq)$, again, namely over the size of subsets $A$.Anchor: Consider the (only) set of size $0$, the empty set. Clearly, $2^\emptyset = \{\emptyset\}$ and therefore $|2^\emptyset| = 1 = 2^0$ as claimed.Hypothesis: Assume that for all sets $A \subseteq \mathbb{N}$ with $|A| \leq n$ with some arbitrary, but fixed $n \in \mathbb{N}$, we have $|2^A| = 2^{|A|}$.Step: Let $B \subseteq \mathbb{N}$ arbitrary of size $n+1$, and let $b \in B$ arbitrary (such $b$ exists as $n+1 > 0$). Now the hypothesis applies to $B \setminus \{b\}$ and thus $|2^{B \setminus \{b\}}| = 2^n$. Since$\qquad \displaystyle 2^B = 2^{B \setminus \{b\}} \cup \{ A \cup \{b\}\mid A \in 2^{B \setminus \{b\}} \}$,we have indeed that $|2^{B}| = 2 \cdot |2^{B \setminus \{b\}}| = 2 \cdot 2^n = 2^{n+1}$ as claimed.Again, by induction the claim is proven.Now, for your problem can use a common trick: strengthening the statement. If you formulate your claim as the automaton accepts all words with an odd number of ones, you get an induction hypothesis like among all words of length $n$, exactly those with an odd number of ones are accepted by the automaton. This won't lead you anywhere since we don't know anything about how many ones are contained in which part of a given (accepted) word; the hypothesis does not apply on whatever you cut away of your arbitrarily selected word.Therefore, you want to formulate a stronger claim: The automaton is in state $B$ if and only if the consumed part of the input contained an odd number of ones, and show this one. Note that it implies the former claim.Anchor: After processing the only string of length zero, $\varepsilon$, the automaton is clearly in state $A$ as claimed.Hypothesis: Assume that claim holds for input fragments of length up to $n$ which is chosen arbitrarily, but fixed.Step: Consider an arbitrary word $w \in \{0,1\}^{n+1}$. There are two cases.$w$ contains an even number of ones. There are two cases for the last symbol.$w_n = 0$: In this case, $w' = w_1 \dots w_{n-1}$ contains an even number of ones. By induction hypothesis, the automaton is in state $A$ after consuming $w'$. Consuming $w_n = 0$ causes the automaton to stay in state $A$, as claimed.$w_n = 1$: In this case, $w' = w_1 \dots w_{n-1}$ contains an odd number of ones. By induction hypothesis, the automaton is in state $B$ after consuming $w'$. Consuming $w_n = 1$ causes the automaton to switch to state $A$, as claimed.$w$ contains an odd number of ones. Similar to case 1.The principle of induction implies that the claim indeed holds. You perform induction along some partial order; the anchor needs to cover all minimal elements, and sometimes more (depending on the statement).The arbitrary, but fixed is essential! We can not change $n$ in the step and treat it as if it were a fixed number, but we can also not assume anything about it.Denoting the power set with $2^A$ may seem weird. It is rooted in the observation that the power set is equivalent to the set of all functions from $A$ to ${0,1}$, which is denoted thus.Choosing $B$ arbitrary is essential for covering the whole space. One may be tempted to say, Take any such $A$ and add an element that was not there before.. In this case, that would do the same, but it can be easy to get wrong in more complicated settings (e.g. adding nodes to graphs). Always take an arbitrary larger object and then cut it apart to apply the hypothesis on its parts; never assemble the larger object from smaller which are covere by the hypothesis.
_scicomp.24271
How to define a variable which is an integral involving cauchy principal value inside in any computer programming language? I want to know how to break down the procedure step by step from a computational science viewpoint. This is the integral I encounter:$S(\omega') = \int_0^\infty d \omega \frac{1}{\omega} \left( \mathcal{P} \left( \frac{1%}{\omega' - \omega} \right) + \mathcal{P} \left( \frac{1}{\omega' + \omega} \right) \right) \ $The LHS is a function of w'. The RHS is a function of w'. For example, x(t) = 2t+1 defines the variable x in terms of t. t = 1 means x = 3. For example in Matlab:t = 1;x = 2t + 1;Now I want to define the variable S in terms of w'. For example,w' = 1;S = 2w' + 1; %<----(*) But what is S in terms of w' in my question?then S = 3 here. But it is not such a simple expression here. I need the expression of S or set up the integral on the R.H.S so I can get the expression of S in terms of w' like in line (*). For example in Matlab, is it needed to do it using sym (symbolic) or do I have to do it by fourier transform fourier?Note that the R.H.S is a definite integral of w. But since it will disappear, w' is the only variable of S here. Or to cut off the question into parts of just defining Cauchy principal value. I browse in matlab documentation http://www.mathworks.com/help/symbolic/int.htmlint(1/(x - 1), x, 0, 2, 'PrincipalValue', true) is what I encountered. But now I am not calculating improper integral. I want to define the Cauchy principal value of $$\frac{1}{x}$$ as in complex analysis and distribution. i.e. $$P\left(\frac{1}{x}\right) = \lim_{\varepsilon\rightarrow 0^+} \left[\int_a^{b-\varepsilon} 1/x\,\mathrm{d}x+\int_{b+\varepsilon}^c 1/x\,\mathrm{d}x\right]$$. Related question:SokhotskiPlemelj theorem
Defining Cauchy principal value in MATLAB (or Scilab/Maple)?
matlab;computational physics;octave;maple
null
_codereview.124527
Forgive me if this is too simple, but I'm a beginner trying to learn and understand. I came across an exercise to create these three basic functions, and this is what I came up with. Any glaring errors? This program defines three functions: sum(x,y)range(x,y,step)rangeSum (start, end)sum will give you the sum of two numbers.range will give you an array of numbers from x to y, with an optional step argument that dictates the increment to use when listing the range. If no step is given, the default value is 1. rangeSum will give you the sum of a range of numbers from start to end.// sum(x,y) takes the sum of two numbersvar sum = function(x,y){ return x + y;};// range(x,y,step) gives an array of the range of x and y, with an optional step argumentvar range = function(x, y, step){ if (step == null) step = 1; var arr = []; if (step > 0) { for (var i = x; i <= y; i += step) arr.push(i); } else { for (var i = x; i >= y; i += step) arr.push(i); } return arr;};// rangeSum(start,end) gives the sum of the range from start to end. var rangeSum = function(start,end){ var arr = []; for (var i = start; i <= end; i++) arr.push(i); return arr.reduce(function(a,b){ return a + b; });};
sum, range and rangeSum functions
javascript;array
First of all, your code is pretty good. No big errors as you fear, there are comments, right indentation, anyone can understand it easily, and... it works !!! Yet let me suggest a few improvements you could make to make it shine : For all your functions : use a function declaration : it's easier to use since you can use them anywhere in your code (and not only after the var statement was actually evaluated), and the global namespace pollution is the same anyway. The sum() function just doesn't make sense as it stands : Why one would use sum(i, 3) instead of i+3 ?It makes sense again with one or both of those features : type checking or accepting any number of arguments.To type-check or not to is a big debate i won't enter into. I did here since it might be a good way to learn to be cautious about types even in 'typeless' Javascript.So following code does both type checking and accepting any number of arguments : // returns the sum of its arguments (0 if none). // throws if any of them is not a number.function sum() { var result = 0; for (var i=0; i<arguments.length; i++) { var thisNumber = arguments[i]; if ((+thisNumber) !== thisNumber) { throw('Error : argument ' + i + ' of sum is not a number ('+thisNumber + ').'); } result+=thisNumber; } return result;}For range() : change the arguments name to start and end makes understanding the function goal easier.To give step a default value, you don't want to test step against null, but rather against undefined. (it worked because because you used ==, but notice that by using '==null', you're just testing is ?? falsy ?, so the wrong input 0 for step will silently be changed to 1.). You might want to check : that start, end, and step (if provided) are meaningful numbers (see above). that sign(end-start)==sign(step) so end might indeed be reached. that start-end is a multiple of step. Otherwise you don't get end in the range, which i find most annoying. that step is not === 0. In fact the previous check already checked that. // returns an array filled with the range of numbers between start and end,// using a optional step that defaults to 1.// throws if the range cannot be built with the provided arguments.function range(start,end, step){ // step defaults to 1 if (step === undefined) step = 1; // type-check start, end, step here if you wish // ... // checking that step sign allows to reach the end if ((end-start)*step<0) { throw ('the sign of step does not allow to reach end value'); } // checking that step value allows to reach the end value // btw will check that step !==0 also var stepCount = (end-start) / step; if ( stepCount - Math.floor(stepCount) !==0) { // division has remainder ? throw('cannot reach '+end+' starting from '+start+' with the step ' + step); } // build result array var result = []; for (var i = start; i != end ; i += step) { result.push(i); } return result;};For rangeSum i was surprised to see that you didn't re-use the range function you just wrote : In fact you re-wrote a simple version of range.I think only two options are relevant : 1) re-use range, and add an optional step argument for free. 2) if you just want to do a most simple range sum function, go for a for loop and sum by yourself.I choosed (2) :You might want to check : that start, end are meaningful numbers (see above). that that end can be reached with a step of 1 <==> that (start < end) and start, end are integers. ( x === 0 | x )// returns the sum of numbers ranging from start to end(included). function rangeSum (start,end){ var result = 0; // you might want to check some things here. for (var i = start; i <= end; i++) { result += i; } return result;};... But in fact, with just a little bit of math, you can write the simple version of rangeSum in one line : :-) function rangeSum(start, end) { // you might want to check some things here. return (end + 1 - start)*( end + start)/2 ;}Edit :To allow easier understanding :1) I used Math.floor to floor the stepCount. ( you might forget about the 0 | stepCount dirty trick for now ). So when i write if ( stepCount - Math.floor(stepCount) !==0) i test if the division has a remainder.2) ((+thisNumber) !== thisNumber) is a trick to test for thisNumber not being a number or NaN. How ?a) On the left side, we convert thisNumber to a number, so since we use !==, thisNumber has to be from a different type from number => for now it's quite like testing if (typeof thisNumber === 'number').b) But NaN qualifies as a number ( ... ... ), so since NaN !== NaN, the expression above does also consider thisNumber as wrong if its value is NaN.
_cs.2981
I'm trying to prove that $L_1=\{\langle M\rangle \mid M \text{ is a Turing machine and visits } q_0 \text{ at least twice on } \varepsilon\} \notin R$.I'm not sure whether to reduce the halting problem to it or not. I tried to construct a new machine $M'$ for $(\langle M \rangle,w)$, such that $M'$ visits $q_0$ twice, iff $M$ halts on $w$. This is specific $q_0$ given to me, but I didn't come to any smart construction, which would yield the requested. Maybe it's easier to show that it's $RE$ and not $coRE$? It is obvious that it's in $RE$, and I need to show that $L_2^{c}$ is not in $RE$.What should I do?
Showing that the set of TMs which visit the starting state twice on the empty input is undecidable
turing machines;reductions;undecidability;halting problem
Don't make this more complicated than it is. Instead of giving you a full solutions, I will give you a partial solution, which should allow you to work out the details by yourself:Every TM be turned into a TM that visits its initial state exactly once. To do so, introduce a new state $q^'_0$, which will be the new start state. Then add a $\varepsilon$-transition from $q^'_0$ to $q_0$. This is the only way to leave the state $q'_0$.For this modified machine, a accepting run visits the initial state once, and ends in the accepting state. What is left to do is to modify the machine further, such that it jumps back to $q^'_0$, after the machine was in the accepting state. But you have to assure that when $q^'_0$ is visited the second time, you will jump to a new accepting state. But it's not difficult to record how often you visited a state. If you want that another state is visited twice, then you can always made a detour in the beginning that visits this state (you record that the machine is in detour mode be writing a flag on a special tape). Than you reroute the normal computation, such that if it should visit the requested state it visits a copy of this state. Finally, when accepting, you jump back to the requested state. Conceptually, this is not very different to relabeling the states.
_unix.161770
Is there some order of operations to rm? I performed rm on a large directory and am curious where I should look to see what might have been deleted. Does rm work on files first, then directories? Or is it based on some information in the inode table?Specs: rm from GNU coreutils 8.22system: Arch Linux running on a beagleboneblackfilesystem operating on was an external Seagate HDD (ext4) using USB 2.0.Backstory:I was performing some directory cleanup and performedcp -r A/ B/ C/ Dest/Unwittingly, I followed that up with rm -r A/ B/ C/ Dest/when I meant to simply perform rm -r A/ B/ C/I caught this and hit Ctrl+C before too long had passed. Specifically, it was < 3 seconds as I was using the time command in conjunction with rm & cp. I went in and examined Dest/ expecting it to be non-existent, but lo and behold it was whole and appeared to not be affected. This is a bit surprising as A/ B/ C/ were quite small. Maybe 100200MB total. Dest/ however, is just shy of 1TB. Performing an ls on Dest/ showed that there were both files and directories at both ends of the alphabet (e.g. AFile.txt .... .... Zoo.txt). Did I get lucky and cancelled the rm before it wrought havoc on my Dest/ directory? Is rm really that slow (thankfully!)? If not, how does rm go about recursively removing things such that I can guess what might have been lost?I'm not really expecting to recover what I might have lost, just curious what potentially was blown away.
How does rm -r go about recursively removing? In what order?
rm;recursive
null
_unix.22355
Firefox is not working/responding after I open it. No buttons will work. It has been updated twice plus an uninstall and install. I am on PinguyOS 10.10 64bit. The same Firefox is working on Ubuntu 10.04 32bit and Windows7 32 bit. After install, Firefox was the same including my custom addons, should it not be a clean install? Install was done thru synaptic. The OS has been shutdown with no help for Firefox.
Firefox not working past opening
firefox
null
_unix.170270
I have a workflow where I am trying to do the following: For a given existing SSH session, access the remote machinne and perform a process from which a port is returned (e.g. a remote daemon has been started). Using this port, I would like to create a new port forward from within the existing session by using the EscapeChar technique to instantiate an SSH shell within the session and construct the new port forward. My question is the following: How do I -- from a shell script or equivalent -- programatically perform SSH session modifications wherein the EscapeChar is required.
Programatically / dynamically adjust SSH session port forwards
bash;shell script;ssh;ssh tunneling;openssh
null
_codereview.160840
I am learning Python and in particular learning about classes. Since I'm self teaching, I'd appreciate any feedback and constructive criticism.I have a couple specific questions:In Python you can have multiple functions and classes in a single file (module), but is it considered bad practice to do so?Python doesn't have private, so is there a point to having accessor methods like I do below?My IDE suggest I put a comment beneath each function signature. Is it still good to do this when the functions are short and simple, like withdraw(x) in a bank account? BankAccount.py# bank account classclass BankAccount: def __init__(self, name, balance=0.00): self.name = name self.balance = balance def deposit(self, amount): make a deposit self.balance += amount def withdraw(self, amount): make a withdraw if amount > self.balance: raise ValueError(insufficient funds) self.balance -= amount def get_balance(self): #are accessor methods needed in Python? check the balance return self.balancedef main(): customer1 = BankAccount('Alex') print(customer1.get_balance()) customer1.deposit(100) customer1.withdraw(30) print(customer1.get_balance()) customer2 = BankAccount('Sam', 200) print(customer2.get_balance())if __name__ == __main__: main()
Basic Python OO bank account
python;finance
null
_softwareengineering.193438
I've read that ios apps can communicate via unique urls. An online tutorial on tutsplussaysCommunication between apps provides your application with an opportunity to take advantage of other applications functionality, send and receive data between apps, and provide a rich user experience that just works.I have to admit that since I have no experience with objective c and cocoa I only scanned the article. But as far as I've understood the url based communication, your app can register a unique url that serves as a socket for communication.Is this not the perfect basis for a crude file system ? I know that all ios apps run in a sandbox and can only access their own data. I do recognose the merits of this design decision but still it seems cure and curse at the same time. This is not meant to be a discussion about apple's ecosystem and the concept of ios apps.My question is simply:Can url communication be used to create a file storage that works like a simple desk ? I would love an app that could store and host my files to allow a simpler workflow between different apps. Is this technically possible or did I misunderstand the url system ? Would apple allow an app like this in the app store ?
Implement a file system for ios devices
objective c;apple;cocoa;ios
While I think your use case is solved by the URI scheme communication, it wouldn't be a good user experience. Here's some documentation about the URI handling (see the Implementing Custom URL Schemes section).To build a file system using that, you'd define a URI scheme that lets other apps tell you an action, a path, and a callback URI. Something like:x-my-filesystem://home/Documents/MyFile.doc?action=read&callback=x-doc-reader%3A%2F%2F...When someone tried to open one of your files from another app, it would switch their iPhone to your app. Then when you've handled the request you'd call the callback, and it would hand the thing back to the other app. That's visually jarring as well as slowyou've added twice the transition animation time (about a second in total) on top of the actual work time. In addition, you'd run the risk of being rejected for duplicating Apple functionality, as the device already has a filesystem. Admittedly not one that can be used for IPC, but it has one.The Dropbox-style approach of providing an SDK used by host apps solves all of the problems above. Unlike a filesystem for a traditional operating system like OS X or Windows, apps need to specifically opt-in to both the Dropbox approach and the custom-URI one outlined above. The remote filesystem technique gives apps cross-device syncing (including potentially across platforms) so is better still than the technique you outline.
_webmaster.72107
Semalt is blatantly ignoring robots.txt and the best way to block them as a webmaster seems to be blocking Semalt referral traffic through e.g. .htaccess.I just found out that they're also have a form on their own website at semalt.com/project_crawler.php on which they claim YOUR WEBSITE WILL BE ELIMINATED FROM OUR BASE IN 30 MINUTES AFTER YOU FILL IN THE FORM. Considering the way they treat robots.txt and also the fact that some people claim this company is even using botnets to gather data I have my doubts about these claims.Has anyone had any luck with this? Does this form do what they promise?
Semalt ignores robots.txt, does their own form actually do what they promise?
robots.txt;web crawlers;semalt
I have seen these people before and they are just what you describe. In my database, I see that they do read robots.txt, but they do not offer a bot name to block accesses to your site. This site fits my definition of a bad bot (unwanted / unappreciated). There is plenty of evidence of this to be found with a simple Google search.When in doubt, just block their crawler IP addresses:ASN: AS49981 - WorldStream IP Address Range:91.212.229.0 - 91.212.229.255Htaccess code to block ASN AS49981 IP address range and referrer:RewriteCond %{HTTP_REFERER} semalt\.com [NC, OR]RewriteCond %{HTTP_HOST} ^91.212.229.([0-2]*[0-5]*[0-5]*)$ [NC]RewriteRule .* - [F,L]This is a not a subscriber block so you will not be blocking users.Further Details:Semalt.com IP address 217.23.11.15 has ignored robots.txt falling into a bot trap despite reading robots.txt. As well, there is hacker activity from this IP address. This IP address has read images. The following user agents are tied to this IP address:- (Yes. This is a dash and a common scraper tactic.)Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)Mozilla/4.0 (compatible; Synapse)Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; TencentTraveler)Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; TencentTraveler ; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727)Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.1634 Safari/535.19 YEOpera/9.80 (Windows NT 5.1; MRA 6.0 (build 5831)) Presto/2.12.388 Version/12.10Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/38.0.2125.104 Safari/537.36Often, the use of multiple user agents is a tactic to disguise access patterns, however, it is not uncommon for a few user agents to be used over a period of time. Having said that, this list is concerning in it's scope.I have activity for IP address 217.23.11.135 but nothing to report including reading robots.txt, reading images, or user agents. However, I have it tied to semalt.com as well.According to http://www.incapsula.com/blog/semalt-botnet-spam.html:The perpetrators goal is to create backlinks to a certain URL by abusing publicly-available access logs. Their first step is to locate vulnerable websites. Offenders do this by using crawl bots, which typically serve a double functionboth as scanners locating vulnerable targets and as spammers that exploit these vulnerabilities.Coincidentally, the Semalt bot can execute JavaScript and hold cookies, thereby enabling it to avoid common challenge-based bot filtering methods (e.g., asking a bot to parse JavaScript). Because of its ability to execute JavaScript, the bot appears in Google Analytics reports as being human traffic.Recently, substantial evidence revealed that Semalt isnt running a regular crawler. Instead, it appears to use a botnet generated by malware hidden in a utility called Soundfrost.Our data shows that, using this malware-infested utility, Semalt has already infected hundreds of thousands of computers to create a large botnet. This botnet has been incorporated in Semalts referrer spam campaign and, quite possibly, several other malicious activities.To put things in numbers, during the last 30 days we saw Semalt bots attempting to access over 32% of all websites on our service with spamming attempts originating over 290,000 different IP addresses around the globe.To answer your question specifically:Probably the most antagonizing behavior of all is Semalts claims that you can complete an online form to easily remove your website. However, instead of stopping the flood of unwanted requests, is seems that submitting the removal form actually results in increased spam traffic.
_unix.116912
I'm trying to use a Khepera III robot. The documentation says I need a Linux OS with kernel 2.6.x. An Ubuntu 8 image was provided at the website. When I created a virtual machine with that image, I tried to install the packages I need for using Kheperra III but I couldn't. I tried also to install the updates but I couldn't since this version of Ubuntu is not supported anymore.What Linux OS still supports kernel 2.6.x and allows me to install modern packages?
What distribution still supports the 2.6.x kernel?
linux;kernel;version
Ubuntu 10.04 Lucid Lynx is uses the 2.6.x kernel and the server edition is supported until 2015-04. You can download it here - http://releases.ubuntu.com/10.04/For more on the differences between server editions and desktop editions of Ubuntu, see this question on Ask Ubuntu.The main issue seems to be that there is no desktop environment included in the default installation. As such there is no GUI installation, although what they give should be intuitive enough to use. You will get other packages installed which you usually get on a server too. Lucid is also old enough to have a server optimised kernel, I'm not sure what the exact differences are but they should me minor enough not to noticeably affect anything.It should also be ok to install the desktop edition too, it can be downloaded here - http://old-releases.ubuntu.com/releases/10.04.3/ (get a 10.04.4 download for more included updates). The repositories are the same for both anyway, it is just that 'server support' probably means that only the server relevant packages are updated. For example the server optimised kernel will probably get security updates while the desktop kernel won't.
_webmaster.63486
I have two websites that are run as the same service. Each domain offers articles from a different market. At the top of each page the two domains are shown as menu options. If a user clicks one they can switch to the other domain.See here: http://www.cgtag.comEach domain has a different Google Analytics account, and when a user switches domains Google is counting this as a new session. It's listing the other domain as the referral for that new session. When the user switches back to the first domain Google is counting this as a returning visitor.This is messing up my reports. Showing returning visitors values that are higher than reality. It's also increasing hits on landing pages when the user switches, and listing the other domain as a referral site.I've found tips on how to list two domains as one website, but that results in merging the data. I want to keep the two domains separate so that I can track each ones performance, but I don't want to count domain changes as new sessions.Maybe something like treating the two domains as subdomains.
Two different domains as one user session in Google Analytics
google analytics;domains
This has actually been answered a couple of times on Stack Overflow.https://stackoverflow.com/questions/4759312/session-share-across-multiple-domains-on-same-serverhttps://stackoverflow.com/questions/6679007/share-session-between-two-websitesBasically, it's a bad idea unless you use something like OpenID. But if you read these, you'll understand why.
_cs.74350
By dynamic array, I mean an array that when it becomes full we replace it with a new array having greater capacity than the previous array.I read in a textbook that doubling the size of the array is the most efficient resizing. I want to know if this is in fact demonstrably true and not just a matter of personal preference.We will want to minimize the amount of resizing events, because each such event requires O(n) time where n is the number of elements in the list.We also should be careful not to make the list too big because it might be a waste of memory.Why does the author of my textbook say that 2 * array.length() is the magic number?
Why is it most efficient to resize a dynamic array to 2 * array.length()?
arrays;efficiency
null
_webapps.58305
In the case that two people agree that they would accept the result of a coin flip to resolve some dispute.Is there a virtual heads or tails flip of a coin system that could be done online by two people, preferably with email notifications of the result for both participants.
Online or email heads or tails coin flip for two people
email;notifications
Two choices come to mind:Random.org coin flipper (they also offer a Third-party draw service that could be useful for you. This service offers true random numbers.)Flip a Coin Online (this site gives no information on the random number generation algorithim used.)
_codereview.96042
This is the first code I've written. It's for an intro to Java course. Could you look over it and let me know of things I could improve before handing it in?For reference, I've also provided what I'm being graded on at the bottom.import java.util.Scanner;public class LB01Smith { public static void main(String[] args) { System.out.println(This program computes the volume and surface area of a sphere, cube, and tetrahedron using a given dimension.); System.out.println(Next, the program will compute the dimension of a sphere, cube, and tetrahedron using a given volume.); Scanner input = new Scanner(System.in); String usersName; String upperCaseName; System.out.print(Please enter your name, then press ENTER: ); usersName = input.nextLine(); upperCaseName = usersName.toUpperCase(); System.out.println(Hello, + upperCaseName + , nice to meet you!); System.out.print( ); double length = 0; double volume = 0; double cubeVolume = 0; double cubeSurfaceArea = 0; double sphereVolume = 0; double sphereSurfaceArea = 0; double tetVolume = 0; double tetSurfaceArea = 0; double cubeSide = 0; double sphereDiameter = 0; double tetSide = 0; final double PI = Math.PI; final double SQRT_2 = Math.sqrt(2); final double SQRT_3 = Math.sqrt(3); System.out.print(Please enter a dimension for volume calculation, then press ENTER: ); length = input.nextDouble(); cubeVolume = (length * length * length); cubeSurfaceArea = 6 * (length * length); sphereVolume = PI / 6 * (length * length * length); sphereSurfaceArea = 4 * PI * ((length / 2) * (length / 2)); tetVolume = (length * length * length ) / (6 * SQRT_2); tetSurfaceArea = SQRT_3 * (length * length); System.out.println(); System.out.println(The Volume of your CUBE is : + cubeVolume); System.out.println(The Surface Area of your CUBE is : + cubeSurfaceArea); System.out.println(); System.out.println(The Volume of your SPHERE is : + sphereVolume); System.out.println(The Surface Area of your SPHERE is : + sphereSurfaceArea); System.out.println(); System.out.println(The Volume of your TETRAHEDRON is : + tetVolume); System.out.println(The Surface Area of your TETRAHEDRON is : + tetSurfaceArea); System.out.println(); System.out.print(Now, please enter a volume for side or diameter calculation, then press ENTER: ); volume = input.nextDouble(); cubeSide = Math.pow(volume, (1.0/3.0)); float roundedValue = Math.round(cubeSide); sphereDiameter = Math.pow(volume / PI * 6, (1.0/3.0)); tetSide = SQRT_2 * Math.pow(3 * volume, (1.0/3.0)); System.out.println(); System.out.println(The Side of your CUBE is : + roundedValue); System.out.println(); System.out.println(The Diameter of your SPHERE is : + sphereDiameter); System.out.println(); System.out.println(The Side of your TETRAHEDRON is : + tetSide); System.out.println(); System.out.println(Closing Program...); input.close(); System.out.println(The program has ended. Thank you, + upperCaseName + , Goodbye.); }}( __ / 1 ) You name your program LB01LastName, where you change the LastName to your own last name.( __ / 2 ) Submit a copy of your source code (the .java file) .( __ / 2 ) Your program tells the user what the program does.( __ / 3 ) Your program prompts the user for a length dimension.( __ / 6 ) Your program declares and uses constants for the square root of two, square root of three, and pi.( __ / 6 ) Your program correctly calculates the volume and surface area of the cube.( __ / 6 ) Your program correctly calculates the volume and surface area of the sphere with that length as its diameter.( __ / 6 ) Your program correctly calculates the volume and surface area of the regular tetrahedron.( __ / 6 ) Your program outputs the results of the area calculations.( __ / 6 ) Your program outputs the results of the volume calculations.( __ / 3 ) Your program prompts the user for a volume.( __ / 6 ) Your program correctly calculates the side length of a cube with that volume.( __ / 6 ) Your program correctly calculates the diameter of a sphere with that volume.( __ / 6 ) Your program correctly calculates the side length of a tetrahedron with that volume.( __ / 6 ) Your program outputs the results of the length calculations.( __ / 2 ) Your program tells the user that it is terminating.( __ / 6 ) Your code is easy to read because you followed the programming style outlined in section 1.10 of the text by Y. Daniel Lang.and made appropriate use of spaces, indentation, and blank lines.( __ / 6 ) You followed the naming conventions outlined in section 2.8 of the text by Y. Daniel Lang.and used a class name that starts with a capital letter, variable names that are full and descriptive and start with a lower case letter, and constant names that are in all capital letters.( __ / 6 ) Your code is well documented as outlined in section 1.10 of the text by Y. Daniel Lang.and has javadoc style comments before the class and main method.( __ / 5 ) Your code is efficiently written.( __ / 5 ) Extra Credit: Have your program prompt the user for a common area and then calculate the dimension for each shape to have that area.
Geometry Calculations - Cube, Sphere, and Tetrahedron
java;beginner;homework
Your program declares and uses constantsGenerally constants are declared at the class level rather that the method level.followed the programming style ... spaces, indentation, and blank linesI'm fairly certain the extra tabs halfway through your main method are side-effects of Markdown, otherwise fix them to match the rest of the method.Your string literals in System.out.print(ln) are excessively long. Older coding styles dictate 80 characters per line, personally, my team has agreed on 140 cpl. Going much beyond that leads to a lot of head shaking when trying the read the code. It's okay to split string literals with new lines and the + operator. javac will compile out the concatenation. Also, call System.out.println without the empty string to end a line or output a blank line. e.g:System.out.println(This is a really long string + literal that the compiler will combine. + Just don't forget the trailing spaces.);System.out.println();If your class has not covered it, you can find a lot of useful information on formatting output here.Some coding standards (and languages) require you to place all variable declarations at the top of the scope (class, method or block) while others (again, like my team's) prefer the declaration where it is first used. Find out which style the class prescribes and stick to it. Having a large block of declaration after all had output code is confusing.