id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.184596 | I am trying to understand why this program behaves differently depending on Y:#!/bin/bashrm -f /tmp/par21d9I.tmxmkfifo /tmp/par21d9I.tmx; tmux new-session -d true\ 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111$Y\;\ perl\ -e\ \'while\(\$t++\<3\)\{\ print\ \$ARGV\[0\],\\\n\\ \}\'\ \ \>\>\ /tmp/par21d9I.tmx\&sleep\ .1;exec perl -e '$/=/;$_=<>;$c=<>;unlink $ARGV; /(\d+)h/ and exit($1);exit$c' /tmp/par21d9I.tmxtmux version 1.8:Y=Y prg#OKY=YY prg#BlocksY=YYYYYYY prg#BlocksY=YYYYYYY prg#OKtmux version 1.9a:Y=Y prg#OKY=YY prg#BlocksY=YYYY prg#BlocksY=YYYYY prg#OKAny idea why the program hangs for some values of Y? | tmux blocks for certain commands | tmux | null |
_reverseengineering.9356 | I'm debugging a vulnerable app on a remote host. I've set up gbserver on the host with:gdbserver host:1234 /my/target/appOn my local host I've connected with:$ gdb /same/target/appgdb$ target extended-remote 192.168.0.100:1234I connect successfully and can proceed to set a breakpoint on a target instruction, ie:$gdb disas vuln_function.... 0x08048e6b <+116>: retEnd of assembler dump.gdb$ b *0x08048e6bBreakpoint 1 at 0x8048e6bLooking at the disassembled function code and having tested this on the host itself, I'm 100% sure I'm breaking on the right address and in any case I'm triggering a buffer overflow which should make gdb break by itself.But instead of getting the usual breakpoint on my gdb client, nothing happens. gdbserver freezes on the BO (so I'm guessing it did break on the ret) without throwing the segfault. gdb doesn't seem to be crashing or behaving abnormally other than not giving me a prompt on the breakpoint.Is there a special way to set breakpoints when debugging with gdbserver? | gdbserver doesn't trigger breakpoints | gdb;breakpoint | null |
_cs.79522 | I need to find out the time complexity of this algorithm. can anybody help me.To me the outer loop will run N times and the inner two loops are independent so they will run N-1 times. I will add the inner loops and multiple with the outer loop. so Time complexity will be O(N^2). Clarity: CWF-net stand for centralized workflow net. Site() will return the number of available servers. Dup() will duplicate places in the workflow-net. This algorithm will decompose a workflow statically and will assign different tasks to available servers (sites). | I want to know the Time Complexity of this algorithm | algorithm analysis;runtime analysis | null |
_codereview.82160 | I come from VB6 where everything is single threaded, so I've never written a lick of multi-threaded code before. I just added a wait cursor to one of our GUI's by stumbling through the docs, but I'm unsure I've done it the best way. Did I?Control is a Winform view and the code below is located in the presenter class. Full file can be found on GitHub. private void RefreshToDoList(object sender, EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; var getItems = new Task<IOrderedEnumerable<ToDoItem>>(() => GetItems()); getItems.Start(); Control.TodoItems = getItems.Result; } finally { Cursor.Current = Cursors.Default; } }private IOrderedEnumerable<ToDoItem> GetItems(){ var items = new ConcurrentBag<ToDoItem>(); var projects = VBE.VBProjects.Cast<VBProject>(); Parallel.ForEach(projects, project => { var modules = _parser.Parse(project); foreach (var module in modules) { var markers = module.Comments.AsParallel().SelectMany(GetToDoMarkers); foreach (var marker in markers) { items.Add(marker); } } }); var sortedItems = items.OrderBy(item => item.ProjectName) .ThenBy(item => item.ModuleName) .ThenByDescending(item => item.Priority) .ThenBy(item => item.LineNumber); return sortedItems;} | Displaying a wait cursor while we're waiting | c#;multithreading;gui | You shouldn't use Task.Run or Task.Factory.StartNew unless you specifically want to put your work on a new thread, which Parallel.ForEach already does. Also the order by is not executed in your async block by the task, it is executed as it is assigned. This is probably not what you want so you should do a .ToArray at the end of the order by sequence.private async Task<IOrderedEnumerable<ToDoItem>> GetItems(){ await Task.Yield(); //returns the Task here so the UI can process var items = new ConcurrentBag<ToDoItem>(); var projects = VBE.VBProjects.Cast<VBProject>(); Parallel.ForEach(projects, project => { var modules = _parser.Parse(project); foreach (var module in modules) { var markers = module.Comments.AsParallel().SelectMany(GetToDoMarkers); foreach (var marker in markers) { items.Add(marker); } } }); var sortedItems = items.OrderBy(item => item.ProjectName) .ThenBy(item => item.ModuleName) .ThenByDescending(item => item.Priority) .ThenBy(item => item.LineNumber).ToArray(); return sortedItems;}Then in your Refresh:private async void RefreshToDoList(object sender, EventArgs e){ try { Cursor.Current = Cursors.WaitCursor; Control.ToDoItems = await GetItems(); } finally { Cursor.Current = Cursors.Default; }} |
_codereview.21345 | I'm trying to make a sprite cache for SFML sprites. The basic idea I got was to use a map of an enum and a sprite pointer. Then when I would ask for a certain sprite I'd have a manager that would check if the pointer for that sprite is null. If it is, then it would create a new sprite object and clip it to fit what it's supposed to be. If it isn't null, then it means that the sprite object for this particular enum already exists, and I get that.So far I've made this and it works, but I'm not sure I did it quite right.This is my example code. It contains a small class called SpriteManager which holds the sprite map. It does the before mentioned pointer checking and creating, as well as assigning a texture to, and clipping the sprite.Here's the example code:#include <SFML/Graphics.hpp>#include <algorithm>#include <map>enum Sprites{ ITEM1, ITEM2, ITEM3, ITEM4, ITEM5};const int WIDTH = 100;const int HEIGHT = 100;typedef std::map< Sprites, sf::Sprite* > SpriteMap;typedef std::map< Sprites, sf::Sprite* >::iterator iter;class SpriteManager{private: SpriteMap spriteMap; sf::Texture& m_texture; void clipSprite(Sprites name) { spriteMap.at(name)->setTexture(m_texture); switch(name) { case ITEM1: spriteMap.at(name)->setTextureRect(sf::IntRect(0,0,WIDTH,HEIGHT));break; case ITEM2: spriteMap.at(name)->setTextureRect(sf::IntRect((1*WIDTH),0,WIDTH,HEIGHT));break; case ITEM3: spriteMap.at(name)->setTextureRect(sf::IntRect((2*WIDTH),0,WIDTH,HEIGHT));break; case ITEM4: spriteMap.at(name)->setTextureRect(sf::IntRect((3*WIDTH),0,WIDTH,HEIGHT));break; case ITEM5: spriteMap.at(name)->setTextureRect(sf::IntRect((4*WIDTH),0,WIDTH,HEIGHT));break; } }public: SpriteManager(sf::Texture& texture) : m_texture(texture) {} sf::Sprite* getSprite(Sprites name) { if(!spriteMap[name]) { spriteMap[name] = new sf::Sprite(); clipSprite(name); return spriteMap[name]; } else return spriteMap[name]; } ~SpriteManager() { for(iter i = spriteMap.begin(); i != spriteMap.end(); ++i ) { delete i->second; } }};int main(){ sf::RenderWindow window(sf::VideoMode(800,600), Test, sf::Style::Titlebar | sf::Style::Close); sf::RectangleShape background(sf::Vector2f(800.0f,600.0f)); window.setFramerateLimit(30); sf::Texture spriteSheet; if(!spriteSheet.loadFromFile(TestSprites.png)) { return 1; } SpriteManager sprites(spriteSheet); sf::Sprite *sprite = sprites.getSprite(ITEM1); sf::Sprite *sprite2 = sprites.getSprite(ITEM3); sprite->setPosition(100,100); sprite2->setPosition(200,100); while(window.isOpen()) { sf::Event event; while( window.pollEvent(event)) { if(event.type == sf::Event::Closed) { window.close(); } } window.clear(); window.draw(background); window.draw(*sprite); window.draw(*sprite2); window.display(); } return 0;}So far my biggest concerns are:Is the destructor ok? I figured that since I'm allocating sprites that I should delete them all upon the manager going out of scope, though the more I think about it the more uneasy I feel. What would I do if I have to have two of the same sprites on the screen at the same time? Basically what happens now is, if I have two calls for a sprite with the same name:sf::Sprite *sprite1 = sprites.getSprite(ITEM1);sprite1->setPosition(100,100);sf::Sprite *sprite2 = sprites.getSprite(ITEM1);sprite2->setPosition(100,200);I won't actually have two sprites on the screen but only one at the position 100x, 200y, since when I called the first getSprite I created a sprite under ITEM1 key and then when I call the getSprite method the second time I get that first sprite again. Now this is great for memory conservation, however a lot of the times I'll need to have multiple instances of the same sprite on screen. For that I have an idea to add some sort of a counter or something, but nothing concrete yet. Any suggestions? | Sprite cache for SFML sprites | c++;cache;sfml | null |
_unix.298563 | Note: I asked the same question on Ask ubuntu USB 3.0 camera recognized under the live boot (try Ubuntu) but not from HDD if any one think that it should be only in one site please let me know.I have a very weird (at least for me) problem, I am relatively new to Ubuntu and trying to install an Intel RealSense R200 camera under Ubuntu 14.04, I have already installed it and tested on my development pc under Ubuntu 16.04 but has not been able to do so on the 14.04 pc (different pc).This camera works only with USB 3.0 and the pc I am having problems with only has one USB 3.0, now when I do a lsusb this is the result I getBus 004 Device 003: ID 08ff:168b AuthenTec, Inc. Bus 004 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching HubBus 004 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 003 Device 003: ID 1bcf:288e Sunplus Innovation Technology Inc. Bus 003 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching HubBus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 001 Device 002: ID 0951:1665 Kingston Technology Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root huband the result of lsusb -t/: Bus 04.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M |__ Port 5: Dev 3, If 0, Class=Vendor Specific Class, Driver=, 12M/: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M |__ Port 3: Dev 3, If 0, Class=Video, Driver=uvcvideo, 480M |__ Port 3: Dev 3, If 1, Class=Video, Driver=uvcvideo, 480M/: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/4p, 5000M/: Bus 01.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/4p, 480M |__ Port 3: Dev 2, If 0, Class=Mass Storage, Driver=usb-storage, 480MNow for the interesting part is that if I use an installation stick and choose the option of try Ubuntu the camera is listed under the devicesBus 004 Device 003: ID 08ff:168b AuthenTec, Inc. Bus 004 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching HubBus 004 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 003 Device 003: ID 1bcf:288e Sunplus Innovation Technology Inc. Bus 003 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching HubBus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 002 Device 004: ID 8086:0a80 Intel Corp. Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 001 Device 002: ID 0951:1665 Kingston Technology Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubThe camera in question is Bus 002 Device 004: ID 8086:0a80 Intel Corp.and again the lsusb -t/: Bus 04.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M |__ Port 5: Dev 3, If 0, Class=Vendor Specific Class, Driver=, 12M/: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M |__ Port 3: Dev 3, If 0, Class=Video, Driver=uvcvideo, 480M |__ Port 3: Dev 3, If 1, Class=Video, Driver=uvcvideo, 480M/: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/4p, 5000M |__ Port 1: Dev 4, If 0, Class=Video, Driver=uvcvideo, 5000M |__ Port 1: Dev 4, If 1, Class=Video, Driver=uvcvideo, 5000M |__ Port 1: Dev 4, If 2, Class=Video, Driver=uvcvideo, 5000M |__ Port 1: Dev 4, If 3, Class=Video, Driver=uvcvideo, 5000M |__ Port 1: Dev 4, If 4, Class=Video, Driver=uvcvideo, 5000M |__ Port 1: Dev 4, If 5, Class=Video, Driver=uvcvideo, 5000M/: Bus 01.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/4p, 480M |__ Port 3: Dev 2, If 0, Class=Mass Storage, Driver=usb-storage, 480MI tried reinstalling everything, updating the Kernel for 4.4 but nothing works so far, I would be very happy if any one could point me on the right direction. | USB 3.0 camera recognized under the live boot (try Ubuntu) but not from HDD | linux;ubuntu;usb | null |
_unix.224351 | Ubuntu 12.04I have success with make, and output a program name algo.When I type ./algo,the terminal just directly shows 'killed'And I searched the var/log/message or syslog kern.log. I don't see any information about this kill. And dmesg also shows nothing about this.Then I try 'sudo algo'. There is no output at the terminal and log.I know there is perhaps an out of memory manager (OOM). But I want to get some information to confirm what happened. What should I do? | program killed as soon as it runs | linux;ubuntu;make;kill;c++ | null |
_unix.313150 | We got an AIX server with default installed with 6100-06-12-1339 update - from oslevel -s command.When I do try to go with smit suma I only got the information : 0500-059 Entitlement is required to download.The system's serial number is not entitled.Please go to the Fix Central website to download fixes.Now going to page downloading TL07 and appropriate SP is not a problem - just a lot of *.bff files downloaded.I did copy them to folder /tmp/a - yeah I knew the magic name :). Created a .toc file on this folder with inutoc /tmp/a.The file is there and contains all information about the updates involved.Now starting smit update_all or smitty doesn't do a thing. The main difference is that smit update_all is saying that everything is already on same level or higher - which btw it's not. And smitty itself is constantly complaining about like 30 out of 700 updates have missing dependencies which btw are not because I did download them all from the IBM official page - every possible update. I can go to the outside world - since there's information back from update server so I can only assume that's not an issue. Please help. | Can't upgrade TL neither update SP | aix | If you were trying to install AIX 6.1 TL7 with a service pack lower than 9, then you would be trying to apply patches that were older than AIX 6.1 TL 6 SP 12.See: https://www-304.ibm.com/webapp/set2/sas/f/best/aix_service_strategy.pdfunder AIX Level Naming to see the build sequence identifier at the end. AIX 6100-06-12 has a sequence ID of 1339; to get a sequence ID higher than that in TL7, you'd have to select SP 9 (1341) or SP 10 (1415).Also in that PDF, under Other considerations, it says:When moving up to a new Technology Level, you must move to a Service Pack that has the same or later Build Sequence Identifier than your current Service Pack. The Service Pack number itself will not be the same, because the Service Packs will be numbered consecutively as they are released, but the dates will tell you where you need to be on the new Technology Level. The update process will not allow an earlier built Service Pack to be applied to avoid the chance of regression.See the releases and their sequence IDs at:https://www-945.ibm.com/support/fixcentral/aix/selectFixes?release=6.1&function=release |
_unix.237785 | I've found such column in ps -elF:PSR processor that process is currently assigned to.I need something similar but for threads. ps huH p 1234 prints threads of process 1234, can I somehow add PSR column to this output?upd: ok I've found ps -LPp 1234 what answers this question. But I prefer live outout. So can i somehow add PSR column to top -H p 1234? | how to get processor that thread is currently assigned to? | linux;process;cpu;ps | This works for me the best:install htop. yum install htopTo enable thread views in htop, launch htop, and press to enter htop setup menu. Choose Display option under Setup column, and toggle on Three view and Show custom thread names options.Also add PROCESSOR column in settings;Presss to exit the setup.To find process by pid just start typing pid when htop is running. |
_webmaster.56518 | I have been trying to redirect several single URLs to their new locations using Nginx. The URLs are from Blogger and are in the format: http://domain.com/yyyy/mm/slug.For example, I have this: http://example.com/2013/04/chartjs-javascript-library-for-easy.htmlI am using this Nginx rewrite to redirect it, but for some reason it doesn't work:server { location ~ /([2012-2013]+)/.*/chartjs-javascript-library-for-easy.html { return 301 http://$server_name/resource/chart-js; }}I place this in /etc/nginx/conf.d/example.conf which is loaded inside /etc/nginx/nginx.confCan anybody tell me why it doesn't work? It was working sometime back. Am I messing up my regex?EDIT:For some reason, location /test redirects ok, but location /test/html doesn't. Any idea why? | Redirecting single URL with Nginx - not working | redirects;server;nginx | null |
_unix.370667 | I have the following in an expect scriptspawn cat versionexpect -re 5.*.*set VERSION $expect_out(0,string)spawn rpm --addsign dist/foo-$VERSION-1.i686.rpmThe cat command is getting the version correctly however it appears to be adding a new line. Since I expect the output to be the following:dist/foo-5.x.x-1.i686.rpmbut am getting including the error at the begining the following:cannot access file dist/foo-5.x.x-1.i686.rpmWhy is expect adding a new line to the cat command output and is there any way to have this not be done or to fix the output of the cat command? | Cat in expect script adds new line to end of string | linux;cat;output;newlines;expect | TCL can read a file directly without the complication of spawn cat:#!/usr/bin/env expect# open a (read) filehandle to the version file... (will blow up if the file# is not found)set fh [open version]# and this call handily discards the newline for us, and since we only need# a single line, the first line, we're done.set VERSION [gets $fh]# sanity check value read before blindly using it...if {![regexp {^5\.[0-9]+\.[0-9]+$} $VERSION]} { error version does not match 5.x.y}puts spawn rpm --addsign dist/foo-$VERSION-1.i686.rpm |
_webmaster.48298 | I'm confused about how to force my url to use www in the address.I have a .htaccess code like this:<IfModule mod_rewrite.c>RewriteEngine OnRewriteBase /RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L]</IfModule>I'm changingRewriteRule . /index.php [L]withRewriteRule (.*) http://www.mysite.com/$1 [R=301,L]but I still get an error.The page isn't redirecting properly when I open http://www.mysite.com/category | Force url to use www | apache;htaccess;url;url rewriting;no www | null |
_unix.56277 | Today I found an empty directory with a size of 4MB.It had no visible contents, so I tried ls -lah. This showed me some hidden files (not very large). Searching for the reason why the directory was so large I found that the dot file (.) had a size of 3.9MB.Maybe this is a newbie question, but what gets stored in that file? Isn't that just a kind of link to the same directory?Here is the shell output (anonymized):-bash# more /proc/versionLinux version 2.6.18-8.1.15.el5 ([email protected]) (gcc version 4.1.1 20070105 (Red Hat 4.1.1-52)) #1 SMP Mon Oct 22 08:32:04 EDT 2007-bash# pwd/data/foo/bar/tmp-bash# ls -lahtotal 4.1Mdrwxrwxrwx 3 nobody nobody 3.9M Nov 21 10:02 .drwxrwxrwx 16 nobody nobody 4.0K Aug 27 17:26 ..-rw------- 1 root root 20K Oct 25 14:06 .bash_history... | Why could the size of the dot file . exceed 4096? | filesystems;directory;ls;ext4;size | The dot file, like every directory, contains a list of names for the files in this directory and their inode numbers. So if you once had lots of files in that directory (not unlikely for a tmp directory) that would have made the directory entry grow to this size. After the files are gone, the file system doesn't automatically shrink the directory file again.You can experiment with this yourself by making a new empty directory, do ls -la in it to see the initial size (4096 on my machine) then touching a lot of files, which will make the directory size grow. (Yes I know that I'm glossing over/being inaccurate about a lot of details here. But the OP didn't ask for a full explanation of how EXT* file systems work.) |
_webmaster.82541 | We thought of having a VAS server at home and collected everything every bit of hardware but the problem we found is that how to get a subnet at cheaper price like that of digital ocean or any other server, how do they actually get IPs? | How to get multiple public ip address in India? | ip address | null |
_unix.324519 | I use the following code to convert WAV to ALAC (bash, macOS 10.12.1):find . -type f -iname *.wav | while read fn; do ffmpeg -i $fn -acodec alac ${fn%.wav}.m4a; doneBut there seems to be a mistake since it prints warnings like this:n---8085/03_Part_III.wav: No such file or directoryThe correct path would be:Bad_Religion/wav/Bad_Religion---8085/03_Part_III.wavFor some reason the path is truncated.What's wrong with the command? | Problems converting WAV to ALAC by a batch job | bash;ffmpeg;conversion;wav | Your file names are not actually being truncated. Here, ffmpeg is trying to read commands from its input stream. Unfortunately, this is the same stream read is using to determine filenames, so it appears that parts of these filenames are not being read. To fix this, you should tell ffmpeg to disable interaction on the input stream with the -nostdin flag. |
_unix.138901 | So I have a python script that emulates an ESC_KEY on pin 17 (Raspberry Pi).#!/usr/bin/env python#Imports for Pins,inputimport RPi.GPIO as GPIOimport uinputfrom time import sleep#Setupkey_events=( uinput.KEY_ESC, )device=uinput.Device(key_events)GPIO.setmode(GPIO.BCM)GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)#MAINwhile True: GPIO.wait_for_edge(17,GPIO.FALLING) device.emit(uinput.KEY_ESC,1) sleep(2) device.emit(uinput.KEY_ESC,0)Is there an easy way to set this up as a kernel module, or does anyone have some good documentation to create this kernel module? Do I need to rewrite it using C?It seems as this is eating alot of resources when running in python, I'm hoping it would be less a strain on the system when run as module. | From Python script to Kernel Module | kernel modules | Is there an easy way to set this up as a kernel moduleProbably not. Also, that might be kind of contra good design principles, because what you have seems like more of a userspace app; there's a kernel driver lurking in the background of it anyway.1It seems as this is eating alot of resources when running in pythonConsidering it sleeps most of the time, that's not a good sign; maybe you should be more specific. The stuff I've done with the rpi pins is all I2C based in C or C++ using the kernel interface, and something simple like this wouldn't be more than 1 MB RSS or use any noticeable CPU time.Do I need to rewrite it using C?Re-writing it in userspace C might solve your problem, if the problem is resources (WRT kernelspace code, yes, that is C and asm only). However, python should not be all that bad -- there's obviously no performance issue here. Again, you should describe the problem in more detail.The RPi.GPIO module is written in C, you might want to take a look at that. However, IMO if you don't know the language already and don't have an interest in it otherwise, it is not worth learning just for this.You could also try using the (language agnostic) existing kernel interface in python directly, instead of RPi.GPIO; it's simply a matter of reading from and writing to file nodes in /sys/class/gpio. You'll find more stuff about that online if you search and at the raspberry pi exchange. The DMA hack mentioned in the footnote may have an advantage over this if you are trying to do things at a very high frequency, but that's not the case here (and I'm dubious as to how useful it really would be in this sense, because it is still a pure userland entity and subject to kernel latency).1 Actually that's not true in this case -- RPi.GPIO uses a direct memory address hack like this one; I think the C level wiringPi modules also work this way. That's stuff that would make a good kernel module, except the kernel already has a gpio module with a userland interface. I imagine the justification for the DMA hack is that it seems more efficient (and more interesting to write). |
_softwareengineering.274444 | I've been working in Agile for a while and am working to move more towards agile at a new company. One of the problems I have always sort of encountered is effective integration of QA within the sprint.We've done better at getting stories to QA earlier and shortening that feedback loop, but in the example of a 2-week sprint it was always inevitable that the last stories would get to QA late in the sprint, so QA would finish testing within the sprint but what does the developer do? They're done and have delivered all their stories, short of anything coming back from QA/UAT. How do we ensure they aren't just twiddling their thumbs for the last day-2 days of a sprint? | Integrating QA within agile sprints | agile;qa;sprint | null |
_reverseengineering.8877 | i have the following question:For example, when I have the structure IMAGE_SECTION_HEADER STRUCT | C1 | C2 Name1 BYTE | +0 | +0 union Misc | PhysicalAddress DWORD | 2 | 2 VirtualSize DWORD | 6 | ends | VirtualAddress DWORD | 10 | 6 SizeOfRawData DWORD | 14 | 10 PointerToRawData DWORD | 18 | 14 ...(etc.)Then how I must count the offsets? The columns C1 and C2 represent my solutions but i am not sure which of the two is right or if both are wrong.Do I have to consider the union in the structure as 1 field, or do I need to consider its fields separately?best regards, | Counting offsets of structure fields | structure | A union is a list of fields starting at the same address in memory (except for bitfields, of course). Its size is at least the size of the largest field in it. In your case, it would be 4 bytes.Note that, like structs, the size can be bigger due to alignment requirements. For example, take this C union:union MyUnion { char a[5]; int b;};The a fields is 5 bytes, b is 4. You would expect the union to be 5 bytes, but, as you can check with sizeof(union MyUnion), it is actually 8. This is because ints are aligned to a 4-byte boundary. Similiarly, shorts are aligned to 2 bytes and doubles to 8. Try it on CodingGround.You may be asking yourself: why does the compiler align the union size? Isn't aligning the starting address enough? It could well keep the size of MyUnion to 5 and align the start to a 4-byte boundary for the int. The problem comes when you have an array of the union. An array needs to be a contiguous block of memory because of how array and pointer arithmetic works. Given a generic T array[] you have that array[i] == *(array + i) == *((T *) (((char *) array) + i * sizeof(T))). In the example case, MyUnion has a 4-byte alignment requirement (the largest aligment in the union). If you have a MyUnion array[], the starting address will be 4-byte aligned because of the int. This means that array[0] will be correctly aligned. But if the size of the union is 5, then array[1] will be at a 5 bytes offset from the starting address. This is not 4-byte aligned! Aligning the union size to 8 bytes puts array[1] to a 8 bytes offset, which is 4-bytes aligned. Aligning the size by padding the union allows the array to be contiguous while keeping everything aligned.Bottom line:In a union (or a struct), both the starting address and the size are aligned to the biggest alignment requirement of the fields.Of course, alignment requirements may vary between compilers and architectures. Keep that in mind.Neither C1 nor C2 is correct as far as I can see, since the first field is a byte and not two:IMAGE_SECTION_HEADER STRUCT |w/o align| aligned |Name1 BYTE | +0 | +0 |union Misc | +1 | +4 | PhysicalAddress DWORD | | | VirtualSize DWORD | | | ends | | |VirtualAddress DWORD | +5 | +8 |SizeOfRawData DWORD | +9 | +12 |PointerToRawData DWORD | +13 | +16 | ...(etc.) |
_unix.45995 | It happened that I had set the grub password in grub.conf. But, using a live linux iso, I was able to delete the password from the grub.conf. Please read the steps for the same mentioned in this link: http://gofedora.com/how-to-recover-crack-root-password-grub-locked/Instead of editing menu.lst, I edited the grub.conf. Rest all steps sameMy question is: Is there a way to prevent such a hack. When I tried rescuing, the system showed a message that if it is not able to rescue (i.e. if it fails mounting the HDD under the directory: /mnt/sysimage), do I want to continue/skip/abort.So, I feel that there must be a concrete way of preventing such hacks by doing something with the mounts/boot etc, which shall prevent mounting into /mnt/sysimage.Any help would be valuableEdit:PS: Please re-consider this environment for a virtualised environment where the actual VM in VSphere is a linux VM, and I need to disable/delete the CD/DVD-Rom and network boot from BIOS. After doing all that stuff, I want to re-package the VM into .ovf and check whether the new ovf has the BIOS restrictions or not. | Prevent hacking the grub.conf using a 'live rescue' from a live linux iso | security;boot;grub;virtualization;vmware | null |
_unix.275661 | As we know, with systemd, core dumps don't just get written to the current directory but to some obscure journal. Now, I'm a poor old non-root user on some machine, and - I want my core dumps! I can't follow the suggestions to edit files in /etc or run systemd utilities as root. Can I still get my core dump files somehow?PS - If it matters, I'm on Fedora 22. | How can a poor old non-root user get the core dumps systemd ate? | systemd;not root user;core dump | Use systemd's coredumpctl to list and retrieve your core dumps. Use the PID or name of the program to select one to dump (to file -o ...) or to run gdb on.$ coredumpctl listTIME PID UID GID SIG PRESENT EXEMon 2016-04-11 11:18:23 CEST 21538 1000 1000 11 * /usr/bin/sleep$ coredumpctl info 21538 PID: 21538 (sleep) UID: 1000 (meuh) ...$ coredumpctl -o core dump sleep$ coredumpctl gdb 21538(Some intermediate versions of systemd use the name systemd-coredumpctl).Your userid must be in group systemd-journal to be able to do this without becoming root. |
_softwareengineering.133486 | I recently took on a contract job that will largely involve generating data feeds from my client's data and sending it to external partners, via feeds and API invocations.I've always found this particular kind of coding to be frustrating, for a number of reasons:You have to rely on specs, which often diverge from the actual implementation or simply don't go into sufficient detailYou have little to no ability to see into the external system, to ensure that your data has been accepted and interpreted properlyIf there's any kind of problem with data you've generated, it's not always straightforward to back out the changes and try againExternal testing and staging environments frequently diverge from production logic and the production databaseWhat are some best practices for doing this kind of work? Creating mocks and stubs won't necessarily resolve my problems, as my real concern is: do my feeds have the correct effect on another system, which is basically a black box? Mocks simply duplicate my assumptions. | How should I deal with external data sinks? | data structures;api design | I've done a bit of work in recent years with EDI, and it has all the problems you've mentioned. The biggest problem is that partners don't follow their own specs and when you point it out, they say, this is a deviation but they never document it.Here's how I deal with it and manage to sleep at night:Create a framework for building and maintaining lots of unit tests. At first you'll just test the spec plus your assumptions, but eventually (every time you find a deviation) you have to write another batch of tests to check those new facts.Your system must log everything. It must log everything that happened, when it happened, who did it, what it received, what it wrote, where, etc. You will need this when you go toe-to-toe with your counterpart on the other end, not just to troubleshoot, but as evidence to prove that your system is doing everything it's supposed to do. Confirmations are particularly important to log. These logs are invaluable when you go to write new tests.Build in the ability to retry with modifications. When something happens, you'll want to be able to tweak the data and submit it again.Avoid intermediaries (aka 3rd parties). Unfortunately in our case we actually have 3 different systems our data travels through between us and the ultimate destination (two of which are called value added resellers, or VARs, which is complete BS because from my perspective they add no value at all). When something goes wrong, we get contacted by the end-user at the other end, and then we have to go up one level on our end, ask them to check, and then they go up a level and talk to their VAR, who has to talk to the other VAR, etc. It's frustrating. If you have the ability to communicate with the other system directly, do it. |
_cstheory.10905 | This question arises out of pure curiosity (it came up while thinking about unshuffling a string, but I'm not sure if it's actually related) so I hope it's appropriate.There are various graph products, and I'm interested in any of them here. What is the complexity of determining whether a graph $K$ is isomorphic to a non-trivial product? (Certainly for the Cartesian product, $K = K \square 1$ where $1$ is the graph with one vertex.)I've looked at the pages factor graph and graph factorization on Wikipedia, but neither seem to be related. Is this problem known under another name? | Complexity of is a graph a product | cc.complexity theory;graph algorithms | Check the paper Wilfried, Imrich; Iztok, Peterin, Recognizing Cartesian products in linear time. Discrete Math., 307, 3-5, Page(s): 472--483, 2007. I think that Imrich has more papers for other products. |
_cs.40620 | Given an undirected tree (i.e. a tree without any designated root) of even number of nodes.The task is to remove as many edges from the tree as possible to obtain a forest of trees,where each such tree contains even number of nodes.And return/output number of removed edges as an output/answer.Counting maximum number of removed edges is relatively simple:Choose any node as a root node;Recursively traverse a tree using depth-first approach;Count number of children of each sub-tree (from bottom to up), and cut sub-tree from the tree if this sub-tree has even number of children (i.e. simply increment counter of removed edges);This solution is correct but I don't understand why.I would like to see proof of correctness of such algorithm.In particular, I have the following doubts (when I'm thinking on this solution):Why starting DFS from any chosen root gives correct maximum number of removed edges?Why cutting sub-trees with even number of children from bottom to up gives correct result?I wrote on paper all possible configurations 1, 2, 3, 4, 5, 6-nodes of undirected trees.For example, there are two possible configurations of undirected tree with 4 nodes:(a)x-x-x-x(b)x-x-x | xIn (a), you can split a tree into 2 sub-trees with 2 nodes each.In (b), you can not do it since it will be two sub-trees of odd number of nodes (with 1 node and with 3 nodes respectively).So my doubts based on suggestions:What if it depends where you start cutting sub-trees?What if greedy cutting sub-trees with even number of children from bottom to up doesn't give correct maximum number of removed edges? (continue of first question)This puzzle is described on HackerRank as Even Tree.Their editorial and discussion just declared algorithm but they don't say why it works.Also, I found discussion on stackoverflow but they also don't give explanation why such approach works. | Correctness of splitting an undirected tree into a forest of trees with even number of children | algorithms;trees;graph traversal | I got my Aha! Gotcha moment when I changed my point of view from nodes (as root of a subtree) to edges. Let me explain.The set of edges that can be cut is a static property, the set of choices is not changed by the earlier cuts that have been made. Any edge is considered to be even if on both sides it has an even number of nodes in the tree. Clearly we can only cut even edges. But also, cutting an even edge does not change the even property of the remaining edges, as we merely remove an even number of nodes in subtrees. So, we are set to find the even edges, and we will cut them all. The proposed solution uses DFS, but any decent traversal will do I would think. The property that a subtree has an even number of nodes now means (in my terminology above) that the edge outside leading to the root of the subtree is in fact even. |
_codereview.71431 | I'm trying to represent the following mathematical expression in C:$$P(n)=(n!)(6^n)$$The first program should compute the answer to expression when n = 20. I have attempted to create the program in C and it produces the correct answer (when compared with wolfram alpha's answer). The answer is approximately \$10^{34}\$.Is there any way that I could improve the code?:#include <math.h>typedef unsigned int uint;void main(){ uint n=20; double F=1,pwr,P; pwr=pow(6,n); while(n>0){ F=F*n; n=n-1; } P=F*pwr;} | Representation of the formula P(n) = (n!)(6^n) in C | c;mathematics | null |
_codereview.1489 | Here is my PHP class for solving Sudoku:GitHubSudoku<?php/*** Bootstrap file** This is an example of how to use the SudokuSolver Class* Here the input array has been hardcoded. It could be send* as get or post in the real application.** @author Anush Prem <[email protected]>* @package Solver* @subpackage Sudoku* @version 0.1*//*** Required Class files*/include_once SudokuSolver.class.php;// The application could take longer than normal php execution// time. So set the execution time limit to 0(unlimited).set_time_limit(0);// input sudoku array in the format row == col array mapping$sudoku = array(array(0,4,0,0,5,3,1,0,2),array(2,0,8,1,0,0,7,0,0),array(5,0,1,4,2,0,6,0,0),array(8,1,4,0,3,0,2,0,7),array(0,6,0,2,0,5,0,1,9),array(0,5,0,7,4,0,0,6,3),array(0,0,0,0,7,4,5,8,1),array(1,8,5,9,0,2,0,0,0),array(4,0,3,0,0,8,0,2,6));// create an object of SudokuSolver.$solver = new SudokuSolver();// Pass the input sudoku to the $solver object.$solver -> input ($sudoku);// Solve the sudoku and return the solved sudoku.$solved = $solver -> solve ();// printing the formated input sudokuprint <B>Input Sudoku:</B><br />;foreach ($sudoku as $row){foreach ($row as $col ){print $col . ;}print <br />;}print <hr />;// printing the formated solved sudoku.print <B>Solved Sudoku:</B><br />;foreach ($solved as $row){foreach ($row as $col ){print $col . ;}print <br />;}?>Sudoku Solver<?php/*** @author Anush Prem <[email protected]>* @package Solver* @subpackage Sudoku* @version 0.1*//*** <i>Sudoku Solver</i> class** This class solves the sudoku in my own logic.** This solver takes time to execute according to the* complexity of the sudoku.** @author Anush Prem <[email protected]>* @package Solver* @subpackage Sudoku* @version 0.1*/Class SudokuSolver{/*** To store the input Sudoku* @access private* @var array $_input row == column mapping*/private $_input;/*** To store the currently solved sudoku at any moment of time* @access private* @var array $_currentSudoku row == column mapping*/private $_currentSudoku;/*** To store the probable values for each cell* @access private* @var array $_probable [row][col] == possible values array mapping*/private $_probable;/*** to store weather the sudoku have been solved or not* @access private* @var bool*/private $_solved = false;/*** store weather each cell is solved or not* @access private* @var array $_solvedParts row == column (bool) values*/private $_solvedParts = array (array ( false, false, false, false, false, false, false, false, false ),array ( false, false, false, false, false, false, false, false, false ),array ( false, false, false, false, false, false, false, false, false ),array ( false, false, false, false, false, false, false, false, false ),array ( false, false, false, false, false, false, false, false, false ),array ( false, false, false, false, false, false, false, false, false ),array ( false, false, false, false, false, false, false, false, false ),array ( false, false, false, false, false, false, false, false, false ),array ( false, false, false, false, false, false, false, false, false ));/*** SudokuSolver constructor** If the input sudoku is provided it will store to the {@link _input} property.** @access public* @param array $input row == column mapping* @return void*/public function __construct($input = null){// check if the input sudoku is provided, if yes then// store it in $_inputif ( $input !== null ) $this -> _input = $input;}/*** Input Method** Explictly give a new input array if its not already provided in* the constructor. If already provieded in the constructore then* it will be replaced** @access public* @param array $input row == column mapping* @return void*/public function input($input){// store the received input into $_input$this -> _input = $input;}/*** Solve Method** The main function to start solving the sudoku and return the* solved sudoku** @access public* @return array row == column mapping of solved sudoku*/public function solve (){// Copy the input sudoku to _currentSudoku$this -> _currentSudoku = $this -> _input;// update _solvedParts of the given sudoku$this -> _updateSolved ();// Start solving the sudoku$this -> _solveSudoku();// return the solved sudokureturn $this -> _currentSudoku;}/*** updateSolved Method** Update the _solvedParts array to match the values of* _currentSudoku.** @access private* @return void*/private function _updateSolved(){// loop for rowsfor ($i = 0; $i < 9; $i++ )// loop for columnsfor ($j = 0; $j < 9; $j++ )// if the value exists for the corresponding row, column// then update the _solvedParts corresponding row, column// to trueif ( $this -> _currentSudoku[$i][$j] != 0 )$this -> _solvedParts[$i][$j] = true;}/*** _solveSudoku Method** Main sudoku solving method** @access private* @return void*/private function _solveSudoku(){// continue running untill the sudoku is completly solveddo{// calculate the probable values for each cell an solve// available cells$this -> _calculateProbabilityAndSolve();// check weather the sudoku is completly solved$this -> _checkAllSolved();}while (!$this -> _solved); // run till the _solved value becomes true}/*** _calculateProbabilityAndSolve Method** Find the possible values for each cell and* solve it if possible** @access private* @return void*/private function _calculateProbabilityAndSolve(){// find possible values for each cell$this -> _findPosibilites();// check if each cell is solveable and if yes solve it$this -> _solvePossible();}/*** _findPosibilites Method** Find possible values for each cell** @access private* @return void*/private function _findPosibilites(){// loop for rowsfor ($i = 0; $i < 9; $i++ ){// loop for columnsfor ($j = 0; $j < 9; $j++ ){// if the ixj cell is not solved yetif ( !$this -> _solvedParts[$i][$j] ){// find all possible values for cell ixj$this -> _findAllProbables ($i, $j);}}}}/*** _solvePossible Method** Solve possible cells using probable values calculated** @access private* @return void*/private function _solvePossible(){// loop for rowsfor ($i = 0; $i < 9; $i++ ){// loop for columnfor ($j = 0; $j < 9; $j++ ){// if cell ixj is not solved yetif ( !$this -> _solvedParts[$i][$j] ){// solve the cell ixj if possible using probable values// calculated$this -> _solveIfSolveable ($i, $j);}}}}/*** _checkAllSolved Method** check if all the cells have been solved** @access private* @return void*/private function _checkAllSolved(){// pre assign all solved as true$allSolved = true;// loop for rowsfor ($i = 0; $i < 9; $i++ ){// loop for columnsfor ($j = 0; $j < 9; $j++ ){// if allSolved is still true an the cell iXj is notif ( $allSolved and !$this -> _solvedParts[$i][$j] ){// set all solved as false$allSolved = false;}}}// copy the value of allSolved into _solved.$this -> _solved = $allSolved;}/*** _solveIfSolveable Method** Solve a single cell $rowx$col if it is solveable using* available probable datas** @access private* @param int $row 0-8* @param int $col 0-8* @return bool*/private function _solveIfSolveable ($row, $col){// if there is only one probable value for the cell $rowx$colif ( count ($this -> _probable[$row][$col]) == 1 ){// copy the only possible value to $value$value = $this -> _probable[$row][$col][0];// set the value of cell $rowx$col as $value an update solvedParts$this -> _setValueForCell ($row, $col, $value);// return true as solvedreturn true;}// pre assign $value as 0. ie; not solved$value = 0;// loop through all the possible values for $row x $col// and check if any possiblity can be extracted from it// by checking if its possible for the same number to be// positioned anywhere else thus confilicting with current// cell. If a possibility is not a possibility for any other// cell in the confilicting places then it is the value for// current cellforeach ($this -> _probable[$row][$col] as $possible){// a try-catch exception handling used here// as a control statement for continuing the main loop// if a value is possible in some place.try{// loop through the current columnfor ($i = 0; $i < 9; $i++ ){// if the cell is solved continue the loopif ($this -> _currentSudoku[$i][$col] != 0)continue;// if the possible is also possible in the $i x $col cell// then throw a ContinueException to continue the outer loopif (in_array($possible, $this -> _probable[$i][$col]))throw new ContinueException (Exists);}// loop through the current rowfor ($i = 0; $i < 9; $i++ ){// if the cell is solved continue the loopif ($this -> _currentSudoku[$row][$i] != 0)continue;// if the possible is also possible in the $i x $col cell// then throw a ContinueException to continue the outer loopif (in_array($possible, $this -> _probable[$row][$i]))throw new ContinueException (Exists);}// find the start of the 3x3 grid with $row x $col cell$gridRowStart = $this -> _findGridStart($row);$gridColStart = $this -> _findGridStart($col);// loop row through the current 3x3 gridfor ($i = $gridRowStart; $i < $gridRowStart + 3; $i++){// loop column through the current 3x3 grifor ($j = $gridColStart; $j < $gridColStart + 3; $j++){// if its the current $row x $col cell then// continue the loopif ($i == $row && $j == $col )continue;// if the cell is already solved then// continue the loopif ($this -> _currentSudoku[$row][$i] != 0)continue;// if the possible is also possible in the// $i x $j cell then throw a ContinueException// to continue the outer loopif (in_array($possible, $this -> _probable[$i][$j]))throw new ContinueException (Exists);}}// if the loop is not continued yet,// then that means this possible value is// not possible in any other conflicting// cells. So assign the value of $value to// $possible and break the loop.$value = $possible;break;}catch (ContinueException $e){// if a ContinueException is thrown then contine// the outer loopcontinue;}}// if the value of $value is not 0 then the value of// the cell is $value.if ($value != 0){// set the value of cell $rowx$col as $value an update solvedParts$this -> _setValueForCell ($row, $col, $value);// return true as solvedreturn true;}// return false as not solved yet.return false;}/*** _setValueForCell Method** If a cell is solved then update the value for* that cell, and also update the {@link _solvedParts}.** @access private* @param int $row 0-8* @param int $col 0-8* @param int $value 1-9* @return void*/private function _setValueForCell($row, $col, $value){// update the solved parts in _currentSudoku.$this -> _currentSudoku[$row][$col] = $value;// update the corresponding _solvedParts.$this -> _solvedParts[$row][$col] = true;}/*** _findAllProbables Method** Find all possible values for any given cell using* other already solved or given cell values.** @access private* @param int $row 0-8* @param int $col 0-8* @return void*/private function _findAllProbables ($row, $col){// initially set the $probable as array 1 to 9.$probable = range(1,9);// loop through current columnfor ($i = 0; $i < 9; $i++ )// if the cell $i x $col is solved and the value of// cell $ix$col is in the $probable array then remove// that element.if (( $current = $this -> _currentSudoku[$i][$col] ) != 0and( $key = array_search($current, $probable) ) !== false)unset ($probable[$key]);// loop through the current rowfor ($i = 0; $i < 9; $i++ )// if the cell $row x $i is solved and the value of// cell $rowx$i is in the $probable array then remove// that element.if (( $current = $this -> _currentSudoku[$row][$i] ) != 0and( $key = array_search($current, $probable) ) !== false)unset ($probable[$key]);// find the start of the 3x3 grid with $row x $col cell$gridRowStart = $this -> _findGridStart($row);$gridColStart = $this -> _findGridStart($col);// loop row through the current 3x3 gridfor ($i = $gridRowStart; $i < $gridRowStart + 3; $i++)// loop column through the current 3x3 gridfor ($j = $gridColStart; $j < $gridColStart + 3; $j++)// if the cell $i x $j is solved and the value of// cell $ix$j is in the $probable array then remove// that element.if (( $current = $this -> _currentSudoku[$i][$j] ) != 0and( $key = array_search($current, $probable) ) !== false)unset ($probable[$key]);// Store the rest of the probable values to// _probable[$row][$col]$this -> _probable[$row][$col] = array_values($probable);}/*** _findGridStart Method** Find the start of the 3x3 grid in which the value* comes** @access private* @param int $value 0-9* @return int*/private function _findGridStart ($value){// return the start of the current 3x3 gridreturn floor( $value / 3 ) * 3;}}/*** <i>ContinueException</i> class** Extends Exception. Used to throw exception for* continue the outer most loop.**/Class ContinueException extends Exception{}?> | Sudoku solving class in PHP | php;php5;sudoku | null |
_codereview.125748 | I reproduced my version of Abstract Factory Pattern in Java. I know it's redundant but can I get critical comments about my code. Is it really the classic implementation of the pattern or not?/** The demonstration of Abstract Factory Pattern* * Here the 'DocumentFactory' creates documents of types * 'Resume' or 'Letter' which are concrete classes responsible to* create things like 'FancyResume' or 'CoverLetter'* * The example is inspired by Wikipedia documentation of Abstract* Factory.*/interface letter{ void print();}class CoverLetter implements letter{ @Override public void print(){ System.out.println(Cover letter printed); }}class FancyLetter implements letter{ @Override public void print(){ System.out.println(Fancy letter printed); }}interface resume{ void process();}class CorporateResume implements resume{ @Override public void process(){ System.out.println(Corporate resume processed); }}class FancyResume implements resume{ @Override public void process(){ System.out.println(Fancy resume processed); }}//Create 'Concrete' factories class LetterFactory{ public letter getLetter(String type){ switch(type){ case Fancy: return new FancyLetter(); case Cover: return new CoverLetter(); } return null; }}class ResumeFactory{ public resume getResume(String type){ switch(type){ case Fancy: return new FancyResume(); case Corporate: return new CorporateResume(); } return null; }}// create abstract factoryabstract class DocumentFactory{ abstract LetterFactory letterFactory(); abstract ResumeFactory resumeFactory();}class DocumentCreator extends DocumentFactory{ @Override LetterFactory letterFactory(){ return new LetterFactory(); } @Override ResumeFactory resumeFactory(){ return new ResumeFactory(); }}class abstractfactory{ public static void main(String args[]){ DocumentCreator creator = new DocumentCreator(); // create a fancy letter letter myLetter = creator.letterFactory().getLetter(Fancy); myLetter.print(); // create a corporate resume resume myResume = creator.resumeFactory().getResume(Corporate); myResume.process(); }} | Abstract Factory Pattern in Java | java;abstract factory | null |
_unix.73216 | TLDR: What environment variables should I update to guarantee that my system has access to everything a package provides when building it on a non-traditional path?I usually don't have root access to the system where I work, so I install my packages on local folder under my home directory:~/my_installations/Over time, this creates the typical folder hierarchy that includesbinlibmanshareinfoincludeamong others. In order to properly provide access to the corresponding binaries and libraries after installation, I update PATH to include ~/my_installations/bin and LD_LIBRARY_PATH to include ~/my_installations/lib. However, how can I provide implicit access to the rest of the material under my build path ? What other environment variables should I update to have everything else available to command line tools and my system in general? (e.g. include paths, man pages, etc.).Is there a general set of standards or guide for this? | Installing packages and tools on a local non-standard directory | shell;compiling;environment variables | You can update MANPATH (as well as INFOPATH) to point at your personal directory's man pages. Unfortunately, there's no single way to tell software to also look in your include paths. You might have to set CFLAGS (but not always) or other variable used in the build system. |
_softwareengineering.320301 | What i mean is something like:I have 2 array var and type, you can input the name of the variable on the var array and type of variable on the type array(type depend on language used), then i want to use the value from these array to define varriable i.e:Var[1] as type[1]Var[2] as type[2]Is it possible to do something like that?Second question:Can i auto increase variable name which contain number? I want to do something that work like array but using normal variable. For example :I have 10 variable f1~f10Then i want to loop it until all variable filled, something likeFor a=1 to 10 do{ f(a) = a}Sorry if it is hard to understand i cant explain it very well. I want to know is possible in general programming, specifically pascal because i study alghoritm using this language in college. | Is it possible to use array values to define variable? | programming languages;pascal | What is it that you are trying to do? The way that you are trying to do it is possible in lexical languages, but not pascal.You can though look-up an array by name. This is sort of the opposite of what you asked, but in some ways very similar.type MonthType = (January, February, March, April, May, June, July, August, September, October, November, December);Then use this to look up an arrayord(December)Gives 11, so you could use it to look up days in month.By pascal programming skills are useless, so someone else can fix and extend this answer.http://wiki.freepascal.org/Enumerated_types |
_unix.244335 | I would like to find and replace text within many .procmailrc files, and using grep and sed. I would like to remove the following line (including the new line break at the beginning) from the .procmailrc files:* !^FROM_MAILERThe full contents of the file I want changed from::0* !^FROM_MAILER! [email protected]::0! [email protected] command I am running is:grep -lir '\n* !^FROM_MAILER' .procmailrc | xargs sed -i 's/\n* !^FROM_MAILER//g'But it is not replacing the *. In leaves the line in with just the * on it. If I escape the * as follows, that also does not work:grep -lir '\n\* !^FROM_MAILER' .procmailrc | xargs sed -i 's/\n\* !^FROM_MAILER//g'So I trying to find out how to do the find and replace to remove the entire line with the * in it. | How to find and replace using sed text containing a star * | text processing;sed | With sed alone:sed -i '/^* !^FROM_MAILER$/d' fileTo remove the whole line containing the exact string * !^FROM_MAILER, with nothing before and after that string. The d command deletes the line.Edit: If you want to do the replace in all files recusively, use the following:find /path -type f -exec sed -i '/^* !^FROM_MAILER$/d' {} + |
_codereview.118854 | I'm trying to implement Dijkstra algorithm in F# for finding the shortest path in a undirected tree using a heap.I've used the type PriorityQueue found here and the code can be found here.///////////////// preparing the data ////////////////////open Systemopen System.Collections.Genericopen System.IOopen MSDN.FSharplet stopWatch = System.Diagnostics.Stopwatch.StartNew()let x = File.ReadAllLines C:\Users\Fagui\Documents\GitHub\Learning Fsharp\Algo Stanford\PA5 - dijkstraData.txt// let x = File.ReadAllLines C:\Users\Fagui\Documents\GitHub\Learning Fsharp\Algo Stanford\PA5 - test4.txt// val x : string [] =// original format of each row is row_number (a1,b1) (a2,b2) ....(an,bn)let split (text:string)= text.Split [|'\t';' '|]let split_comma (text:string)= text.Split [|','|]let splitIntoKeyValue (A: 'T[]) = (A.[0], Seq.toList (Seq.tail A))let parseLine (line:string)= line |> split |> Array.filter (fun s -> not(s=)) // |> Array.map (fun s-> (int s)) |> splitIntoKeyValuelet y = x |> Array.map parseLinelet nodelist = y |> Array.map fst |> Array.map intlet N1 = Array.max nodelist // be careful if there is an image node with a bigger ID !!!let graphcore = // (int*int) list [] // nodes without outgoing edges will be missing (y |> Array.map snd |> Array.map (List.map split_comma) |> Array.map (List.map (fun (A:'T[]) -> (int A.[0],int A.[1]) )))let N2 = graphcore |> Array.map (List.map fst) |> Array.map List.max |> Array.max // node maxlet N=N2// non-optimized constructionlet graph = let g = Array.create (N+1) [] for i in 0..((Array.length nodelist)-1) do g.[nodelist.[i]] <- graphcore.[i] glet reversegraph = // (int*int) list [] let (rg:(int*int) list [])= Array.create (N+1) [] for i in 1..N do graph.[i] |> List.iter (fun (node,value) -> rg.[node] <- (i,value)::rg.[node] ) rg/////////////////// test /////////////////////let PQ1 = new PriorityQueue<int,int>()////PQ1.Enqueue 2 3//PQ1.Enqueue 3 4//PQ1.Enqueue 1 5//PQ1.Enqueue 1 6//printfn PriorityQueue %A PQ1////Console.ReadKey() |> ignore/////////////////// DJIKSTRA ///////////////////let limit = 1000000 // max distance limitlet S = 1 // Sourcelet V = [0..N] |> List.filter (fun s -> not(s=S));;let A = Array.create (N+1) limit // on ne se sert pas de A.[0]A.[S] <- 0let C = Array.create (N+1) -1 // stores the index of the element in X nearest to an element in V.let D = Array.create (N+1) limit // stores the value of Dijkstra criterionlet inX = Array.create (N+1) false // remembers if the node is in X (= has been processed)inX.[S]<-truelet PQ = new PriorityQueue<int,int>() // Key = distance to X ; Value = Node let init_loop () : unit = for node in V do PQ.Enqueue limit node for (node,dist_to_S) in graph.[S] do PQ.RemoveAt (PQ.IndexOf limit node) |> ignore PQ.Enqueue dist_to_S node |> ignore C.[node]<-S D.[node]<-dist_to_Sinit_loop()let PP () = for i in 0..(PQ.Count-1) do (printfn PQ %i %A i PQ.[i]);; // code to double check everything and DEBUGlet check() : unit= let V = [0..N] |> List.filter (fun s-> (inX.[s]=false)) let mutable temp = limit for k in V do temp <- limit let check_list = reversegraph.[k] |> List.filter (fun (n,d) -> inX.[n]=true) for (i,d_i) in check_list do let y = (A.[i]+d_i) if (y < temp) then temp <- y else () if not(PQ.Contains temp k) then printfn error at node %d with temp=%d k temp printfn check_list = %A check_list failwith stopping program else()let one_loop() : int = // take the first element from the queue let z = PQ.Dequeue() let W = z.Value let l = z.Key A.[W]<- l // maintain the heap // the Key must the Dijkstra criterion let update_list = graph.[W] update_list |> List.iter ( fun (node,dist) -> if (inX.[node]=true) then () else let x = l+dist if x > D.[node] then () else PQ.RemoveAt (PQ.IndexOf D.[node] node) |> ignore // updater le node PQ.Enqueue x node C.[node]<- W // prdcesseur D.[node]<- x // update la distance X if node = 196 then printfn D.[196] = %d x else () ) inX.[W] <- true // DEBUG check check() // returns W as a result of one_loop Wfor k in 1..N do // one_loop() printfn big loop k=%d k printfn k= %d W=%d k (one_loop())printfn %A A// printfn %i,%i,%i,%i,%i,%i,%i,%i,%i,%i A.[7] A.[37] A.[59] A.[82] A.[99] A.[115] A.[133] A.[165] A.[188] A.[197]PP()// stopWatch.Stop()printfn %f stopWatch.Elapsed.TotalMillisecondsConsole.ReadKey() |> ignore// my answer 2599,2610,2947,2052,2367,2399,2029,2442,2610,3068//// the right answer for A.[188] is 2505...// solution from Pythonlet AA =[|1000000;0; 2971; 2644; 3056; 2525; 2818; 2599; 1875; 745; 3205; 1551; 2906; 2394; 1803; 2942; 1837; 3111; 2284; 1044; 2351; 3630; 4028; 2650; 3653; 2249; 2150; 1222; 2090; 3540; 2303; 3455; 3004; 2551; 2656; 998; 2236; 2610; 3548; 1851; 4091; 2732; 2040; 3312; 2142; 3438; 2937; 2979; 2757; 2437; 3152; 2503; 2817; 2420; 3369; 2862; 2609; 2857; 3668; 2947; 2592; 1676; 2573; 2498; 2047; 826; 3393; 2535; 4636; 3650; 743; 1265; 1539; 3007; 4286; 2720; 3220; 2298; 2795; 2806; 982; 2976; 2052; 3997; 2656; 1193; 2461; 1608; 3046; 3261; 2018; 2786; 647; 3542; 3415; 2186; 2398; 4248; 3515; 2367; 2970; 3536; 2478; 1826; 2551; 3368; 2303; 2540; 1169; 3140; 2317; 2535; 1759; 1899; 508; 2399; 3513; 2597; 2176; 1090; 2328; 2818; 1306; 2805; 2057; 2618; 1694; 3285; 1203; 676; 1820; 1445; 2468; 2029; 1257; 1533; 2417; 3599; 2494; 4101; 546; 1889; 2616; 2141; 2359; 648; 2682; 3464; 2873; 3109; 2183; 4159; 1832; 2080; 1831; 2001; 3013; 2143; 1376; 1627; 2403; 4772; 2556; 2124; 1693; 2442; 3814; 2630; 2038; 2776; 1365; 3929; 1990; 2069; 3558; 1432; 2279; 3829; 2435; 3691; 3027; 2345; 3807; 2145; 2703; 2884; 3806; 1151; 2505; 2340; 2596; 4123; 1737; 3136; 1073; 1707; 2417; 3068; 1724; 815; 2060|]let B = [|for i in 0..200 do yield A.[i]-AA.[i]|];;let BB = [0..N] |> List.filter (fun s-> not(B.[s]=0))//val BB : int list = [10; 26; 95; 96; 101; 147; 157; 184; 188; 196]// index of nodes with differences// Array.partition (fun s->not(s=0)) B// [for i in BB do yield B.[i]] // donne un rsultat similaire...//I've done already some debugging, inserting a function check() (to be deleted when everything is fixed) which will check directly that the heap has always the right value, i.e., that at every moment, the key of any entry in the heap corresponds to the Dijkstra criterion.For the example graph found here in the same repository (click on the parent directory), dijkstraData.txt, the format is as follows:On every line, the first element is the ID# n of the node for that linethen we have tuples like (a,d) indicating that there is an edge from node n to node a, and that the distance is d. In this .txt example, edges are two way with same distance, so if you look at it carefully, for example there is an edge from node 1 to node 80 of length 982 and an edge from node 80 to node 1 of length 982.The solution for distances from node 0 (non-existent) to node I should be summarized in the following array:let AA =[|1000000;0; 2971; 2644; 3056; 2525; 2818; 2599; 1875; 745; 3205; 1551; 2906; 2394; 1803; 2942; 1837; 3111; 2284; 1044; 2351; 3630; 4028; 2650; 3653; 2249; 2150; 1222; 2090; 3540; 2303; 3455; 3004; 2551; 2656; 998; 2236; 2610; 3548; 1851; 4091; 2732; 2040; 3312; 2142; 3438; 2937; 2979; 2757; 2437; 3152; 2503; 2817; 2420; 3369; 2862; 2609; 2857; 3668; 2947; 2592; 1676; 2573; 2498; 2047; 826; 3393; 2535; 4636; 3650; 743; 1265; 1539; 3007; 4286; 2720; 3220; 2298; 2795; 2806; 982; 2976; 2052; 3997; 2656; 1193; 2461; 1608; 3046; 3261; 2018; 2786; 647; 3542; 3415; 2186; 2398; 4248; 3515; 2367; 2970; 3536; 2478; 1826; 2551; 3368; 2303; 2540; 1169; 3140; 2317; 2535; 1759; 1899; 508; 2399; 3513; 2597; 2176; 1090; 2328; 2818; 1306; 2805; 2057; 2618; 1694; 3285; 1203; 676; 1820; 1445; 2468; 2029; 1257; 1533; 2417; 3599; 2494; 4101; 546; 1889; 2616; 2141; 2359; 648; 2682; 3464; 2873; 3109; 2183; 4159; 1832; 2080; 1831; 2001; 3013; 2143; 1376; 1627; 2403; 4772; 2556; 2124; 1693; 2442; 3814; 2630; 2038; 2776; 1365; 3929; 1990; 2069; 3558; 1432; 2279; 3829; 2435; 3691; 3027; 2345; 3807; 2145; 2703; 2884; 3806; 1151; 2505; 2340; 2596; 4123; 1737; 3136; 1073; 1707; 2417; 3068; 1724; 815; 2060|]I got the results from another code in Python the solution differs at nodes [10; 26; 95; 96; 101; 147; 157; 184; 188; 196] only.I can't figure out if my algo is wrong as I got a 95% good answer. Maybe I've missed some cases, or I have a bug in the I/O part and don't play with the same graph.the data file:1 80,982 163,8164 170,2620 145,648 200,8021 173,2069 92,647 26,4122 140,546 11,1913 160,6461 27,7905 40,9047 150,2183 61,9146 159,7420 198,1724 114,508 104,6647 30,4612 99,2367 138,7896 169,8700 49,2437 125,2909 117,2597 55,6399 2 42,1689 127,9365 5,8026 170,9342 131,7005 172,1438 34,315 30,2455 26,2328 6,8847 11,1873 17,5409 157,8643 159,1397 142,7731 182,7908 93,8177 3 57,1239 101,3381 43,7313 41,7212 91,2483 31,3031 167,3877 106,6521 76,7729 122,9640 144,285 44,2165 6,9006 177,7097 119,7711 4 162,3924 70,5285 195,2490 72,6508 126,2625 121,7639 31,399 118,3626 90,9446 127,6808 135,7582 159,6133 106,4769 52,9267 190,7536 78,8058 75,7044 116,6771 49,619 107,4383 89,6363 54,313 5 200,4009 112,1522 25,3496 23,9432 64,7836 56,8262 120,1862 2,8026 90,8919 142,1195 81,2469 182,8806 17,2514 83,8407 146,5308 147,1087 51,22 6 141,8200 98,5594 66,6627 159,9500 143,3110 129,8525 118,8547 88,2039 83,4949 165,6473 162,6897 184,8021 123,13 176,3512 195,2233 42,7265 47,274 132,1514 2,8847 171,3722 3,9006 7 156,7027 187,9522 87,4976 121,8739 56,6616 10,2904 71,8206 53,179 146,4823 165,6019 125,5670 27,4888 63,9920 150,9031 84,4061 8 152,1257 189,2780 58,4708 26,8342 199,1918 31,3987 35,3160 71,5829 27,3483 69,8815 130,55 168,2076 122,5338 73,4528 28,9996 17,3535 40,3193 72,7308 24,8434 87,2833 25,3949 175,1022 177,8508 9 152,1087 115,7827 17,7002 72,794 150,4539 190,3613 95,9480 36,5284 166,8702 63,1753 199,70 131,700 76,9340 70,2 139,8701 140,4163 180,5995 10 57,9988 78,3771 62,4816 137,5273 7,2904 187,4786 184,3207 96,807 31,1184 88,2539 135,4650 168,9495 164,3866 11,8988 116,1493 51,5578 171,2029 11 1,1913 185,2045 77,815 22,8425 181,8448 47,8727 81,7299 150,4802 178,1696 28,2275 183,594 131,833 157,8497 25,5057 59,3203 10,8988 2,1873 134,294 83,4211 124,6180 12 78,5753 17,4602 62,5676 16,8068 60,5933 67,371 71,6734 53,7001 72,3626 34,6690 59,761 18,1520 128,7542 38,6699 57,9416 13 144,9987 59,9801 97,7026 50,758 43,5400 163,3870 178,4194 151,9629 45,1794 105,6821 29,2784 172,2070 57,6850 77,8638 135,861 14 149,4352 187,4874 26,3841 128,9662 155,4446 118,373 123,2733 106,7912 169,4333 53,9197 161,4275 126,9602 73,4106 160,7860 131,358 141,4477 119,960 43,3199 47,7898 175,6718 177,6741 60,2464 127,5682 31,1945 143,5848 94,3551 82,3283 15 42,1789 22,3571 25,7019 163,818 56,2334 100,809 143,1041 107,4589 190,6854 169,7485 94,9606 34,7961 54,8983 157,2136 24,8040 16 200,2848 198,2223 92,2896 18,8663 27,8673 75,4116 150,1680 36,1555 41,2747 90,4558 68,5894 12,8068 42,2596 185,6280 171,3482 109,1469 127,9807 178,1714 35,839 56,9828 134,5203 55,6680 110,4252 17 26,1275 45,5114 142,8016 83,4615 140,6440 8,3535 69,3610 153,8545 9,7002 12,4602 173,7312 114,8915 108,1942 54,3115 66,6176 190,7000 70,3899 5,2514 178,7464 166,4762 2,5409 146,5362 117,6266 18 57,4216 80,5252 86,7517 62,1926 120,44 173,7256 133,2702 148,589 167,7625 16,8663 170,4989 118,6388 142,332 95,6122 99,5717 154,453 150,5150 149,2664 146,9000 171,4403 111,785 12,1520 19 33,6938 77,7013 187,107 109,8397 88,2002 95,8691 132,3157 195,5038 154,4320 23,8560 152,9751 185,5896 119,7406 160,3997 80,62 20 66,2667 173,2676 43,8105 135,6434 33,6387 74,6183 106,8785 75,2484 130,9048 56,7194 50,9507 88,3014 124,392 61,2580 90,7372 92,1704 87,2639 154,2398 41,4203 85,1435 169,5990 166,6086 28,2234 145,8099 21 23,5183 40,2199 31,2556 71,4986 165,2151 193,494 154,1845 111,3060 85,2880 101,2775 182,2447 80,9884 87,2681 102,6643 131,3748 22 92,5592 64,4257 11,8425 24,594 15,3571 42,3783 41,1374 114,9960 144,9362 146,3620 71,3243 143,8603 131,6075 192,4606 108,9656 168,4356 177,8713 132,1560 23 143,7543 161,6863 45,8074 165,208 21,5183 118,5079 40,8336 27,9054 112,3201 135,4560 167,2133 188,4236 166,8077 195,3179 48,4485 137,7591 99,6485 5,9432 71,3316 96,2431 125,922 19,8560 24 141,6862 197,9337 66,5879 59,6941 70,4670 55,4106 103,8083 61,7906 48,7959 151,784 177,393 102,8731 199,2838 73,3509 8,8434 187,9327 22,594 150,5669 164,7312 157,9540 15,8040 25 115,9233 197,3875 185,3573 72,2332 104,4899 137,5378 8,3949 5,3496 77,2729 136,9251 143,108 83,9569 15,7019 48,3214 155,3242 153,2477 129,3005 132,219 11,5057 37,1591 68,4188 26 14,3841 8,8342 1,4122 147,5759 113,5553 157,7 65,9434 116,4221 66,2747 138,7027 145,6697 130,5706 60,701 127,9896 136,7200 17,1275 120,5788 175,6165 70,9252 95,36 106,6940 2,2328 96,425 51,9329 183,4842 196,6754 27 23,9054 78,3066 8,3483 1,7905 152,2124 108,9929 63,3896 151,5915 111,3101 34,8912 182,6234 133,7749 16,8673 192,5344 114,714 168,1578 175,210 138,5918 7,4888 122,84 28 8,9996 188,3816 116,2638 132,5604 20,2234 178,3642 76,3705 122,9165 184,4164 198,366 161,9217 160,9059 56,5375 120,8874 11,2275 111,4495 193,9441 157,6880 48,2803 29 78,8190 144,6452 114,9478 156,5083 62,9692 121,4537 184,9797 109,6873 153,5446 67,3449 172,5830 111,1005 100,1642 148,3252 13,2784 30 78,5469 119,7372 144,1616 130,1356 59,4458 40,9818 79,503 43,6233 148,4760 42,263 1,4612 57,5668 185,3846 101,6979 94,6976 106,7819 2,2455 71,9294 31 4,399 8,3987 50,2598 75,7688 47,7840 99,8583 190,5055 112,5231 114,7617 118,6949 180,3598 21,2556 199,5564 14,1945 3,3031 35,9855 10,1184 146,2837 51,3739 83,6588 46,5964 32 136,3823 77,1689 92,3395 121,1615 85,7494 173,9631 177,6902 88,8129 36,7329 116,6065 61,3332 68,7352 119,1914 82,8571 70,9909 33 144,4841 173,5949 170,3648 113,652 110,1986 82,3577 61,1837 97,5671 55,1252 19,6938 48,914 74,3642 125,67 89,3089 176,3258 20,6387 138,6960 153,6574 171,3913 34 86,6435 156,8641 72,2540 181,5267 27,8912 58,8824 179,8528 62,9864 70,2348 57,5471 53,236 168,3923 101,3383 142,7791 55,7174 2,315 147,9758 15,7961 199,8196 12,6690 35 57,3693 8,3160 144,3087 114,490 65,8910 178,5774 172,992 16,839 118,8640 41,6749 31,9855 39,853 64,6071 166,2816 184,7437 49,3098 182,7369 110,4985 93,8775 36 80,2032 130,7589 123,6226 16,1555 150,116 88,7759 100,8612 9,5284 198,6280 49,953 143,5111 42,4917 134,979 159,6043 32,7329 67,2380 148,9550 48,7266 37 197,9188 119,9313 187,4105 191,3573 109,2135 75,751 200,7541 139,8208 155,609 142,6433 25,1591 132,821 156,7714 107,1144 99,7757 38 91,7087 88,502 132,6092 126,5441 147,8391 12,6699 130,5227 146,4400 108,8712 100,1369 134,4730 87,2975 99,6169 183,5213 109,4945 39 200,4319 98,3993 130,2414 40,2489 196,9267 133,8145 82,3528 44,9175 42,5464 127,6103 93,6132 180,9506 192,7454 119,1376 115,983 81,7400 35,853 40 23,8336 1,9047 120,7760 101,2885 21,2199 144,7772 96,5739 136,4658 184,4306 189,4263 30,9818 39,2489 108,8883 8,3193 80,9657 181,2338 162,3056 71,2826 68,5800 41 200,2622 78,63 66,4654 198,7215 59,284 75,7333 22,1374 181,5235 16,2747 154,901 150,7278 3,7212 103,7917 163,5256 20,4203 91,7776 35,6749 147,1858 165,3741 107,8116 42 160,2382 156,6539 6,7265 15,1789 61,8096 164,347 194,6498 172,5383 104,2726 124,3496 161,4792 159,5951 117,7074 2,1689 186,9391 62,3249 79,9404 39,5464 187,3075 22,3783 30,263 16,2596 137,4572 163,1278 60,6663 70,9396 36,4917 73,9154 43 200,8943 159,9621 97,3906 20,8105 164,6849 13,5400 3,7313 133,8488 108,8964 30,6233 79,5052 131,8231 167,8120 14,3199 130,2685 138,7965 177,9544 143,1171 65,5805 118,8008 140,4482 93,8479 44 197,4900 144,2276 198,2619 39,9175 87,7875 191,8130 166,6953 170,6940 163,18 79,9988 145,2888 173,5518 57,9979 82,3134 54,4113 3,2165 45 57,4630 23,8074 112,9496 130,4994 86,8207 17,5114 120,5279 169,662 162,3436 170,8060 118,5918 124,3290 110,8317 13,1794 167,1163 46 57,2413 152,9550 86,7512 123,132 138,2860 195,8206 176,9923 119,2687 54,9328 196,9632 73,5109 31,5964 173,2969 193,199 80,7968 194,2429 47 57,9584 114,9480 145,9483 190,5892 182,8382 31,7840 129,9533 142,5297 58,1229 146,2959 6,274 14,7898 189,5939 11,8727 76,2138 70,2236 48 152,5835 23,4485 33,914 24,7959 25,3214 135,8869 53,3578 162,201 28,2803 141,7941 36,7266 85,2792 86,3588 124,2593 130,7921 49 160,8648 154,2962 109,7520 36,953 178,9747 192,3113 112,2935 35,3098 71,3441 4,619 96,9901 171,9736 163,4688 1,2437 133,5167 117,2896 105,9278 50 152,5767 112,6454 185,3968 77,5220 20,9507 165,2667 98,990 187,2485 198,3798 13,758 128,2987 189,7031 52,9931 127,3622 31,2598 179,2502 191,5026 153,4905 51 80,7589 72,4882 137,1096 138,8755 109,662 67,4225 181,158 132,6107 189,8899 159,3017 5,22 10,5578 31,3739 120,5675 26,9329 176,1625 52 4,9267 115,4973 159,7816 185,8925 188,7805 97,9063 50,9931 137,9846 91,424 150,634 56,2416 107,3647 68,7601 168,1134 179,3504 53 14,9197 114,7352 156,4662 62,153 85,1227 177,9852 34,236 7,179 12,7001 48,3578 71,9285 86,7353 150,662 183,5304 125,8054 54,8361 54 197,2223 66,2906 136,1794 188,4883 17,3115 109,7832 44,4113 182,438 15,8983 200,4899 112,2279 169,2296 4,313 53,8361 138,6261 46,9328 55 33,1252 188,5181 101,6050 24,4106 169,7795 149,3088 34,7174 193,8583 1,6399 145,3342 105,8477 166,3686 121,44 16,6680 82,3547 56 101,3516 20,7194 179,5284 127,3031 5,8262 161,9811 16,9828 15,2334 52,2416 7,6616 77,7923 182,7267 88,3375 61,1315 117,1934 28,5375 124,552 100,361 57 18,4216 94,558 186,8815 3,1239 85,6678 45,4630 46,2413 35,3693 84,6563 185,9772 67,8012 47,9584 155,893 64,810 10,9988 80,8722 160,2058 59,2689 79,2330 30,5668 184,7592 44,9979 162,6483 116,656 34,5471 106,4868 131,6342 183,9093 13,6850 12,9416 58 152,5877 98,3677 8,4708 130,7020 59,5735 121,8818 47,1229 102,6906 150,4857 90,7141 86,5989 175,3675 79,2365 34,8824 186,8993 125,1050 74,7934 147,2267 193,6166 59 86,1293 147,2651 149,2405 141,9126 112,4585 58,5735 74,4470 24,6941 199,8958 57,2689 13,9801 162,391 30,4458 180,2435 41,284 72,7154 101,1804 87,4628 168,4170 99,671 70,8055 11,3203 12,761 60 200,3269 98,2073 26,701 185,6670 120,2231 14,2464 127,1402 12,5933 42,6663 189,4415 107,52 146,2317 112,2570 154,6667 177,5345 172,2781 61 1,9146 159,49 33,1837 42,8096 20,2580 24,7906 87,9053 163,448 190,9775 155,5301 173,4803 115,3324 196,5577 171,6888 32,3332 56,1315 131,6924 195,8928 62 97,9163 53,153 120,3851 18,1926 154,3238 12,5676 88,9007 152,7404 29,9692 161,4144 10,4816 105,2736 42,3249 107,5324 115,1913 121,4145 116,7419 34,9864 193,6610 103,8383 63 141,5607 77,5873 27,3896 169,5160 95,5264 69,2323 125,1315 158,5709 102,5806 9,1753 103,9314 71,3007 131,5257 92,9006 96,5638 7,9920 64 57,810 98,3909 97,2201 22,4257 120,2385 177,7660 83,2716 81,9744 111,2663 145,2685 130,2493 148,6419 106,256 141,158 86,414 87,9403 121,771 102,4635 5,7836 67,2090 35,6071 131,4631 182,4701 110,6711 65 152,3595 66,6930 26,9434 97,6170 123,9599 175,7920 155,5533 102,1652 77,4069 198,3575 81,3054 199,11 95,6605 35,8910 43,5805 71,439 134,9956 74,6617 165,3705 140,5376 66 80,2902 68,8312 142,777 156,2965 41,4654 6,6627 84,7710 102,3328 65,6930 54,2906 24,5879 112,2271 93,5873 94,3424 20,2667 26,2747 130,5826 17,6176 69,824 89,3012 67 57,8012 102,5417 175,5048 153,6204 12,371 137,1414 133,3802 64,2090 98,980 200,475 171,1394 36,2380 29,3449 124,1880 51,4225 195,5737 100,6216 103,1468 68 141,3540 197,8223 78,7924 66,8312 144,2277 174,7082 16,5894 163,4920 146,3895 52,7601 140,9624 40,5800 25,4188 32,7352 186,2528 69 8,8815 198,6284 17,3610 156,9959 75,3354 168,2357 102,1172 190,8022 139,9030 161,6171 96,4815 189,5215 66,824 94,1427 63,2323 70 4,5285 24,4670 148,7231 26,9252 17,3899 59,8055 47,2236 42,9396 175,3256 149,2366 92,96 153,6532 178,3394 168,1295 156,4830 34,2348 9,2 124,9089 32,9909 183,5332 71 8,5829 22,3243 138,1229 81,1711 170,1539 49,3441 23,3316 134,7485 12,6734 30,9294 21,4986 142,6038 65,439 7,8206 40,2826 145,6127 53,9285 63,3007 186,7143 171,6702 72 4,6508 78,5839 119,6215 114,8350 9,794 8,7308 113,8782 102,3377 34,2540 25,2332 59,7154 172,3153 89,4836 178,5128 51,4882 120,2287 174,2019 153,541 96,859 146,4264 171,8573 157,604 12,3626 73 14,4106 8,4528 159,4969 97,6534 77,2438 24,3509 174,2581 150,8061 139,4428 149,5233 42,9154 90,5133 78,212 194,8521 172,2239 46,5109 74 159,8960 33,3642 59,4470 20,6183 99,7031 179,1223 93,5576 164,8627 58,7934 65,6617 110,6731 108,8251 165,2602 121,1468 182,1873 176,8129 75 115,9140 141,9237 80,2187 86,259 20,2484 92,6095 97,1883 41,7333 87,3244 69,3354 120,6892 131,5902 31,7688 108,5943 4,7044 16,4116 191,1403 81,2609 37,751 76 115,7291 185,3674 181,3275 47,2138 143,1079 28,3705 125,1865 178,8433 3,7729 114,9690 100,1793 200,4623 199,6878 138,5683 141,1969 126,9595 9,9340 83,4424 89,6942 77 112,3500 160,105 189,5702 191,5135 124,8896 198,5081 19,7013 73,2438 63,5873 129,2337 11,815 133,2481 192,561 32,1689 50,5220 87,7040 25,2729 65,4069 106,9161 153,4483 56,7923 172,4771 13,8638 78 10,3771 68,7924 12,5753 30,5469 158,6367 122,6207 27,3066 116,2732 41,63 72,5839 161,6310 4,8058 104,1377 83,3955 29,8190 98,6603 154,8423 137,1910 135,6919 73,212 145,7244 79 141,7918 101,3205 165,3768 96,3059 119,4117 152,6519 57,2330 42,9404 166,8726 161,8395 30,503 89,5169 134,5792 117,9043 129,7314 43,5052 109,9677 58,2365 44,9988 167,820 193,7737 194,5784 80 36,2032 84,4645 1,982 115,1417 151,6728 112,5208 51,7589 152,9606 113,917 18,5252 121,2257 75,2187 57,8722 133,7217 179,7729 119,108 66,2902 40,9657 97,7213 172,7715 89,7224 19,62 46,7968 21,9884 81 115,2608 197,5540 97,8866 101,4493 64,9744 11,7299 71,1711 109,2519 136,1409 39,7400 75,2609 142,424 141,4032 183,3061 184,4485 95,7627 5,2469 143,9810 65,3054 89,6124 82 33,3577 130,3349 156,4691 39,3528 173,591 177,7882 44,3134 116,8491 132,4162 135,519 131,3457 128,6834 32,8571 55,3547 14,3283 83 78,3955 6,4949 185,9306 17,4615 64,2716 25,9569 149,6823 5,8407 167,8200 117,8516 165,1555 151,162 31,6588 76,4424 11,4211 84 57,6563 80,4645 119,6417 66,7710 198,5999 136,4270 86,195 104,5330 154,5421 137,4367 95,3812 159,8763 170,2436 107,2954 85,9888 134,9312 7,4061 85 57,6678 160,3613 156,6669 168,6193 136,6221 180,5525 32,7494 118,1102 192,544 129,517 93,2349 87,7478 189,1147 53,1227 20,1435 167,8110 133,836 84,9888 132,3873 128,4644 110,6060 21,2880 48,2792 86 115,4291 197,9714 144,8808 59,1293 126,937 189,1115 18,7517 45,8207 46,7512 177,7010 180,4604 75,259 157,4447 84,195 34,6435 120,5230 64,414 184,801 58,5989 142,1663 53,7353 117,4220 48,3588 87 160,8712 119,518 75,3244 94,9647 59,4628 61,9053 44,7875 168,9716 64,9403 164,3629 20,2639 8,2833 77,7040 7,4976 159,19 85,7478 191,6921 88,8011 167,1022 158,4081 110,1219 21,2681 38,2975 88 6,2039 62,9007 20,3014 113,7322 136,9026 32,8129 38,502 151,2295 150,6770 183,5547 36,7759 87,8011 94,4629 115,6611 19,2002 161,1726 56,3375 10,2539 125,5012 89,6267 89 33,3089 72,4836 123,1723 79,5169 174,858 76,6942 4,6363 199,2446 105,2736 66,3012 180,6612 80,7224 163,4055 88,6267 81,6124 90 152,4427 4,9446 115,1117 119,928 185,7284 20,7372 16,4558 108,9076 179,3149 139,7846 58,7141 5,8919 73,5133 144,6223 174,6914 91 160,383 181,5060 174,3418 113,4626 95,1806 3,2483 192,6625 52,424 115,1105 137,4129 142,9164 41,7776 158,5553 38,7087 200,1988 92 1,647 130,4320 108,1844 134,610 194,426 177,3182 75,6095 20,1704 94,6085 128,556 22,5592 16,2896 186,7980 32,3395 139,6763 121,3819 138,8080 70,96 63,9006 93 66,5873 39,6132 181,4071 154,4073 85,2349 106,7477 74,5576 150,9213 98,6617 147,7807 43,8479 152,6543 35,8775 167,5670 2,8177 94 57,558 66,3424 92,6085 120,2733 87,9647 30,6976 191,8318 139,7116 109,1299 88,4629 170,9318 69,1427 14,3551 115,3350 171,9959 15,9606 95 119,8126 112,555 120,1104 18,6122 91,1806 173,4092 196,231 26,36 147,1278 19,8691 125,2917 9,9480 63,5264 81,7627 84,3812 65,6605 105,6026 96 40,5739 79,3059 104,9639 113,712 162,3737 155,1251 10,807 49,9901 151,5643 23,2431 72,859 26,425 69,4815 143,9274 183,5939 63,5638 147,6736 193,8831 97 33,5671 185,7065 52,9063 64,2201 188,4695 192,6411 43,3906 73,6534 13,7026 112,7969 81,8866 80,7213 62,9163 65,6170 140,6527 75,1883 137,4667 98 115,5825 131,4614 64,3909 155,5515 139,1235 39,3993 102,8330 60,2073 200,2690 166,2364 78,6603 162,6139 58,3677 117,9545 6,5594 144,7198 50,990 150,2093 143,4300 67,980 93,6617 99 104,9140 18,5717 174,5675 157,6818 132,6234 182,2897 151,4990 183,3577 59,671 133,2090 23,6485 153,4560 31,8583 74,7031 1,2367 127,1408 37,7757 193,4566 194,5832 38,6169 100 159,6567 137,7178 163,9709 190,6674 36,8612 142,2994 76,1793 67,6216 29,1642 56,361 144,6605 128,2584 153,9522 145,5512 15,809 38,1369 101 188,8531 40,2885 157,1393 171,4083 55,6050 144,3619 3,3381 113,5024 81,4493 163,6033 56,3516 129,8821 184,9591 59,1804 79,3205 30,6979 138,2902 143,4042 34,3383 21,2775 102 98,8330 66,3328 144,7884 72,3377 24,8731 181,3585 137,6814 172,6572 58,6906 64,4635 117,2689 177,4462 67,5417 183,9634 69,1172 65,1652 178,1334 161,8230 63,5806 140,6370 21,6643 103 200,6851 123,8756 24,8083 41,7917 191,9683 63,9314 112,7409 110,491 131,2920 196,696 186,9654 62,8383 113,5248 67,1468 114,1318 104 141,8162 78,1377 42,2726 123,9213 1,6647 126,8615 200,7083 197,4174 84,5330 192,4219 142,6236 99,9140 96,9639 25,4899 172,561 179,8827 169,3712 105 185,1033 62,2736 113,3388 116,7899 89,2736 164,4661 183,7722 55,8477 190,2518 180,341 95,6026 119,9930 120,9333 13,6821 49,9278 106 14,7912 4,4769 115,9598 141,674 112,4854 20,8785 64,256 181,5332 190,3305 3,6521 30,7819 93,7477 26,6940 77,9161 57,4868 111,6460 107 114,2032 123,4581 62,5324 187,2610 60,52 116,9864 84,2954 182,8313 37,1144 169,668 52,3647 4,4383 41,8116 146,7862 112,7448 15,4589 176,6806 108 200,9976 185,8699 17,1942 40,8883 156,7039 92,1844 75,5943 22,9656 43,8964 27,9929 174,5669 90,9076 145,521 143,972 113,4342 74,8251 126,525 38,8712 109 152,2743 136,8658 81,2519 169,382 51,662 49,7520 129,2464 79,9677 54,7832 37,2135 94,1299 185,6644 29,6873 19,8397 16,1469 38,4945 110 197,751 33,1986 145,6099 118,9403 74,6731 126,1073 103,491 35,4985 137,8848 165,4097 85,6060 87,1219 45,8317 64,6711 16,4252 111 197,4083 144,5456 114,2027 64,2663 27,3101 191,5723 162,8771 152,1940 28,4495 106,6460 29,1005 130,9137 133,6767 18,785 160,9702 21,3060 112 23,3201 141,130 80,5208 181,2524 95,555 77,3500 183,9037 164,1492 155,7915 106,4854 50,6454 133,9083 5,1522 45,9496 173,7338 66,2271 59,4585 97,7969 60,2570 31,5231 149,8736 49,2935 158,383 128,7645 107,7448 103,7409 54,2279 196,5663 113 80,917 33,652 26,5553 72,8782 101,5024 108,4342 132,5383 116,8036 184,4999 88,7322 105,3388 187,6332 190,697 136,1984 96,712 91,4626 103,5248 114 29,9478 180,8490 189,3102 111,2027 192,6813 141,6388 72,8350 115,3112 152,9627 53,7352 129,168 107,2032 1,508 47,9480 35,490 17,8915 22,9960 27,714 31,7617 76,9690 117,7876 193,4000 103,1318 194,949 115 152,4383 176,8236 75,9140 25,9233 9,7827 98,5825 52,4973 146,9828 81,2608 128,9072 86,4291 76,7291 90,1117 106,9598 144,3825 80,1417 114,3112 62,1913 39,983 91,1105 88,6611 129,7465 166,3001 61,3324 117,1399 94,3350 116 78,2732 26,4221 113,8036 179,8099 32,6065 105,7899 62,7419 107,9864 82,8491 186,8639 176,4512 192,5906 57,656 4,6771 28,2638 10,1493 117 98,9545 198,3936 42,7074 79,9043 102,2689 56,1934 114,7876 83,8516 86,4220 196,3366 1,2597 49,2896 138,7762 17,6266 115,1399 118 14,373 23,5079 4,3626 6,8547 123,2088 181,8129 18,6388 85,1102 31,6949 166,3979 35,8640 43,8008 45,5918 177,8279 110,9403 128,6289 119 80,108 154,741 130,730 84,6417 72,6215 30,7372 170,275 168,1890 157,9158 90,928 121,6261 37,9313 95,8126 14,960 87,518 79,4117 39,1376 163,5189 169,3511 195,617 3,7711 32,1914 19,7406 46,2687 196,2824 105,9930 120 40,7760 62,3851 72,2287 94,2733 86,5230 95,1104 164,5926 26,5788 18,44 155,6822 60,2231 185,556 45,5279 179,3327 159,5811 75,6892 64,2385 5,1862 178,8906 28,8874 51,5675 105,9333 121 4,7639 80,2257 197,6502 119,6261 136,1320 156,195 29,4537 7,8739 58,8818 32,1615 168,7186 62,4145 92,3819 173,2976 64,771 175,8821 191,8606 162,1977 132,3867 74,1468 165,7147 148,8115 55,44 122 78,6207 8,5338 174,8205 168,1574 162,3518 166,6712 135,6345 28,9165 192,1494 128,7247 189,2017 3,9640 148,3230 27,84 179,7377 123 14,2733 198,3493 6,13 104,9213 107,4581 89,1723 118,2088 128,1602 155,3251 46,132 36,6226 184,2832 103,8756 65,9599 124,6490 145,8804 193,7460 124 141,168 159,6580 42,3496 123,6490 77,8896 20,392 67,1880 158,1870 147,9014 165,9797 136,7388 56,552 11,6180 70,9089 45,3290 48,2593 125 33,67 174,9048 95,2917 53,8054 1,2909 63,1315 76,1865 88,5012 58,1050 23,922 173,2615 188,230 172,8515 196,4519 138,9932 183,9920 7,5670 126 14,9602 4,2625 159,2980 86,937 181,8920 104,8615 179,7436 191,3989 161,4512 108,525 155,307 110,1073 134,5002 38,5441 76,9595 180,7176 127 4,6808 160,7534 26,9896 39,6103 50,3622 137,4069 60,1402 156,6372 2,9365 16,9807 56,3031 139,2526 14,5682 99,1408 167,3756 135,1752 161,6643 146,8151 128 14,9662 115,9072 123,1602 92,556 50,2987 190,2968 118,6289 157,6815 132,2789 184,6339 198,1860 112,7645 122,7247 85,4644 82,6834 100,2584 196,1760 12,7542 129 6,8525 114,168 101,8821 77,2337 79,7314 47,9533 85,517 175,7121 184,5623 109,2464 143,8021 167,5370 25,3005 159,6895 115,7465 130 119,730 8,55 26,5706 45,4994 36,7589 30,1356 184,8488 178,615 92,4320 58,7020 82,3349 174,4481 66,5826 39,2414 194,9429 156,2264 20,9048 64,2493 43,2685 137,5926 190,3429 147,9251 111,9137 48,7921 38,5227 131 14,358 98,4614 159,4355 75,5902 22,6075 43,8231 163,8625 11,833 57,6342 61,6924 82,3457 64,4631 134,6293 167,6269 2,7005 63,5257 9,700 103,2920 21,3748 132 198,2393 113,5383 99,6234 138,5667 28,5604 19,3157 38,6092 85,3873 82,4162 25,219 182,6433 22,1560 147,2847 6,1514 121,3867 128,2789 51,6107 37,821 133 80,7217 112,9083 136,3739 77,2481 39,8145 43,8488 18,2702 27,7749 168,899 99,2090 190,9958 139,4719 182,8241 191,4296 85,836 153,8437 67,3802 49,5167 111,6767 134 197,6225 198,4071 92,610 79,5792 175,4489 36,979 131,6293 71,7485 146,9556 158,119 11,294 65,9956 135,276 16,5203 84,9312 126,5002 38,4730 135 23,4560 4,7582 20,6434 174,6977 150,9732 190,1431 173,5664 144,6396 127,1752 122,6345 48,8869 82,519 158,8348 184,7629 78,6919 10,4650 134,276 194,5726 13,861 136 161,3866 195,4279 32,3823 84,4270 168,9519 54,1794 170,1529 197,9068 121,1320 194,2496 109,8658 199,7783 133,3739 145,1769 179,6711 26,7200 40,4658 174,5711 85,6221 113,1984 25,9251 184,6682 81,1409 88,9026 178,2752 124,7388 137 188,9117 100,7178 42,4572 51,1096 52,9846 97,4667 25,5378 102,6814 130,5926 84,4367 141,7872 23,7591 127,4069 157,5286 78,1910 91,4129 155,5736 67,1414 10,5273 110,8848 138 200,678 160,9902 26,7027 101,2902 51,8755 132,5667 43,7965 92,8080 1,7896 173,8555 33,6960 71,1229 46,2860 27,5918 188,892 169,7498 178,6589 125,9932 76,5683 117,7762 54,6261 140,5446 139 197,1386 98,1235 92,6763 181,5456 176,8186 182,2354 133,4719 158,3451 196,3988 73,4428 90,7846 155,2100 194,6966 69,9030 94,7116 127,2526 162,4510 9,8701 37,8208 140 1,546 17,6440 97,6527 158,4029 151,5289 68,9624 138,5446 43,4482 169,2230 9,4163 155,5001 188,6223 102,6370 166,9829 65,5376 141 154,3188 68,3540 106,674 79,7918 104,8162 24,6862 63,5607 6,8200 75,9237 150,2634 124,168 14,4477 112,130 164,6499 198,2621 114,6388 185,6820 59,9126 64,158 137,7872 81,4032 76,1969 48,7941 142 66,777 17,8016 104,6236 18,332 47,5297 81,424 91,9164 150,2598 5,1195 34,7791 155,6613 169,7506 86,1663 100,2994 190,8070 2,7731 71,6038 145,5378 37,6433 143 23,7543 6,3110 22,8603 108,972 25,108 81,9810 43,1171 186,8430 14,5848 129,8021 101,4042 76,1079 98,4300 155,2442 177,3884 36,5111 153,9940 96,9274 15,1041 176,5062 144 115,3825 173,8693 29,6452 98,7198 68,2277 195,652 102,7884 30,1616 111,5456 33,4841 13,9987 44,2276 86,8808 148,3617 35,3087 40,7772 101,3619 22,9362 184,5222 135,6396 90,6223 3,285 100,6605 145 200,2753 1,648 136,1769 26,6697 64,2685 174,7252 47,9483 108,521 44,2888 123,8804 71,6127 142,5378 20,8099 78,7244 110,6099 100,5512 55,3342 146 115,9828 22,3620 47,2959 60,2317 5,5308 127,8151 7,4823 134,9556 18,9000 31,2837 17,5362 68,3895 72,4264 188,5715 167,52 107,7862 38,4400 147 26,5759 59,2651 163,7221 95,1278 132,2847 124,9014 5,1087 34,9758 96,6736 38,8391 41,1858 167,5546 130,9251 149,6379 58,2267 93,7807 148 160,3995 144,3617 185,2814 64,6419 18,589 30,4760 173,6725 179,6374 70,7231 155,6603 122,3230 192,4834 36,9550 121,8115 29,3252 149 14,4352 59,2405 188,1003 163,9897 70,2366 83,6823 187,9580 174,2824 73,5233 112,8736 55,3088 18,2664 176,2255 190,3755 180,3407 147,6379 150 141,2634 1,2183 16,1680 41,7278 36,116 135,9732 11,4802 98,2093 58,4857 142,2598 73,8061 9,4539 18,5150 24,5669 52,634 190,5243 88,6770 53,662 7,9031 93,9213 151 80,6728 156,6169 24,784 27,5915 174,1846 168,9216 99,4990 88,2295 178,5979 96,5643 83,162 13,9629 140,5289 189,9732 163,3624 152 161,6939 58,5877 48,5835 9,1087 8,1257 46,9550 189,8140 199,2697 109,2743 65,3595 186,2075 115,4383 50,5767 193,5444 90,4427 80,9606 114,9627 62,7404 79,6519 27,2124 111,1940 19,9751 93,6543 153 17,8545 99,4560 70,6532 164,8748 29,5446 25,2477 72,541 143,9940 173,7613 77,4483 50,4905 165,897 133,8437 33,6574 67,6204 100,9522 154 141,3188 119,741 198,5078 156,8062 62,3238 20,2398 18,453 49,2962 187,1808 168,6317 200,229 185,1448 93,4073 78,8423 84,5421 41,901 60,6667 170,5971 19,4320 21,1845 199,5786 155 57,893 14,4446 98,5515 112,7915 123,3251 120,6822 25,3242 139,2100 143,2442 65,5533 142,6613 96,1251 137,5736 148,6603 61,5301 126,307 37,609 140,5001 194,6768 156 66,2965 42,6539 82,4691 53,4662 151,6169 7,7027 85,6669 29,5083 154,8062 130,2264 108,7039 34,8641 121,195 175,2205 69,9959 70,4830 127,6372 37,7714 157 119,9158 26,7 86,4447 101,1393 187,7184 137,5286 99,6818 11,8497 2,8643 158,1881 128,6815 175,1597 72,604 24,9540 28,6880 15,2136 158 78,6367 187,6714 91,5553 139,3451 169,1709 135,8348 63,5709 195,4912 140,4029 157,1881 124,1870 181,969 112,383 87,4081 134,119 159 4,6133 160,4243 61,49 180,5757 6,9500 194,9391 43,9621 100,6567 126,2980 73,4969 131,4355 124,6580 1,7420 52,7816 74,8960 198,8330 42,5951 120,5811 87,19 36,6043 84,8763 129,6895 2,1397 51,3017 193,3786 160 14,7860 138,9902 127,7534 49,8648 85,3613 189,1530 57,2058 159,4243 183,9293 148,3995 87,8712 180,624 179,2542 91,383 42,2382 1,6461 77,105 28,9059 111,9702 19,3997 161 152,6939 14,4275 23,6863 78,6310 136,3866 42,4792 62,4144 79,8395 127,6643 69,6171 126,4512 56,9811 196,9729 102,8230 88,1726 28,9217 162 4,3924 98,6139 6,6897 59,391 194,1483 122,3518 57,6483 121,1977 179,9718 139,4510 199,7749 40,3056 111,8771 96,3737 45,3436 186,6114 48,201 163 1,8164 101,6033 41,5256 173,5799 15,818 13,3870 149,9897 131,8625 181,5593 119,5189 61,448 42,1278 68,4920 100,9709 147,7221 44,18 49,4688 192,2762 151,3624 89,4055 164 141,6499 112,1492 42,347 120,5926 43,6849 87,3629 184,9774 170,328 153,8748 10,3866 172,9550 74,8627 195,9730 105,4661 24,7312 183,615 176,8681 165 23,208 6,6473 79,3768 187,1291 50,2667 153,897 166,4221 74,2602 21,2151 121,7147 124,9797 83,1555 65,3705 7,6019 41,3741 110,4097 166 23,8077 98,2364 79,8726 173,6917 44,6953 167,7080 118,3979 165,4221 168,4399 17,4762 9,8702 122,6712 20,6086 169,5530 115,3001 35,2816 55,3686 140,9829 167 23,2133 188,6549 187,9538 43,8120 18,7625 127,3756 180,6183 87,1022 79,820 83,8200 3,3877 129,5370 85,8110 193,8116 166,7080 131,6269 146,52 147,5546 45,1163 199,2001 93,5670 168 119,1890 8,2076 136,9519 87,9716 154,6317 121,7186 133,899 122,1574 85,6193 173,3859 59,4170 27,1578 69,2357 151,9216 22,4356 70,1295 34,3923 166,4399 10,9495 52,1134 169 14,4333 175,9164 177,2274 45,662 20,5990 63,5160 119,3511 104,3712 187,9225 192,8603 109,382 158,1709 55,7795 1,8700 138,7498 142,7506 166,5530 107,668 15,7485 54,2296 140,2230 170 119,275 1,2620 198,8089 136,1529 33,3648 18,4989 177,2774 44,6940 84,2436 2,9342 154,5971 164,328 45,8060 71,1539 94,9318 171 188,6981 101,4083 16,3482 67,1394 61,6888 49,9736 182,4704 94,9959 10,2029 33,3913 185,5113 71,6702 6,3722 18,4403 72,8573 172 200,6888 42,5383 72,3153 104,561 174,3433 102,6572 175,5353 35,992 73,2239 164,9550 29,5830 80,7715 77,4771 2,1438 60,2781 125,8515 13,2070 173 112,7338 1,2069 144,8693 33,5949 17,7312 20,2676 18,7256 121,2976 168,3859 32,9631 148,6725 82,591 163,5799 192,2550 166,6917 179,4234 138,8555 44,5518 95,4092 153,7613 135,5664 61,4803 125,2615 193,4808 46,2969 174 130,4481 89,858 73,2581 135,6977 68,7082 136,5711 91,3418 125,9048 122,8205 145,7252 72,2019 151,1846 172,3433 108,5669 99,5675 179,1886 149,2824 90,6914 175 156,2205 187,2864 27,210 199,3779 67,5048 121,8821 169,9164 134,4489 65,7920 26,6165 172,5353 197,5909 8,1022 129,7121 14,6718 184,9107 70,3256 58,3675 157,1597 176 200,1709 115,8236 6,3512 33,3258 187,1128 191,3352 139,8186 149,2255 116,4512 46,9923 143,5062 51,1625 164,8681 107,6806 74,8129 177 86,7010 92,3182 24,393 64,7660 102,4462 43,9544 22,8713 190,1332 14,6741 8,8508 170,2774 82,7882 169,2274 32,6902 53,9852 60,5345 143,3884 178,7547 118,8279 3,7097 178 130,615 72,5128 70,3394 13,4194 120,8906 11,1696 151,5979 16,1714 138,6589 102,1334 17,7464 49,9747 177,7547 35,5774 136,2752 28,3642 76,8433 179 80,7729 160,2542 136,6711 120,3327 56,5284 50,2502 186,9993 180,664 104,8827 90,3149 74,1223 148,6374 174,1886 126,7436 173,4234 162,9718 116,8099 34,8528 52,3504 122,7377 180 160,624 159,5757 114,8490 59,2435 86,4604 39,9506 85,5525 179,664 191,6312 31,3598 149,3407 167,6183 89,6612 9,5995 126,7176 105,341 181 112,2524 187,7956 41,5235 118,8129 185,9712 139,5456 76,3275 40,2338 11,8448 34,5267 102,3585 126,8920 106,5332 93,4071 91,5060 191,4844 163,5593 158,969 51,158 182 27,6234 47,8382 99,2897 139,2354 5,8806 133,8241 132,6433 56,7267 74,1873 35,7369 64,4701 107,8313 54,438 171,4704 2,7908 21,2447 183 160,9293 112,9037 102,9634 99,3577 81,3061 88,5547 11,594 96,5939 53,5304 105,7722 26,4842 57,9093 70,5332 125,9920 164,615 38,5213 184 6,8021 130,8488 188,198 40,4306 123,2832 101,9591 113,4999 129,5623 144,5222 175,9107 136,6682 164,9774 86,801 57,7592 29,9797 81,4485 35,7437 135,7629 28,4164 10,3207 128,6339 185 57,9772 105,1033 90,7284 52,8925 83,9306 97,7065 148,2814 25,3573 197,3140 50,3968 11,2045 141,6820 76,3674 108,8699 60,6670 188,700 120,556 181,9712 154,1448 30,3846 16,6280 109,6644 171,5113 19,5896 196,1339 186 57,8815 152,2075 197,1324 42,9391 188,5027 92,7980 179,9993 191,8255 58,8993 143,8430 116,8639 162,6114 71,7143 189,8128 195,2099 68,2528 103,9654 187 14,4874 200,6767 176,1128 37,4105 7,9522 175,2864 19,107 107,2610 167,9538 157,7184 24,9327 181,7956 42,3075 158,6714 165,1291 50,2485 154,1808 113,6332 169,9225 149,9580 10,4786 188 23,4236 198,9114 137,9117 184,198 101,8531 167,6549 54,4883 149,1003 28,3816 196,88 52,7805 55,5181 185,700 186,5027 171,6981 97,4695 138,892 125,230 146,5715 140,6223 189 152,8140 160,1530 8,2780 114,3102 86,1115 40,4263 77,5702 50,7031 47,5939 85,1147 60,4415 69,5215 186,8128 198,9430 122,2017 51,8899 151,9732 193,2375 190 4,7536 200,5999 47,5892 113,697 130,3429 135,1431 150,5243 61,9775 69,8022 133,9958 128,2968 100,6674 17,7000 106,3305 9,3613 177,1332 31,5055 149,3755 142,8070 15,6854 105,2518 191 77,5135 126,3989 176,3352 94,8318 186,8255 121,8606 87,6921 44,8130 103,9683 75,1403 181,4844 50,5026 180,6312 111,5723 37,3573 133,4296 192 114,6813 97,6411 77,561 39,7454 22,4606 104,4219 27,5344 85,544 173,2550 91,6625 169,8603 116,5906 49,3113 163,2762 122,1494 148,4834 193 152,5444 167,8116 114,4000 55,8583 58,6166 189,2375 159,3786 96,8831 79,7737 21,494 28,9441 62,6610 123,7460 99,4566 173,4808 46,199 194 200,2915 159,9391 136,2496 130,9429 42,6498 92,426 139,6966 162,1483 73,8521 99,5832 155,6768 114,949 46,2429 79,5784 135,5726 195 23,3179 4,2490 197,5337 144,652 136,4279 6,2233 158,4912 186,2099 200,8114 61,8928 46,8206 164,9730 119,617 19,5038 67,5737 196 188,88 39,9267 139,3988 95,231 61,5577 161,9729 125,4519 117,3366 103,696 46,9632 26,6754 112,5663 128,1760 119,2824 185,1339 197 54,2223 186,1324 121,6502 134,6225 68,8223 24,9337 25,3875 139,1386 81,5540 44,4900 195,5337 37,9188 111,4083 86,9714 110,751 136,9068 185,3140 104,4174 175,5909 198 141,2621 170,8089 44,2619 188,9114 41,7215 1,1724 154,5078 84,5999 16,2223 117,3936 123,3493 159,8330 69,6284 132,2393 134,4071 77,5081 50,3798 65,3575 36,6280 28,366 128,1860 189,9430 199 152,2697 8,1918 136,7783 59,8958 24,2838 175,3779 31,5564 162,7749 65,11 76,6878 9,70 89,2446 34,8196 167,2001 154,5786 200 108,9976 103,6851 145,2753 41,2622 187,6767 190,5999 16,2848 194,2915 5,4009 172,6888 39,4319 176,1709 60,3269 138,678 43,8943 98,2690 1,8021 104,7083 154,229 91,1988 67,475 76,4623 195,8114 37,7541 54,4899 | Dijkstra algorithm implementation in F# | algorithm;graph;f# | A few small comments on the code:1.In function parseLine, when you parse file, you use Array.filter (fun s -> not(s=)) . But there is standard function for check it - String.IsNullOrWhiteSpaceArray.filter (String.IsNullOrWhiteSpace >> not)2. In F# there is Forward composition operator. You can apply it, for example, in function nodelist, to group conditions:let nodelist = Array.map (fst >> int) y3.Not necessary use new when creating SortedDeque:let PQ = SortedDeque<int*int>() May be useful: F# new keyword. What is it for?4.Use short form to get elements of tuple. The tuple types in F# are somewhat more primitive than the other extended types. As you have seen, you dont need to explicitly define them, and they have no name.It is easy to make a tuple -- just use a comma!And as we have seen, to deconstruct a tuple, use the same syntax:Taken from TuplesSo, instead:let z = PQ.RemoveFirst()let W = snd zlet l = fst zbetter:let l, W = PQ.RemoveFirst()5.Redundancy init_loop. Creating internal functions for only one invocation degrades the code readability.6.In my opinion such entry: for k in 1..N do one_loop() only confuses. There is nothing wrong if the body of the loop contain meaning!7.It is better to invert the conditions, if it saves you from writing empty branches. Instead: update_list |> List.iter ( fun (node,dist) -> if (inX.[node]=true) then () else let x = l+dist if x > D.[node] then () else better: for node, dist in graph.[W] do if inX.[node] |> not then let x = l + dist if x <= D.[node] then Your function that implements the algorithm, contains the console output. It is better to avoid those moments. For example, if you want to add a GUI or web interface.A lot of unnecessary brackets.If you change it, you get:Module Dijkstra:module Dijkstraopen Spreads.Collectionslet limit = 1000000 // max distance limitlet tryIndexOf (heap:SortedDeque<_>) elem = try heap.IndexOfElement elem |> Some with | :? System.ArgumentOutOfRangeException -> Nonelet dijkstraWithPath (graph: (int*int) list []) (s:int) (n:int) = // S = source let count = n + 1 let V = [s + 1..n] |> List.append [0..s - 1] // List.filter ((=) S >> not) [0..N] let A = Array.create count limit // on ne se sert pas de A.[0] let B = Array.create (n+1) [] let C = Array.create count -1 // stores the index of the element in X nearest to an element in V. let D = Array.create count limit // stores the value of Dijkstra criterion let inX = Array.create count false // remembers if the node is in X (= has been processed) A.[s] <- 0 inX.[s] <- true let PQ = SortedDeque<int*int>() // Key = distance to X ; Value = Node for node in V do PQ.Add (limit, node) for node, dist_to_S in graph.[s] do (limit, node) |> PQ.IndexOfElement |> PQ.RemoveAt |> ignore (dist_to_S, node) |> PQ.Add |> ignore B.[node] <- [s, node] C.[node] <- s D.[node] <- dist_to_S for k in 1..n do let l, W = PQ.RemoveFirst() // take the first element from the queue A.[W] <- l // maintain the heap // the Key must the Dijkstra criterion for node, dist in graph.[W] do if inX.[node] |> not then let x = l + dist if x <= D.[node] then match tryIndexOf PQ (D.[node], node) with | Some i -> PQ.RemoveAt i |> ignore // updater le node PQ.Add (x,node) C.[node]<- W // prdcesseur D.[node]<- x // update la distance X B.[node]<- (W, node)::B.[W] | None -> failwith some information message inX.[W] <- true // returns the array of all shortest paths with source A.[0]=limit doesn't mean anything. A, B |> Array.map List.rev Test:open Systemopen System.IOopen System.Diagnosticslet stopWatch = Stopwatch.StartNew()let path = F:\Test.txtlet x = File.ReadAllLines path// original format of each row is row_number (a1,b1) (a2,b2) ....(an,bn)let split (text:string) = text.Split [|'\t';' '|]let split_comma (text:string)= text.Split [|','|]let splitIntoKeyValue (A: 'T[]) = A.[0], A |> Array.toList |> List.taillet parseLine line = line |> split |> Array.filter (String.IsNullOrWhiteSpace >> not) |> splitIntoKeyValuelet y = Array.map parseLine xlet nodelist = Array.map (fst >> int) ylet N1 = Array.max nodelist // be careful if there is an image node with a bigger ID !!!let graphcore = // nodes without outgoing edges will be missing y |> Array.map (snd >> List.map split_comma) |> Array.map (List.map (fun (A:string[]) -> int A.[0], int A.[1]))let N = graphcore |> Array.map (List.map fst >> List.max) |> Array.max // node max// non-optimized constructionlet graph = let g = Array.create (N+1) [] let count = Array.length nodelist for i in 0..count - 1 do g.[nodelist.[i]] <- graphcore.[i] glet s = 1let n = 200let A, B = Dijkstra.dijkstraWithPath graph s n//stopWatch.Stop()printfn A = %A Aprintfn B = %A Bprintfn %f stopWatch.Elapsed.TotalMillisecondsConsole.ReadKey(true) |> ignoreThe name of the variable it is better to give meaningful, but not A,B,C,...x,y. I'm not familiar with graph theory, so couldn't fix it. |
_softwareengineering.155419 | In addition to create list using parentheses, Clojure allows to create vectors using [ ], maps using { } and sets using #{ }.Lisp is always said to be a very extensible language in which you can easily create DSLs etc. But is Lisp so extensible that you can take any Lisp dialect and relatively easily add support for Clojure's vectors, maps and sets (which are all functions in Clojure)?I'm not necessarily asking about cons or similar actually working on these functions: what I'd like to know is if the other could be modified so that the source code would look like Clojure's source code (that is: using matching [ ], { } and #{ } in addition to ( )).Note that if it cannot be done this is not a criticism of Lisp: what I'd like to know is, technically, what should be done or what cannot be done if one were to add such a thing. | Can the Clojure set and maps syntax be added to other Lisp dialects? | syntax;lisp;clojure | Yes, they can be added. It is something you can do using reader macros. There is already #() for vectors, but you can define your own [...] macro:(set-macro-character #\] (get-macro-character #\)))(set-macro-character #\[ (lambda (stream char) (declare (ignore char)) `',(apply #'vector (read-delimited-list #\] stream t))))CL-USER> [1 2 3]#(1 2 3)CL-USER> (aref [1 2 3] 0)1CL-USER> Look at closer-apl for more&cooler examples. |
_cs.11933 | Does there exist a cellular automaton (in 2D) which simulates a $1/r$ force between particles?More specifically, I would like to know whether it is possible, with strictly local update rules, to have two objects (defined within the model) attract each other with a $1/r$ force, where $r$ is the distance separating the objects. This would in particular entail an acceleration of the object (particles) as they get closer together.More generally, can long range attractive forces between objects (blobs) be simulated in a cellular automaton setting with strictly local rules? | 1/r attractive force by cellular automaton | simulation;cellular automata | null |
_codereview.138992 | I just began learning how to use signals and slots in PyQt5, and so I made a cute (pun intended) little program to display just one button. When the button is pressed a thread is spawned which will count from 0 to 99 and display the current count onto the button. However, when the button is counting, the program will not allow the user to spawn another thread.I am about to actually use my knowledge for a much heavier task, and I wanted to know if there was an easier way to do what I did. Or, perhaps my way is not very efficient? Thanks in advance!import threadingimport sysimport timefrom PyQt5.QtWidgets import *from PyQt5.QtCore import *class Application(QMainWindow): counter = pyqtSignal(str) counting = False def __init__(self): super(Application, self).__init__() self.button = QPushButton() self.button.setText('99') self.button.clicked.connect(self.startCounting) self.counter.connect(self.button.setText) self.layout = QVBoxLayout() self.layout.addWidget(self.button) self.frame = QFrame() self.frame.setLayout(self.layout) self.setCentralWidget(self.frame) def startCounting(self): if not self.counting: self.counting = True thread = threading.Thread(target=self.something) thread.start() def something(self): for x in range(100): self.counter.emit(str(x)) time.sleep(.01) self.counting = Falseif __name__ == '__main__': app = QApplication(sys.argv) window = Application() window.show() sys.exit(app.exec_()) | Simple PyQt5 counting GUI | python;gui;pyqt | Looks good to me!super minor nits: thread = threading.Thread(target=self.something) thread.start()only uses the thread variable once, so you might as well do: threading.Thread(target=self.something).start()Also, the only thing you use from threading is Thread so you might as well change your import to:from threading import Threadand then it can be just:Thread(target=self.something).start()...but again, these are super minor things! It looks good to me; I may have to look at pyQT again :) |
_webapps.95978 | I am not sure if a concept of a group task is available in Trello, below is what we are tryingA number of team member create individual level tasks and push them through backlog, working, done etc. A bunch of these tasks form a group task. Let's say team member A is doing task P, Q, R and Q is an important dependency for another task S which is being done by team member B. We do not know how to link dependencies. A & B's team lead wants to know what is happening to hist group task or a mini project or whatever we call it. It might involve a series of tasks some of which has dependency relationship. Others are in a schedule and sequence. Question is how to have that group-task or mini-project view? | Using Trello to track Progress of a task group (A group of tasks) | trello | null |
_unix.386145 | I'm trying to set up a Heartbeat client on a linux machine (CentOS Linux release 7.3.1611) which is sending ICMP echo requests to roughly 1300 hosts. However, in future this number will be higher. The messages generated by heartbeat are being shipped to a logstash instance on another server.These requests go out every 3 minutes, all at once. After the first round of requests, a large number of these messages contain an error: write ip4 0.0.0.0->x.x.x.x: sendto: no buffer space availableI've tried multiple ways of mitigating this issue, including staggering the requests so there are less being sent out in 1 second. This caused issues with data synchronisation at the end of this pipeline (as well as not completely resolving the issue) so it's not really a feasible option for me.Researching online led me to increasing the memory allocated to TCP/IP connections by the system, however these are ICMP requests which as far as I'm aware should be separate.I'm also unable to bounce the network interface as the machine is remote and I don't have a way of getting back in to bring it back up.I also tested out increasing (and setting to 0) the icmp_ratelimit variable in /proc/sys/net/ipv4 but this hasn't helped either.My question is pretty general, what could be causing this issue? Is there some sort of variable I need to tweak on the system that will allow these requests to all be sent out at once? I can't really deduce what buffer the error message is referencing.Any help would be greatly appreciated...P.S. if further clarification is needed I'd be happy to provide it.EDITStill unsure if there is a fault elsewhere however increasing the size of the socket buffer determined by the wmem_max, wmem_default, rem_max, rem_default variables in /proc/sys/net/core has fixed the issue. It's likely that the total size of the data for all the ICMP echo requests was too large to fit under the previous maximum of 208kb and so a large number of them would be dropped. Doesn't really explain why the number of dropped requests would vary each time, maybe there is an underlying issue...Now my only problem is that each time I reboot the system, these variables reset to 208kb each. How do I make these changes persistent? | No buffer space available - ICMP | linux;networking;icmp;heartbeat | null |
_unix.120097 | Sorry if this is a duplicate. It seems somewhat similar to the question here but I think what I'm asking is a little different. I've got a CentOS 5.x box running with mysql on it. The root linux user can edit/modify files in /var/lib/mysql/ sub-directories but most (if not all) of these directories have file system ownerships of mysql:mysql. When I run groups root I see: [root@foo ~]# groups rootroot : root bin daemon sys adm disk wheelI get that root is a privileged account and can/will have access to everything but why don't I see mysql in the list of groups it belongs to? | Why does the root user have control over mysql directories but not show as a member of the mysql group? | linux;permissions;mysql | The definition of the root user dictates that it has control over all files on the disk, irregardless of the user's & groups that own said files & directories.Many Unixes, such as Solaris, used to have a limitation where users could not be in more than 15 groups. NIS another technology for sharing user/group/automounting information also had this limitation. So typically you would not see the root user in these groups. For one it wasn't possible to do so (given this limit), and also it was not needed for the root user to access files/directories with other ownership anyway. Additionally it's often considered bad design to have all your services/daemons running as root, instead they would each be governed by their own dedicated users & groups.So the simple answer to your question is root doesn't need to be in those groups because it can do anything it wants to the files/directories on a system, it's the master owner and has complete dictatorship over the files that are local to the system.So then why is root in any groups?This is more of a historical practice where you used to see root in several key groups. This is being phased out, to my knowledge, and most of the newer systems that I've supported no longer have this, since it's completely unnecessary now.Fedora 19$ groups rootroot : rootCentOS 6$ groups rootroot : root bin daemon sys adm disk wheelNOTE: The primary purpose you'll often times see root in other groups is to allow root to create files within these groups directly, without having to do a chgrp or chown after creating files in directories that are grouped to one of these groups afterwards. When root needs to assume one of the other groups it can run a simple newgrp <group> to switch if needed, or respect a directory that already has the SGID bit on a directory.ReferencesHow does the sticky bit work?How do the internals of sudo work? |
_unix.18272 | When I start my computer I want that remember my applications opened before close the last session such as Ubuntu, and other distros do normally.Googling, I see that I can run apps when I start session, configuring the autostart file but I don't want always run the same programs at start, instead I want reopen the programs opened before close last session.I use Fedora spin with LXDE. | Remember applications on logout from LXDE | x11;session;lxde | null |
_softwareengineering.14461 | According SaaS maturity model a SaaS is level 2 if is configurable, but how i can get started in this concept?how patterns and Technics, i can use to enable my SaaS? | SaaS maturity level 2, how i can build configurable SaaS?(Technics and patterns) | cloud computing;architect | null |
_unix.356612 | I have two questions about virtual address layout of kernel on x86 and x64 system.As far as I know, x86 uses the splited memory layout that is highmem and lowmem.If my understanding is correct, the only difference between highmem and lowmem is whether it has 1:1 virtual to physical address mapping or not. Also, it seems that lowmem contains code and data frequently accessed by the kernel program and highmem contains the page tables or userlevel program data which is not frequently accessed. However, I cannot understand the reason the x86 kernel splits the virtual address spaces and locates the frequently accessed data and code to lowmem. What is the advantage of it? It seems that regardless of the location of the kernel memory, page table walking should be invoked to get virtual to physical mappings. If it is correct, it seems that there is no advantage of the highmem and lowmem. Here, my first question is, if lowmem uses the 1:1 mappings (i.e., physical address + constant(0x80000000) => kernel virtual address) why the MMU spends its clock to walk the page table to know the virtual to physical mappings. If possible, we can modify the MMU logic to make it only minus magic constant from the virtual address to get a physical address if it is located in lowmem region.or is there any other reasons to locate frequently accessed data and code into the lowmem? And why only the lowmem uses the 1:1 mappings...?My second question is does lowmem and highmem memory split mechanism deployed in the x64 linux system also? Thanks in advance | Questions about kernel virtual address layout | linux;virtual memory;x86 | Highmem and lowmem are related to the Physical Address Extension on x86 processors. This mechanism enables the processor to address 64GB of memory, instead of the conventional 4GB. However, because the instruction set is unchanged, and the registers and pointers are still 32 bit long, the virtual address space is still limited to 4GB. Machine instructions always use virtual addresses, not physical addresses.The consequence of this is that highmem cannot be directly addressed at all until it is mapped into the addressable region. This is why only lowmem uses the 1:1 mapping; mapping to highmem is not possible.Your next question was: why can't the MMU logic be simplified to skip page tables and do a simple subtraction to get the physical address? The MMU is implemented in hardware, and it is designed to use page tables (and the TLB) to do its job. Huge pages exist, though, which skip one level in the page tables, making the page size 4MB instead of 4kB on the x86.Your last question: is the memory split in lowmem and highmem on the x64 architecture too? No. The PAE mechanism is a bit of a kludge to extend the lifetime of the x86. The x64 with its much larger address spaces (both physical and virtual) does not need it. |
_softwareengineering.337616 | I've been developing applications according to the principles of DDD for a while now, and, as many, I often run into issues when it comes to persisting an aggregate.One of the main advantages of DDD is that it allows me to use the full power of OO design in my domain -- as such I want to use polymorphism and conform to the open-closed principle. I.e. I can extend my logic by adding new subtypes without requiring changes to the supertypes.The problem comes when persisting this. Somehow I need to flatten this domain to some persisted representation, and then later restore it. How do I achieve this, without littering the Repository implementation with instanceof (or equivalent in your language of preference) all over the place. This is generally considered bad form, plus it violated OCP, at least in the repository itself. When I add a new subtype, I'm forced to add a case in the repository.Is there an elegant way to handle this? | In DDD, how do I persist an aggregate containing polymorphism | domain driven design;open closed principle | One of the ways is to use reflection. During application startup, the repository would inspect structure of your domain entities and automagically determine relational model and mapping of entities to this relational model. This is basically what most modern ORMs can do. The disadvantage of this approach is that it is extremely complicated to implement for non-trivial cases and one small change in domain model might result in drastically different relational model, which complicates migrations between versions.Other than that, no, there is no way. If your repository depends on your domain model, it means the repository has to change when domain model changes. That is very definition of dependency. And OCP can only really work if things are not dependent of each other.But there is a way to make the change easier and safer. Why is usage of instanceof a problem? There is nothing wrong with using it. Its just that if you add new subtype, you don't know where you have to extend the code to support this new subtype. But there is solution for that : a Visitor pattern. With visitor, when you add a new subclass, you also add new method to an interface. This means every class that implements this interface will become non-compilable and you will immediatelly know where everywhere you have to extend the code to support the new class. Yes, it will make adding new subtype harder, but it will make that change safer. |
_webapps.51281 | I have this table:| A | B ||---------|-----|| grocery | $10 || clothes | $40 || grocery | $19 |etc.So I'd like to have a column with an aggregation of the categories like grocery and clothes with the total expenses, what in SQL would be a JOIN with the aggregate function SUM()How can I achieve this? | How to do a Google Spreadsheet equivalent to SQL's JOIN and SUM( )? | google spreadsheets | This is what I think you're looking for:Formula=QUERY(DATA!B1:C3;SELECT B, SUM(C) GROUP BY B label B 'Type', SUM(C) 'Sum')ExplainedColumn C is aggregated by column B through a summation. Labels are added. In this particular case, the usage of JOIN in an SQL statement isn't applicable, since the aggregation is done on one table. ScreenshotsData:ResultExampleI've created an example file for you: Sum Aggregate |
_codereview.40190 | I am learning about object oriented programming in Python using classes. I have attached an image of what I had in mind when structuring my classes. This is supposed script model cars. I want to know if the way that I set up my code it the ideal way of modeling cars.A few things:There are no syntax errors. I can create instances without errors.The subclasses uses *args to get the attributes of the parent class. Is this the correct way of doing that?I am using Python 2.7.5I have included a few example instances of the classEach class only has an __init__ method and a vehicle_print method. I have not yet added any other methods.class Vehicle(object): # no instance of this class should be created def __init__(self, typ, make, model, color, year, miles): self.typ = typ self.make = make self.model = model self.color = color.lower() self.year = year self.miles = miles def vehicle_print(self): print('Vehicle Type: ' + str(self.typ)) print('Make: ' + str(self.make)) print('Model: ' + str(self.model)) print('Color: ' + str(self.color)) print('Year: ' + str(self.year)) print('Miles driven: ' + str(self.miles))class GasVehicle(Vehicle): def __init__(self, fuel_tank, *args): self.fuel_tank = fuel_tank Vehicle.__init__(self, *args) def vehicle_print(self): Vehicle.vehicle_print(self) print('Fuel capacity (gallons): ' + str(self.fuel_tank))class ElectricVehicle(Vehicle): def __init__(self, energy_storage, *args): self.energy_storage = energy_storage Vehicle.__init__(self, *args) def vehicle_print(self): Vehicle.vehicle_print(self) print('Energy Storage (Kwh): ' + str(self.energy_storage))class HeavyVehicle(GasVehicle): # no instance of this class should be created def __init__(self, max_weight, wheels, length, *args): self.max_weight = max_weight self.wheels = wheels self.length = length GasVehicle.__init__(self, *args) def vehicle_print(self): GasVehicle.vehicle_print(self) print('Maximum load (tons): ' + str(self.max_weight)) print('Wheels: ' + str(self.wheels)) print('Length (m): ' + str(self.length))class ConstructionTruck(HeavyVehicle): def __init__(self, cargo, *args): self.cargo = cargo HeavyVehicle.__init__(self, *args) def vehicle_print(self): HeavyVehicle.vehicle_print(self) print('Cargo: ' + str(self.cargo))class Bus(HeavyVehicle): def __init__(self, seats, * args): self.seats = seats HeavyVehicle.__init__(self, *args) def vehicle_print(self): HeavyVehicle.vehicle_print(self) print('Number of seats: ' + str(self.seats))class HighPerformance(GasVehicle): # no instance of this class should be created def __init__(self, hp, top_speed, *args): self.hp = hp self.top_speed = top_speed GasVehicle.__init__(self, *args) def vehicle_print(self): GasVehicle.vehicle_print(self) print('Horse power: ' + str(self.hp)) print('Top speed: ' + str(self.top_speed))class SportCar(HighPerformance): def __init__(self, gear_box, drive_system, *args): self.gearbox = gear_box self.drive_system = drive_system HighPerformance.__init__(self, *args) def vehicle_print(self): HighPerformance.vehicle_print(self) print('Gear box: ' + self.gearbox) print('Drive system: ' + self.drive_system)bmw = GasVehicle(30, 'SUV', 'BMW', 'X5', 'silver', 2003, 120300) # regular carbmw.vehicle_print()printtesla = ElectricVehicle(85, 'Sport', 'Tesla', 'Model S', 'red', 2014, 1243) # electric cartesla.vehicle_print()printlambo = SportCar('manual', 'rear wheel', 650, 160, 23, 'race car', 'Lamborgini', 'Enzo', 'dark silver', 2014, 3500) # sportscarlambo.vehicle_print()printtruck = ConstructionTruck('cement', 4, 12, 21, 190, 'transport', 'Dirt Inc.', 'Dirt Blaster 100', 'blue', 1992, 120030) # Construction trucktruck.vehicle_print()dpastepastebin | Model cars as classes | python;object oriented;classes;python 2.7 | A couple of things to consider1) As a style thing, I'd prefer **kwargs to *args in your constructors. This makes things clearer since there's no chance that a change to a base class initializer will invalidate other code in subclasses. Something like @MichaelUrman's example:class Vehicle(object): Represent a vehicle. def __init__(self, **kwargs): self.info = kwargsAllows you to flexibly specify values while providing class level defaults that vary on application. Super (as mentioned in other answers) is great for avoiding repetition here. For exampleclass FourByFour (Vehicle): def __init__(self, **kwargs): # provide a default transmissions if not 'transmission' in kwargs: kwarg['transmission'] = 'Generic 4x4' super (FourByFour, self).__init__(**kwargs)In the comments to @MichaelUrman's example, OP asks how to create a specific class of car. A common python idiom (which is less common in other languages) is to create 'thin' subclasses that vary primarily by default content and then occasionally override default methods. This is common in cases where you want a lot of classes which are mostly the same but differ in details and you don't expect to manage lots of subtle hierarchical changes. From the 10,000 ft level this is the same using helper classes, since you're just populating a set of variables in a structured way; I prefer it to using helper functions because it allows you to add custom methods as necessary while keeping things data driven.For example:class Vehicle(object): Represent a vehicle. DEFAULTS = {'wheels':4, 'doors':2, 'fuel':'gasoline', 'passengers':2} def __init__(self, **kwargs): kwargs.update(self.DEFAULTS) self.info = kwargs def drive(self): print Vroomclass Sedan(Vehicle): DEFAULTS = {'wheels':4, 'doors':4, 'fuel':'gasoline', 'passengers':5}def Hybrid(Sedan): DEFAULTS = {'wheels':4, 'doors':4, 'fuel':'smug', 'passengers':4} def drive(self): print purrrrrr...class Van(Vehicle): DEFAULTS = {'wheels':4, 'doors':3, 'fuel':'gasoline', 'passengers':2, 'cargo':[]} def unload(self): if not self.cargo: print no cargo loaded else: print unloading return self.cargoConceptually this is halfway between 'traditional' inheritance heavy OOP and @MichaelUrman's data customization approach. All three have their applications, and the neat thing about python is that it's very good at both @MichaelUrman's method and mine -- which is not true for languages obsessed with type-checking and signature maintenance.2) On the strategy level, in the long term you'll benefit from a finer grained approach. Engines, transmissions, and tires for example might be their own classes instead of aspects of vehicle (a station wagon and a sedan, for example, might share everything but body styles). The class hierarchy becomes less of an issue as you do more mix-and-match customization by creating collections of components. The usual pretentious programmer way to say this is 'prefer composition over inheritance' |
_webmaster.27611 | I am trying to enable the internal site seach tracking with Google Analytics.So at analytics page, account mysite.com: Profile Settings => Site Search Settings, do track enabled.At my site when someone make a search for test, URL looks like: mysite.com/search?keyword=test. At the query parameter I added search?keyword= but I haven't seen any results so far, any idea how to fix this? | Google Analytics site search | google analytics | If the search result page is at mysite.com/search?keyword=test, then the query parameter is keyword |
_codereview.27573 | I have built a 3D matrix class in C++, mainly for data I/O, for a project I am working on. The code works ok, but I would like you to help me improve it.Are there any bad programming practices I am doing?Is there any code that could be simplified?Is there something that would give me fastest access to the data stored in the object? 4. Is there something that could lead me to error in the future?Grid3d.h:#ifndef _GRID3D_#define _GRID3D_#include <iostream>#include <cmath>#include <iomanip> // setprecision()#include <cassert> // assert()using namespace std;class Grid3d{private: int L; int M; int N; double *** G;public: //Constructors Grid3d(int,int,int); Grid3d(); Grid3d(const Grid3d &); ~Grid3d(); //Operators double & operator()(int,int,int); Grid3d & operator=(Grid3d); //Access int get_L(); int get_M(); int get_N(); double get(int,int,int); void clean(); void swap(Grid3d &); friend std::ostream & operator<< (std::ostream &,Grid3d &);};#endifGrid3d.cc:#include Grid3d.h//ConstructorGrid3d::Grid3d(int L,int M,int N) :L(L), M(M), N(N){ int i,j,k; G = new double ** [L]; for (i=0;i<L;i++){ G[i] = new double * [M]; for (j=0;j<M;j++){ G[i][j] = new double [N]; for (k=0;k<N;k++){ G[i][j][k] = NAN; } } }}//Empty constructorGrid3d::Grid3d() :L(0), M(0), N(0){ G = NULL;}//Copy constructorGrid3d::Grid3d(const Grid3d &A) :L(A.L), M(A.M), N(A.N){ G = new double ** [L]; int i,j,k; for (i=0;i<L;i++){ G[i] = new double * [M]; for (j=0;j<M;j++){ G[i][j] = new double [N]; for (k=0;k<N;k++){ G[i][j][k] = A.G[i][j][k]; } } }}//DestructorGrid3d::~Grid3d(){ // Free memory for (int i=0;i<L;i++){ for (int j=0;j<M;j++){ delete [] G[i][j]; G[i][j] = NULL; } delete [] G[i]; G[i] = NULL; } delete G; G = NULL;}//------------------------------------------------------------------// Operators//------------------------------------------------------------------//Access operator ():double& Grid3d::operator()(int i,int j,int k){ assert(i >= 0 && i < L); assert(j >= 0 && j < M); assert(k >= 0 && k < N); return G[i][j][k];}//Assignment operatorGrid3d& Grid3d::operator = (Grid3d A){ swap(A); return *this;}//------------------------------------------------------------------// Access//------------------------------------------------------------------int Grid3d::get_L(){ return L;}int Grid3d::get_M(){ return M;}int Grid3d::get_N(){ return N;}double Grid3d::get(int i,int j,int k){ return G[i][j][k];}void Grid3d::clean(){ int i,j,k; for (i=0;i<L;i++){ for (j=0;j<M;j++){ for (k=0;k<N;k++){ G[i][j][k] = NAN; } } }}//------------------------------------------------------------------// Others//------------------------------------------------------------------//Swapvoid Grid3d::swap(Grid3d & A){ std::swap(L, A.L); std::swap(M, A.M); std::swap(N, A.N); std::swap(G, A.G);}//coutstd::ostream & operator << (std::ostream & os , Grid3d & g){ int L = g.get_L(); int M = g.get_M(); int N = g.get_N(); for (int k=0;k<N;k++){ cout << k = << k << endl; for (int i=0;i<L;i++){ for (int j=0;j<M;j++){ cout.width(10); os << setprecision(3) << g.G[i][j][k] << ; } os << endl; } os << endl; } return os;}This is a sample function in which I am using these objects to evaluate the curl of a vector field in a point:double System::curl_r(Grid3d &Ath,Grid3d &Aph,int i,int j,int k){ double curl_rA = ( (SIN[j+1]*Aph(i,j+1,k)-SIN[j-1]*Aph(i,j-1,k))/dth - (Ath(i,j,k+1)-Ath(i,j,k-1))/dph )/(2.0e0*R[i]*SIN[j]); return curl_rA;}For example:Grid3d Er = Grid3d(Nr,Nth,Nph);Grid3d Eth = Grid3d(Nr,Nth,Nph);Grid3d Eph = Grid3d(Nr,Nth,Nph);Grid3d curlE_r = Grid3d(Nr,Nth,Nph);...curlE_r(i,j,k) = curl_r(Eth,Eph,i,j,k); | Simple matrix class | c++;matrix | null |
_webapps.22723 | Most news feeds give all their main headlines for the day, but is there a feed that only gives the headlines that are actually really important? For example, the death of a public figure, major political developments, natural disasters. The kind of headlines that happen once or twice a month. | Where can I find an RSS feed for TRULY big deal news headlines? | rss;feeds;news feed;news | null |
_unix.76985 | I installed gEDA and I am trying to find it's installation directory/path.I've searched Google for many strings and entered a lot of the results it returned but didn't find anything about that.So how can I find gEDA's installation directory/path?Edit (24 May, 16:55 UTC):I've tried the following, suggested by @phunehehe:$ dpkg-query -L gEDA/./usr/usr/share/usr/share/doc/usr/share/doc/gedabut it doesn't seem like the installation folder for gEDA, only the documentation. | Finding gEDA installation directory | software installation | If you installed it by the package manager, you can find the files installed like this:# Debian, Ubuntu etc.dpkg-query -L <package-name># Redhat, Centos etc.rpm -ql <package-name>The package might pull in other packages that you should also check. To find them:# Debian, Ubuntu etc.apt-cache rdepends <package-name># Redhat, Centos etc.yum resolvedep <package-name>See Pacman Rosetta for commands on other distros.As a last resort (or if you didn't use the package manager, which I strongly recommend against), you can try searching by file name:sudo updatedblocate --ignore-case <program-name> |
_unix.14185 | I am writing a release script, which uses scp/sftp to get the the file from a remote server, we want to log the output of this script to a release.log file as well. I am using tee to achieve this, which works perfectly fine for everything, i mean standard out and error, but when it comes to progress of the file download(which takes time to copy), it doesn't show up on the console or in the file as well.Output of scp without [email protected]:/apps/flowrisk/valservice/release/London/uat2/vs-server-2.1.16-21190-linux-amd64-frod-uat2-London-dist.zip /apps/flowrisk/uatldn/valservicevs-server-2.1.16-21190-linux-amd64-frod-uat2-London-dist.zip 100% 78MB 39.1MB/s 00:02Output of scp WITH [email protected]:/apps/flowrisk/valservice/release/London/uat2/vs-server-2.1.16-21190-linux-amd64-frod-uat2-London-dist.zip /apps/flowrisk/uatldn/valserviceCan someone please tell me how to make it to output the progress of scp/sftp command on the console with tee as well, so that user know what is happening? | Output progess of the scp/sftp command to both standard out and a file on linux server | logs;io redirection;scp | null |
_codereview.31040 | What this should do is wait for dataBlockSize bytes to be ready and then continue, but wait for 10ms if they are not ready yet to not block the CPU, but not the first time as I do not want to wait once even if the bytes are ready.Is there a better way of doing this?while (!cancellationToken.IsCancellationRequested){ var ftdiStatus = ftdiDevice.GetRxBytesWaiting(ref rxBytes); if (ftdiStatus != FTDI.FT_STATUS.FT_OK) return null; if (rxBytes >= dataBlockSize) break; Thread.Sleep(10);} | Waiting for bytes to be ready | c#;multithreading | I think it is just a matter of taste. Here is one approach:do{ var ftdiStatus = FtdiDevice.FtdiDevice.Instance.GetRxBytesWaiting(ref rxBytes); if (ftdiStatus != FTDI.FT_STATUS.FT_OK) return null; if(rxBytes >= dataBlockSize) break; Thread.Sleep(10);}while (true); // Perhaps a check for timeout? |
_softwareengineering.175452 | Yesterday I asked a question that happened to have another meaning inside. I can see that Control/data flow is often mentioned to be static analysis (when tools is used) or dynamic analysis testing in terms of white box testing. Could it be that automatic analysis tools can just help by creating graphs or they do actually test it with inputs (then it would not be static IMHO). | Control flow testing in white box - static or dynamic? | testing;unit testing;flow | You can also have automatic analysis tools that perform symbolic execution. Klee is an example of this. Basically it goes through the program trying to figure out what are the possible values of variables at different points. Using that it decides which input variables can cover which parts of the code. It even does some cool things with modelling file systems and environment variables. Their paper is a fairly easy read and quite informativeSo in general I think the distinction is not that simple. KLEE runs the code in a way, but I would not call that proper execution. |
_codereview.60984 | Here is my program that turns numbers into text. It can be extended to millions, billions, trillions and so on. Please review my code and here is what I expect from the users:Is there any better variable names, function names, you can give me? Or my given names are okay? If you've better variable name ideas, please share.Last time one expert user gave me suggestion to write functions in separate files and then implement into main function by calling header name, I just did that, is this okay? Or I should make more separate files for each custom function?I tried my best to write program in object oriented way. I used Class and then wrote some functions inside them so I can call any method after the object name.For example: number.validate(varName)Do you see any problems in that? Am I doing something that isn't a good programming practice?My program works perfectly without any problem, is there any better way to do this?1. main.cpp/* * Implement the source code that turns numbers into English text. */#include <iostream>#include numberToText.hppint main (void){ numberToText(); return 0;}2. numberToText.cpp#include <iostream>#include <string>#include textlib.hppclass num{ public: bool validate (std::string numStr) { for (int i = 0; i < numStr.length(); i++) { if (!(isdigit(numStr[i]))) { return false; // terminate loop by returning value if there's anything in this string apart from number } } return true; // if there is no problem in loop then return true to confirm that string has all the numbers. } void take (std::string &numberString) { std:: cout << Enter your number:\n; std::cin >> numberString; while (1) { if (validate(numberString)) { break; //SUCCESS } else { std::cout << Invalid number, try again:\n; std::cin >> numberString; } } } void text (std::string string) { int digitLength = string.length(); if (digitLength == 1) { one_Nine(0, string); } else if (digitLength == 2) { twoDigits(0, string); } else if (digitLength == 3) { threeDigits(0, string); } else if (digitLength > 3 && digitLength < 7) { thousand(0, string, digitLength); } else // add more conditions if you want to extend the program { std::cout << Sorry, that's a vary large number.\n; } } private:};void numberToText (void){ std::string numStr; num number; number.take(numStr); number.validate(numStr); number.text(numStr);}3. numberToText.hpp/* * take numbers and display text */#ifndef NUMBERTOTEXT_HPP_#define NUMBERTOTEXT_HPP_void numberToText (void);#endif4. textlib.cpp#include <iostream>#include <string>#include textlib.hppvoid one_Nine (int i, std::string numberString){ if (numberString[i] == '1') { std::cout << One ; } else if (numberString[i] == '2') { std::cout << Two ; } else if (numberString[i] == '3') { std::cout << Three ; } else if (numberString[i] == '4') { std::cout << Four ; } else if (numberString[i] == '5') { std::cout << Five ; } else if (numberString[i] == '6') { std::cout << Six ; } else if (numberString[i] == '7') { std::cout << Seven ; } else if (numberString[i] == '8') { std::cout << Eight ; } else if (numberString[i] == '9') { std::cout << Nine ; } else if (numberString[0] == '0') { std::cout << Zero\n; } else { std::cout << Error: one_Nine() function isn't working!\n; }}void twoDigits (int j, std::string numberString){ if (numberString[j] == '1') { if (numberString[j+1] == '0') { std::cout << Ten ; } else if (numberString[j+1] == '1') { std::cout << Eleven ; } else if (numberString[j+1] == '2') { std::cout << Twelve ; } else if (numberString[j+1] == '3') { std::cout << Thirteen ; } else if (numberString[j+1] == '4') { std::cout << Fourteen ; } else if (numberString[j+1] == '5') { std::cout << Fifteen ; } else if (numberString[j+1] == '6') { std::cout << Sixteen ; } else if (numberString[j+1] == '7') { std::cout << Seventeen ; } else if (numberString[j+1] == '8') { std::cout << Eighteen ; } else if (numberString[j+1] == '9') { std::cout << Nineteen ; } else { std::cout << Error: twoDigits().\n; } } else if (numberString[j] == '2') { std::cout << Twenty ; if (numberString[j+1] == '0') { std::cout << ; } else { one_Nine(j+1, numberString); } } else if (numberString[j] == '3') { std::cout << Thirty ; if (numberString[j+1] == '0') { std::cout << ; } else { one_Nine(j+1, numberString); } } else if (numberString[j] == '4') { std::cout << Forty ; if (numberString[j+1] == '0') { std::cout << ; } else { one_Nine(j+1, numberString); } } else if (numberString[j] == '5') { std::cout << Fifty ; if (numberString[j+1] == '0') { std::cout << ; } else { one_Nine(j+1, numberString); } } else if (numberString[j] == '6') { std::cout << Sixty ; if (numberString[j+1] == '0') { std::cout << ; } else { one_Nine(j+1, numberString); } } else if (numberString[j] == '7') { std::cout << Seventy ; if (numberString[j+1] == '0') { std::cout << ; } else { one_Nine(j+1, numberString); } } else if (numberString[j] == '8') { std::cout << Eighty ; if (numberString[j+1] == '0') { std::cout << ; } else { one_Nine(j+1, numberString); } } else if (numberString[j] == '9') { std::cout << Ninety ; if (numberString[j+1] == '0') { std::cout << ; } else { one_Nine(j+1, numberString); } } else if (numberString[j] == '0') { one_Nine(j+1, numberString); } else { std::cout << Error: **********^^*****************; }}void threeDigits (int k, std::string numberString){ if (numberString[k] != '0') { one_Nine(k, numberString); std::cout << Hundred ; } if (numberString[k+1] != '0' || numberString[k+2] != '0') { twoDigits(k+1, numberString); }}void thousand (int l, std::string numberString, int digitLength){ if (digitLength == 4) { if (numberString[l] != '0') { one_Nine(l, numberString); std::cout << Thousand ; } threeDigits(l+1, numberString); } else if (digitLength == 5) { if (numberString[l] != '0') { twoDigits(l, numberString); std::cout << Thousand ; } else if (numberString[l] == '0' && numberString[l+1] != '0') { one_Nine(l, numberString); std::cout << Thousand ; } else { std::cout << ; } threeDigits(l+2, numberString); } else if (digitLength == 6) { if (numberString[l] != '0') { threeDigits(l, numberString); std::cout << Thousand ; } else if (numberString[l] == '0' && numberString[l+1] != '0') { twoDigits(l+1, numberString); std::cout << Thousand ; } else if (numberString[l+2] != '0') { one_Nine(l+2, numberString); std::cout << Thousand ; } else { std::cout << ; } threeDigits(l+3, numberString); } else { std::cout << Error: ~~~~~~; }}5. textlib.hpp/* * Can print numbers in English text. */#ifndef TEXTLIB_HPP_#define TEXTLIB_HPP_void one_Nine (int i, std::string numberString);void twoDigits (int j, std::string numberString);void threeDigits (int k, std::string numberString);void thousand (int l, std::string numberString, int digitLength);#endif | Turning numbers into text | c++;converting | C++ vs C styleIn C++ you don't need to declare empty parameter lists as void. Replace int int main (void)by int main()You also don't need to return 0; at the end of main in C++. This is done automatically by the compiler if the end of the main function is reached.Class designUsing a class in this context was not the best choice. When you look at your class you will notice that it has no member variables and only member functions.This means that each function could have been declared static (which means it does not need an instance of this class to be called on). If you were to make this transformation (making all of these class member functions static) you would have another code smell: A class that contains no (per instance) data and only static functions should in fact be a namespace.Applying this transformation would only change your code in numberToText to: std::string numStr; num::take(numStr); num::validate(numStr); num::text(numStr);Function (signature) designYou clearly need to use the return values of functions!Let's have a look at num::take for example. It returns the value via a reference parameter and has the return type void. This is somewhat counterintuitive. When looking at a function and asking oneself what it returns the first look is for the return type which says void in your case. How about this function interface:std::string take();It clearly communicates that take returns a string. Looking at the previous calls take(string) looks like it is taking the string and doing something with it (rather than returning into it).The name take seems a bit generic to me. What is taken? What the function actually does is querying the user for a valid number(string) until one is given. The name should reflect that. How about getNumberStringFromUser or something similar?Don't break your loop unnecessarilyLooking at the code I wonder why you are using a break here:while (1){ if (validate(numberString)) { break; //SUCCESS }//...Use the loop condition instead of breaking from the loop if it is more clear:while (!validate(numberString)){Exiting the loop within its body forces the reader to understand the additional (unexpected) branch introduced at the break.redundant validationThe string has already been validated in take so why validating it again and then discarding the return value of validate?function namesThe names of some functions are not well chosen:one_Nine -> printOnesDigitWordtwoDigits -> printTensDigitWordthreeDigits -> printHundredsDigitWordthousand -> printNumberAsWordsAlgorithmYour code looks very brittle and not that extensible. The interfaces of the printing functions are a bit complicated. Instead of passing the full number string and the index where to look you should pass only the part of the string that is relevant to the function. Another possibility would be to pass the value as an int. This would allow you to fit the function more easily (and portable) into arrays for example one_Nine:std::string oneDigitToString(int digit){ assert(0 <= digit && digit < 10); static const char *digitNames[] = {Zero One, Two, Three, Four, Five, Six, Seven, Eight, Nine }; return digitNames[digit];}Note that there are several improvements:reduced sideeffects by not calling std::cout (but now the caller has to print!)increased efficiency (you always get the result in one step instead of hopping through the cascading ifs)tighter interface (there are less wrong values that you can pass into this function)stricter error reporting: the assert enforces correct values being passed to the function. Breaking the assert condition gives a (runtime) error and tells the developer that it is the callers fault (assert guards preconditions!)Side effectsIn the previous example I have returned the digit word string instead of printing it to std::cout this reduces side effects and increases the reusability of the function. Lets say you want to have a GUI version of this program where the string is not presented on cout but in the window title. Using functions that return the result as a string makes this easy while using cout makes it hard (you would have to duplicate or rewrite the code). |
_softwareengineering.155648 | The probjem is that I have two sets of bugs top fix on the project. One to deploy in 5 days, and one to deploy in 10 days.I am going to solve all the bugs before the fifth day but I do not want to deploy the last 5 before the release date (in 10 days).How can I work on two separate codes and the merge all the modification?Is it possible?Do I have to create a branch? | svn usage advice | svn | Branching. Separate Branch for each bug (or batch of bug fixes), then you have complete control on when you merge back (ie release) the fixes. The book http://svnbook.red-bean.com/ is pretty good - work through that, or I'm sure there are lots of tutorials online. |
_codereview.115208 | I'm trying to shorten this piece of my code into a loop:<?php header('Access-Control-Allow-Origin: http://mysite.com'); ?><?php if(sizeof($_POST)) { file_put_contents; } else { echo ERROR! Must be activated from Tampermonkey script!; exit(); }file_put_contents(content.html, <strong> Updated last: . $_POST['date'] . </strong><br><br> .//Please add more entries depending on how many accounts you have configured<strong>Account 1</strong><br>( . $_POST['accountname1'] . ) . <br>CREDITS<br> . $_POST['credits1'] . <br>-<br> . <strong>Account 2</strong><br>( . $_POST['accountname2'] . ) . <br>CREDITS<br> . $_POST['credits2'] . <br>-<br> .<strong>Account 3</strong><br>( . $_POST['accountname3'] . ) . <br>CREDITS<br> . $_POST['credits3'] . <br>-<br> .<strong>Account 4</strong><br>( . $_POST['accountname4'] . ) . <br>CREDITS<br> . $_POST['credits4'] . <br>-<br> .<strong>Account 5</strong><br>( . $_POST['accountname5'] . ) . <br>CREDITS<br> . $_POST['credits5'] . <br>-<br> .<strong>Account 6</strong><br>( . $_POST['accountname6'] . ) . <br>CREDITS<br> . $_POST['credits6']); ?>Here's the JavaScript code I'm posting with:function bprs() { { var rowCount = $('#accountsTable tr').length; var accountsCount = rowCount -1; var accounts = []; for (var n = 1; n <= accountsCount; n++) { accounts[n] = { name: $('#accountName' + n).text(), credits: $('#credits' + n).text() }; } var date = new Date(); var data = date= + date + accounts.reduce(function (prev, account, n) { return prev + &accountname + n + = + account.name + &credits + n + = + account.credits; }, ''); $.ajaxPrefilter(function( options, originalOptions, jqXHR ) { options.async = true; }); $.ajax({ url: 'http://mysite.com/submit.php', // point to the php file here async:false, type: POST, dataType: json, data: data, success: function (result) { JSON.parse(result); }, error: function (xhr, ajaxOptions, thrownError) { console.log(xhr); } });Here's the post data my browser gives me: array(13) { [date]=> string(58) Sun Dec 27 2015 11:28:53 GMT-0700 (Mountain Standard Time) [accountname1]=> string(28) *****@gmail.com [credits1]=> string(3) 110 [accountname2]=> string(33) *****@gmail.com [credits2]=> string(3) 109 [accountname3]=> string(23) *****@gmail.com [credits3]=> string(3) 536 [accountname4]=> string(32) *****@outlook.com [credits4]=> string(3) 333 [accountname5]=> string(19) *****@gmail.com [credits5]=> string(3) 188 [accountname6]=> string(20) *****@gmail.com [credits6]=> string(2) 72 } What this does is post data from a web page to a PHP script on a server, then the script parses the data into an HTML file.As it stands right now, the script requires me to add a new entry when I create a new account and add it to the page.What I'd like is for my PHP page to generate the HTML code based on how many entries are in the post data. | PHP script for getting post data from Tampermonkey script | javascript;php | Alright. To simplify this I had to modify bprs a little bit:var date = new Date();var data = date= + date + &accountsnumber= + accountsCount + accounts.reduce(function (prev, account, n) { return prev + &accountname + n + = + account.name + &credits + n + = + account.credits; }, '');Then I modified my PHP to accept that value and used that number to figure out how many entries should be written to my html file.<?php header('Access-Control-Allow-Origin: http://mysite.com'); ?><?phpif (sizeof($_POST)) { load_contents();}else { echo ERROR! Must be activated from Tampermonkey script!; exit();}function load_contents(){ $accountnumber = $_POST['accountsnumber']; $str = '<strong>Updated last: ' . $_POST['date'] . '</strong><br /><br />'; for ($i = 0; $i < $accountnumber; $i++) { $identer = $i + 1; $str.= '<strong>Account ' . $identer . '</strong><br />(' . $_POST['accountname' . $identer] . ')' . '<br />CREDITS<br />' . $_POST['credits' . $identer] . '<br />-<br />'; } file_put_contents(content.html, rtrim($str, '<br />-<br />'));}?> |
_unix.151404 | How can I output first and last time of an access_log so that I can quickly check which time range access_log keep records between?Output may look like:[21/Aug/2014:06:29:41 -0400] :::: [21/Aug/2014:10:29:41 -0400]My access_log path is:/var/www/vhosts/example.com/statistics/logs/access_logExample Access Log Entry:123.123.123.123 - - [21/Aug/2014:08:12:30 -0400] GET /wp-content/themes/simple/comment-style.css HTTP/1.1 200 6221 http://example.com/?p=1 Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0 | Access Log Timespan | logs | If your log entries are not in strict chronological order, on a GNU system, you can do:# 1 2# 12345678901234567890# [21/Aug/2014:06:29:41 -0400]< access.log sed -n 's/^[^[]*\(\[[^]]*]\).*/\1/p' | sort -k1.9n -k1.5M -k1.2n -k1.14,1.21 | sed -n '1p;$p' | paste -sd -The result is probably going to be wrong one day per year upon the switch between summer time and winter time. |
_unix.337280 | I have an SSD I removed from a system. It had full disk encryption via LUKS (without using LVM).I want to reuse this drive for a different purpose (in a different system). I cloned (using dd) a non-encrypted Arch Linux system (which is known to be good and does boot) to this previously encrypted drive. However, the cloned drive will not boot. The dd command I used was:dd if=/dev/sda of=/dev/sdb bs=1M status=progress(I got the input and output devices correct too.) The disk I cloned from is back in its original hardware and it booted and runs fine. The new (cloned) disk is in identical hardware.The newly cloned disk has the same partition structure and the UUID's are the same (as expected). Furthermore, when I mount the new disk and browse through the directories, all files appear to be as expected. The newly cloned disk appears identical upon inspection and it is not obviously corrupted. For example, I can open and read the UEFI loader config files to inspect the UUID numbers. I can also run blkid to verify that the UUID's are correct (they are).Both systems use UEFI boot. The vfat EFI partition is on the newly cloned drive and it appears to be normal. As stated, the default loader config has the appropriate UUID (because nothing has changed from the drive that was cloned).The error upon trying to boot from the cloned disk is: :: running early hook udevstarting version 231:: running hook [udev]Waiting 10 seconds for device /dev.. (it lists the partition ID)ERROR: device [partition UUID] not found. Skipping fsck.ERROR: unable to find root device [partition UUID]You are being dropped into a rescue shellThen Arch drops into a rescue shell. EDIT:The cloned drive was connected to the system via USB. When I changed the connection to SATA, the problem went away. The drive works and the system boots as expected.I expected the cloned drive to work when mounted via USB because this system has already been tested to boot from a btrfs snapshot residing on a USB drive and that works without any issues. | cloned drive won't boot. (It was a LUKS encrypted drive) | luks;storage;disk encryption | Your system boots up to the point where it tries to find the root filesystem, and fails at that point. This is often a sign that the kernel is missing a necessary driver. As your system, like most non-embedded systems, uses an initramfs, kernel here means the set of drivers compiled in the kernel image (/boot/bzImage or wherever it's located) plus the set of drivers that are present on the initramfs. The necessary drivers include everything that's needed to access the filesystem: bus controller, disk controller, disk type, partition, software RAID layer, encryption layer, LVM, filesystem In your case, evidently the higher layers are present, but if you connected the disk to a different interface (say USB instead of SATA, or a different SATA port on a different controller, etc.) then maybe the driver for that interface is missing. You probably need to regenerate the initramfs.As it says on the Arch wiki:Boot succeeds on one machine and fails on another() If you transfer your /boot directory to another machine and the boot sequence fails during early userspace, it may be because the new hardware is not detected due to missing kernel modules. () try manually adding modules to the initramfs. |
_unix.163862 | I'd like to use find to report files under the following conditions:If the file contains the word SerializableThen report the file if it does NOT contain the wordserialVersionUIDSomething like: find . -name *.java -exec grep Serializable {} \; <magic stuff here> grep serialVersionUID {} \; -printSo am I smoking crack and would be better served by awk?Thanks for your help. | Using find to search and report files that have one but not two keywords inside | linux;awk;find | The -exec operand of find evaluates to true if the command succeeds (i.e. returns zero) and false if it fails (returns nonzero), so you can use the success/failure of grep as part of the expression used by find.Together with find's ! operand, which negates the following operand, you can search for files for which one grep command succeeds and another grep command fails:find . -name *.java \ -exec grep -q Serializable {} ; -a \ ! -exec grep -q serialVersionUID {} ; -a -printThe -q option tells grep not to print out anything; we're only interested in its return value.The -a operand isn't strictly required, but it doesn't slow things down and I like to use it when there's a possibility that the expression may grow even more complex and require -o or parentheses. |
_unix.167221 | Assume I let netcat listen on some port on PC1 (IP:10.0.0.1) with:PC1:~$ nc -l 9999I connect from PC2 (IP:10.0.0.2) and send some strings:PC2:~$ nc 10.0.0.1 9999 hello touchit test what's up touchit byeHow do I have to modify the the first command on PC1 such that the command 'touch test.txt' is run on PC1 whenever I send 'touchit' from PC2? It would be great to do that with a clever combinations of standard command and pipes. Of course, 'touch test.txt' could then be replaced by an arbitrary command. It would be extremely cool, if you could even launch different programswith different command strings sent from PC2. | Using netcat to launch a program? | netcat | null |
_softwareengineering.78807 | I have used a couple of the hosted SCM's like Unfuddle and Codespaces before and I like that they have Project Management tools built in. I've started using Mercurial and really like it, I would like to make the switch to it, but I can't seem to find any hosted mercurial solutions that contain project management tools.Does anyone know any hosted solutions that have mercurial repositories with project management solutions? Similar to Aseembla, CodeSpaces, Unfuddle, etc.I know there is BitBucket, but I don't see any project management tools.EDIT: Details about the types of tools I'm looking for.It is for a very small team, 2-5 people. Looking for Agile (or close to Agile) tools. For example, in CodeSpaces there is a card wall, Assembla has a robust ticketing system that you can create swim lanes in, etc. | Hosted Mercurial with Project Management tools | project management;version control;mercurial | FogBugz (Project Management) and Kiln (Mercurial Repository). Both made by Fog Creek. Some would say that FogBugz is only a bug tracking software but it is actually a PM tool if used correctly. There is actually a book on how to use it as a PM tool. The title of the book is Painless Project Management.The nice thing about these two tools is that they are completed integrated so that you can tie cases to check-ins, etc. |
_unix.238618 | How do I write a script that for each argument, the script should display the largest item in the directory along with its size. Something like this:[user]$ maxls /boot 2> /dev/null | sort -n1024 /boot/grub2/themes/stars8101 /boot/grub2/pic.png | Bash script to list items in directory by size | bash;shell script;disk usage | null |
_unix.313965 | I have set up a mailserver using Postfix, Dovecot as my SASL and Rainloop as my WebClient. I'm using MySQL (after asking my last question) for my user accounts and passwords, and it's working properly, but there are two issues that I'm facing with. [THE SECOND IS SOLVED]I cannot receive email! (I just need employees to be in touch via email, they cannot receive any email at the moment, when I send email from one employee to the other, I can find no log file showing a sign of failure, I really have no idea what might be an issue for not being able to receive.)[SOLVED] Users can login via ThunderBird since it'll ask for confirmation on Certificate for both SMTP and IMAP. i.e. when I'm logging in, I should accept the certificate, and the first time I'm sending a mail, I should accept another certificate, and then it will work. But Outlook cannot log in since it's only asking certificate once and for IMAP.Here is my config files:/etc/postfix/main.cfmyhostname = mail.domain.tldmydomain = domain.tldmyorigin = $mydomaininet_interfaces = allinet_protocols = allmydestination = $myhostname, localhost.$mydomain, localhost, $mydomain#home_mailbox = Maildir/#relayhost =#mynetworks = 127.0.0.0/8, 172.16.67.68, [::1]/128smtpd_tls_cert_file=/etc/ssl/certs/mailcert.pemsmtpd_tls_key_file=/etc/ssl/private/mail.keysmtpd_use_tls=yessmtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scachesmtp_tls_session_cache_database = btree:${data_directory}/smtp_scachesmtpd_tls_security_level=may#smtpd_tls_protocols = !SSLv2, !SSLv3smtpd_sasl_type = dovecotsmtpd_sasl_path = private/authsmtpd_sasl_auth_enable = yes#smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks# reject_unauth_destination#alias_maps = hash:/etc/aliases#alias_database = hash:/etc/aliasesvirtual_transport = lmtp:unix:private/dovecot-lmtpvirtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cfvirtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cfvirtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf, mysql:/etc/postfix/mysql-virtual-email2email.cfmailbox_size_limit = 209715200message_size_limit = 57671680/etc/postfix/master.cfsmtp inet n - n - - smtpdpickup unix n - n 60 1 pickupcleanup unix n - n - 0 cleanupqmgr unix n - n 300 1 qmgr#qmgr unix n - n 300 1 oqmgrtlsmgr unix - - n 1000? 1 tlsmgrrewrite unix - - n - - trivial-rewritebounce unix - - n - 0 bouncedefer unix - - n - 0 bouncetrace unix - - n - 0 bounceverify unix - - n - 1 verifyflush unix n - n 1000? 0 flushproxymap unix - - n - - proxymapproxywrite unix - - n - 1 proxymapsmtp unix - - n - - smtprelay unix - - n - - smtp# -o smtp_helo_timeout=5 -o smtp_connect_timeout=5showq unix n - n - - showqerror unix - - n - - errorretry unix - - n - - errordiscard unix - - n - - discardlocal unix - n n - - localvirtual unix - n n - - virtuallmtp unix - - n - - lmtpanvil unix - - n - 1 anvilscache unix - - n - 1 scachesubmission inet n - - - - smtpd -o syslog_name=postfix/submission -o smtpd_tls_wrappermode=no -o smtpd_tls_security_level=encrypt -o smtpd_sasl_auth_enable=yes -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject -o milter_macro_daemon_name=ORIGINATING -o smtpd_sasl_type=dovecot -o smtpd_sasl_path=private/authsmtps inet n - n - - smtpd -o syslog_name=postfix/smtps -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes -o smtpd_client_restrictions=permit_sasl_authenticated,reject -o milter_macro_daemon_name=ORIGINATINGI have 3 DB tables, virtual_domains, virtual_users, virtual_aliases. Postfix knows all of them, and it's been proven by using postmap commands, and the configs are set in mysql-virtual-mailbox-domains.cf, mysql-virtual-mailbox-maps.cf, mysql-virtual-email2email.cf, mysql-virtual-alias-maps.cf./etc/dovecot/dovecot.confdisable_plaintext_auth = yesssl=requiredssl_cert = </etc/ssl/certs/mailcert.pemssl_key = </etc/ssl/private/mail.key!include conf.d/*.conf# A config file can also tried to be included without giving an error if# it's not found:!include_try local.confuserdb { driver = static args = uid=vmail gid=vmail home=/var/mail/vhosts/%d/%n}passdb { driver = sql args = /etc/dovecot/dovecot-sql.conf.ext}service auth { unix_listener /var/spool/postfix/private/auth { group = postfix mode = 0660 user = postfix }}protocol imap { mail_plugins = autocreate# $mail_plugins = autocreate}plugin { autocreate = Trash autocreate2 = Sent autosubscribe = Trash autosubscribe2 = Sent}/etc/dovecot/conf.d/auth-sql.conf.extpassdb { driver = sql args = /etc/dovecot/dovecot-sql.conf.ext}userdb { driver = static args = uid=vmail gid=vmail home=/var/mail/vhosts/%d/%n}/etc/dovecot/conf.d/10-mail.confnamespace inbox { # Namespace type: private, shared or public #type = private # Hierarchy separator to use. You should use the same separator for all # namespaces or some clients get confused. '/' is usually a good one. # The default however depends on the underlying mail storage format. #separator = # Prefix required to access this namespace. This needs to be different for # all namespaces. For example Public/. #prefix = # Physical location of the mailbox. This is in same format as # mail_location, which is also the default for it. #location = # There can be only one INBOX, and this setting defines which namespace # has it. inbox = yes # If namespace is hidden, it's not advertised to clients via NAMESPACE # extension. You'll most likely also want to set list=no. This is mostly # useful when converting from another server with different namespaces which # you want to deprecate but still keep working. For example you can create # hidden namespaces with prefixes ~/mail/, ~%u/mail/ and mail/. #hidden = no # Show the mailboxes under this namespace with LIST command. This makes the # namespace visible for clients that don't support NAMESPACE extension. # children value lists child mailboxes, but hides the namespace prefix. #list = yes # Namespace handles its own subscriptions. If set to no, the parent # namespace handles them (empty prefix should always have this as yes) #subscriptions = yes}mbox_write_locks = fcntlmail_location = maildir:/var/mail/vhosts/%d/%nmail_privileged_group = mailI'm open to any suggestion, even if it's starting from the scratch. But please be precise and explain in detail, I'm not an expert in setting up mail servers. Thanks in advance.If anything else is needed, let me know and I will update the question with the required config files.UPDATE:Guys, I have no idea why I cannot receive Email while everything seems to be correct, can anyone help? Any idea?? | Mail Server send/receive issues | centos;email;postfix;thunderbird;imap | null |
_webapps.55372 | I have admin rights for Google Apps on our domain. Recently an employee left the firm. Rather than delete his Google account, I just disabled his rights to use GMail. This worked. His account can no longer be used to access GMail. Yet when I send mail to his GMail account, I don't receive a bounce-back (NDR - non-deliverable). Why is this? I'd prefer that those who send email to this old account get a bounce-back so they don't assume that their email was delivered successfully. Any ideas? | Why don't emails targeting disabled GMail account bounce (NDR) to sender? | gmail;google apps email;email bounces | Removing access is not the same as removing the email. The email account still exists, they just can't access it. So emails are collecting in the inbox. If you enable access and log in, you will see them. To get a message to bounce, you have to remove the email account entirely. If you managed your own mailbox server, for example Postfix, then you could probably set an option or filter to bounce even if the account existed. However, for web-based mail, you won't have that level of control. |
_cogsci.9402 | I have just started to work on problems in neuroscience on my own. I sought to analyze the P300 response from EEG data because I was trying to understand a Kaggle.com challenge that used it. I found a few available datasets online, a couple of which were from BCI competitions, but have not been able to successfully separate the signals with the P300 response from those without the response. So far, I have subtracted the average of a channel from the channel and run a bandpass filter on the data. This seems to produce good looking data, but looking for the associated event related potential (ERP) leads to inclusive results.It appears that the data from the BCI competition may not be easy to analyze, but it is the most documented P300 response with available data that I can find. That said, some of the techniques used involve mathematical functions such as principal component analysis (PCA), linear discriminant analysis (LDA), and T-weights to find the signal and classify and analyze it. I am aware of references available for these mathematical techniques but not in the context of neuroscience.Furthermore, I am aware that there are some EEG analysis toolboxes for Python, but it is more important for me to understand the data than to feed it through a black box. Also, I have found these toolboxes rather undocumented. | What are some good references for preprocessing and analysis of the P300 response from EEG data in Python? | theoretical neuroscience;eeg;mathematical psychology;signal detection;p300 | null |
_codereview.55622 | In this problem you are given input of phone numbers and you are supposed to determine whether any number is the prefix of another. I have an addchild method that returns true or false if a given string can be inserted and is not a prefix of another string. How could I improve the efficiency of my code so that I could pass the time constraints?http://www.spoj.com/problems/PHONELST/import java.util.Arrays;import java.util.Scanner;class PhoneList {static class Node{ Node [] children; int value; public Node(){ children=new Node[11]; } public Node(int value){ children=new Node[11]; this.value=value; }}static class Trie{ Node root=null; public Trie(){ root=new Node(); } boolean addChild(String s){ Node currentNode=root; int number=0; for(int i=0;i<s.length();i++){ number=s.charAt(i)-'0'; if(currentNode.children[currentNode.children.length-1]!=null){ return false; } if(currentNode.children[number]==null){ currentNode.children[number]=new Node(number); } currentNode=currentNode.children[number]; } if(currentNode.children[currentNode.children.length-1]==null){ currentNode.children[currentNode.children.length-1]=new Node(10); }else{ return false; } return true; }}public static void main(String[] args) { Scanner input=new Scanner(System.in); int number_of_test_cases=input.nextInt(); boolean istrue; for(int i=0;i<number_of_test_cases;i++){ Trie tree=new Trie(); int length=input.nextInt(); String numbers[]=new String[length]; for(int j=0;j<numbers.length;j++){ numbers[j]=input.next(); } Arrays.sort(numbers); istrue=true; for(int k=0;k<numbers.length;k++){ if(!tree.addChild(numbers[k])){ System.out.println(NO); istrue=false; break; } } if(istrue){ System.out.println(YES); } }}} | Trie SPOJ Problem - PhoneList TLE | java;optimization;algorithm;strings;trie | null |
_unix.126393 | I am using Linux mint 16 cinnamon. After my last upgrade free disk space dropped from 4.2GB to around 344MB. Don't know what happened. This is the output of df -hFilesystem Size Used Avail Use% Mounted on/dev/sda10 10G 9.1G 329M 97% /none 4.0K 0 4.0K 0% /sys/fs/cgroupudev 1.7G 4.0K 1.7G 1% /devtmpfs 345M 1.4M 344M 1% /runnone 5.0M 0 5.0M 0% /run/locknone 1.7G 1.3M 1.7G 1% /run/shmnone 100M 28K 100M 1% /run/userHow can I clear all the temporary files and folders.Contents of var/log/dpkg.log for last upgrade are here: dpkg.log | I get low disk space warning after my last upgrade | linux mint;upgrade;disk usage;cinnamon | null |
_webmaster.39330 | 301 Wildcard. I don't think I am doing it right. Need domain1.com/keyword5 to go to domain2.com/keyword5. Instead it does this:www.domain1.com/keyword5 goes to www.domain2.com (tld, root, not the keyword5 directory)Here is my .htaccess:RewriteCond %{HTTP_HOST} ^domain1\.com$ [OR]RewriteCond %{HTTP_HOST} ^www\.domain1\.com$RewriteRule ^(.*)$ http\:\/\/www\.domain2\.com\/$1 [R=301,L]PS: Can I do multiple domains on the same .htaccess? For example, I have 3 domains on the same public_html, can I 301 each of them like this? | 301 Redirect not behaving like I am wanting it too. What is my mistake? | seo;301 redirect;drupal | null |
_datascience.14326 | I am trying to compute Silhouette with k-means. However I have the value really close to 0 and the clusters are very clearly separated. Do you know where can be the problem? This is the code:n_samples, n_features = data.shapen_digits=2labels=data[:,-1]data=data[:,:-1]sample_size = 300print(n_digits: %d, \t n_samples %d, \t n_features %d % (n_digits, n_samples, n_features))print(79 * '_')print('% 9s' % 'init' ' time inertia homo compl v-meas ARI AMI silhouette')def bench_k_means(estimator, name, data): t0 = time() estimator.fit(data) print('% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f %.3f' % (name, (time() - t0), estimator.inertia_, metrics.homogeneity_score(labels, estimator.labels_), metrics.completeness_score(labels, estimator.labels_), metrics.v_measure_score(labels, estimator.labels_), metrics.adjusted_rand_score(labels, estimator.labels_), metrics.adjusted_mutual_info_score(labels, estimator.labels_), metrics.silhouette_score(data, estimator.labels_, metric='euclidean', sample_size=sample_size))) pca = PCA(n_components=n_digits).fit(data)bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1), name=PCA-based, data=data)print(79 * '_')The obtained Silhouette is 0.052 and this is the obtained k-means clustering.Thanks,Laia | Silhouette calculation in k-means | python;clustering;scikit learn;k means | null |
_scicomp.27292 | I have an image that looks like this (it might appear low res in a browser because it is 16 MB). This image was taken with a scanning electron microscope, but because the equipment is outdated there is a lot of noise within the image. What I would like to do is develop a program (in Java) that would take this image as an input and try to remove the noise as much as possible to produce a high quality image. However, being a beginner in the field of image/signal processing, I have no idea where to begin researching techniques. I was wondering if you guys had any good starting points for me to look into, or perhaps de-noising algorithms/techniques that I could research to potentially help me reach my goal. | Which technique to use for signal/image processing or noise removal? | image processing;signal processing | null |
_unix.33961 | How can I assign two or more IPv6 address on one NIC. I tried Google but no luck. I've done it with ipv4 but ipv6 can not. | How do I setup two or more IPv6 address on one NIC in FreeBSD? | freebsd;ipv6 | I tried a search for freebsd ip tools ipv6. I found instruction at http://www.kame.net/~suz/freebsd-ipv6-config-guide.txt.method 1) completely static configuration like IPv4Linklocal prefix (fe80:....) is automatically generated, so you don't have to configure it.-------/etc/rc.conf---------ipv6_network_interfaces=fxp0ipv6_ifconfig_fxp0=3ffe:501:ffff:2::1 prefixlen 64ipv6_ifconfig_fxp0_alias0=2001:ffff:0:2::2 prefixlen 64ipv6_defaultrouter=fe80::1%fxp0---------------------------- |
_unix.369968 | I was using the default vim colorscheme, and one day when I turned on my computer, suddenly everything was a really weird theme with a red background and yellow/white text (I'm not even sure if this is even a colorscheme?) My ~/.vimrc contains colo evening but vim files still open with the red colorscheme. How can I fix this? | Vim won't use default colorscheme | rhel;vim;colors;vimrc | null |
_codereview.78070 | I have made a merge sort algorithm but am unsure of the 'Space Usage' of the algorithm.public class Sorting { public static void mergeSort(int[] arr) { if (arr.length == 1) { return; } int[] newArrLeft = new int[arr.length / 2]; int[] newArrRight = new int[arr.length - (arr.length / 2)]; int currentRight = 0; for (int i = 0; i < arr.length; i++) { if (i < arr.length / 2) { newArrLeft[i] = arr[i]; } else { newArrRight[currentRight++] = arr[i]; } } mergeSort(newArrLeft); mergeSort(newArrRight); merge(newArrLeft, newArrRight, arr); } private static void merge(int[] arrLeft, int[] arrRight, int[] sortedValuesArr) { int currentLeft = 0; int currentRight = 0; int currentSorted = 0; while (currentLeft < arrLeft.length && currentRight < arrRight.length) { if (arrLeft[currentLeft] < arrRight[currentRight]) { sortedValuesArr[currentSorted++] = arrLeft[currentLeft++]; } else { sortedValuesArr[currentSorted++] = arrRight[currentRight++]; } } while (currentLeft < arrLeft.length) { sortedValuesArr[currentSorted++] = arrLeft[currentLeft++]; } while (currentRight < arrRight.length) { sortedValuesArr[currentSorted++] = arrRight[currentRight++]; } }}I am specifically inquiring about:int[] newArrLeft = new int[arr.length / 2];int[] newArrRight = new int[arr.length - (arr.length / 2)];int currentRight = 0;for (int i = 0; i < arr.length; i++) { if (i < arr.length / 2) { newArrLeft[i] = arr[i]; } else { newArrRight[currentRight++] = arr[i]; }}Is the above code wasting space? Is there a better implementation? | Merge Sort Implementation: Space Usage | java;algorithm;sorting;mergesort | Is the above code wasting space?Yes. As @cHao pointed out in a comment, you are using \$O(N log N)\$ space. You can do mergesort in \$O(N)\$ space.Is there a better implementation?Yes. The biggest problem wrt both time and space efficiency is that you are unnecessarily allocating and copying auxiliary arrays.You can instead create 1 auxiliary array and pass the same array around together with the interval to be sorted, or merged.Your methods would look like these, some implementation left exercise :public static void mergeSort(int[] arr) { mergeSortBetween(arr, new int[arr.length], 0, arr.length -1);}private static void mergeSortBetween(int[] arr, int[] aux, int startIndex, int endIndex) { if (...) { return; } //... mergeSortBetween(arr, aux, startIndexLeft, endIndexLeft); mergeSortBetween(arr, aux, startIndexRight, endIndexRight); merge(arr, aux, startIndexLeft, endIndexLeft, startIndexRight, endIndexRight);}private static void mergeBetween(int[] arr, int[] aux, int startIndexLeft, int endIndexLeft, int startIndexRight, int endIndexRight) { // only need to merge consecutive chunks assert startIndexRight = endIndexLeft + 1; //merge into aux while (currentLeft < startIndexLeft && currentRight < endIndexRight) { if (...) aux[...] = arr[...] else aux[...] = arr[...] } while (currentLeft < endIndexLeft) { aux[...] = arr[...] } while (currentRight < endIndexRight) { aux[...] = arr[...] } //copy merged values back into arr System.arraycopy(aux, ..., arr, ..., ...);} |
_cs.30101 | I have a table that contains only bits. I would like to be able to do the following two queries:SET any bit to 0 or 1;GET the number of bits that are set to 1 from the beginning of the table up to a specifique index i.Is there a data structure that is more efficient than a binary indexed tree, i.e. a Fenwick tree? A binary indexed tree performs both operations in $O(\log n)$ time, where $n$ is the number of elements.For practical info, my tables are really large, containing up to millions of elements. | Data structure for counting bits set on a table | algorithms;data structures;trees | If one of the operations is much more common, you could use an array of bits resp. of counts, so the common operation can be done in $O(1)$ at the cost of the other operation taking $O(n)$.If you can't make such an assumption, then I don't think there is anything better than the $O(\log n)$ of the BIT. |
_codereview.115125 | I wrote the following to check whether a string ends with a second string.function isEndOf(origin, target) { return (origin.substr(target.length * -1, target.length) === target);}Usage:isEndOf(A long time ago in a galaxy far, far away, far away)This takes a substring with the size of the target string counting from the end of the string and checks whether it's equal to the target string. Quite straightforward. However, I'm concerned about my usage of target.length * -1. This smells like using the wrong method altogether.Is there a more idiomatic approach for writing such a basic function? Would slicing be more appropriate? The naming can probably be improved. | Check whether string ends with string | javascript;strings | There's no need for the 2nd argument in substr. So you could just do:origin.substr(target.length * -1) === targetororigin.slice(target.length * -1) === targetSame deal.Edit: Whoops. Actually it's not quite the same deal. As Sumurai8 commented on Simon's answer, MDN says that JScript does not handle negative offsets for substr. However, slice has no such caveat. So long story short: Use slice, not substr.Instead of * -1, you could also use a unary minus:origin.slice(-target.length) === targetOne thing you might want, though, is to check target before you try accessing its length property. If target == undefined you'll get an error. Something simple like this should do:if(!target) return false;One gotcha though: It'll return false if target is an empty string, since empty strings are false'y. However, it doesn't really make much sense to check if string ends with an empty string, so perhaps that's fine? Otherwise, do a typeof check (like the one below) on target.And you might want to check origin too. However, here you just want to check that it's a string - not if it's just false'y. You'll be calling slice on it, so it must be a string or you'll get an error, whereas the worst that can happen if target isn't a string (but is truth'y) is that target.length is undefined.So to check origin do:if(typeof origin !== 'string') return false;By the way, without the target-is-false'y check, if target is a string but also empty, you'll get some tricky results:Origin Target Result==========================================foo false foo false trueResults #2 makes sense, but results #1 and #3 are perhaps a little strange, because, again, what does it mean to have an string end with an empty string? The results are due to slice(-0) being the same as slice(0), i.e. returning the whole string. So in effect you're checking:foo.slice(0) == // => foo == (false).slice(0) == // => == (true)Kinda confusing.If you want an empty target string to always return true, you could do:if(typeof origin !== 'string') return false;if(typeof target !== 'string') return false;if(!target) return true;I'm aware my code has a lot of white-space for JavaScript standards. I like to think it keeps code readable. The naming can probably be improved.Whitespace seems just fine to me! Don't know what JS you're used to, but I see absolutely no reason to change anything about whitespace usage.I would drop the outer parentheses though, like Simon suggested.As for naming, I'd call it endsWith, or stringEndsWith.You could also extend the String prototype with an endsWith method, but generally it's better to leave native prototypes alone. However, this is fairly harmless, so I'd be tempted to say:if(!String.prototype.endsWith) { String.prototype.endsWith = function (ending) { if(typeof ending !== 'string') return false; if(!ending) return true; return this.slice(-ending.length) === ending; };}Here we can skip checking origin, because we're adding the method to String itself. So if it's called, it's called on a string. |
_datascience.20296 | Suppose I build a NN for classification. The last layer is a Dense layer with softmax activation. I have five different classes to classify. Suppose for a single training example, the true label is [1 0 0 0 0] while the predictions be [0.1 0.5 0.1 0.1 0.2]. How would I calculate the cross entropy loss for this example? | Cross-entropy loss explanation | machine learning;deep learning | Cross entropy formula given two distributions over discrete variable $x$, where $q(x)$ is the estimate for true distribution $p(x)$ is given by$$H(p,q) = -\sum_{\forall x} p(x) log(q(x))$$For a neural network, the calculation is independent of these parts:What kind of layer was used.What kind of activation you use - although many activations will not be compatible with the calculation, because it will produce nonsense values if the sum of probabilities is not equal to 1. Softmax is often used for multiclass classification because it guarantees a well-behaved probability distribution function.For a neural network, you will usually see the equation written into a form where $\mathbf{y}$ is the ground truth vector and $\mathbf{\hat{y}}$ (or some other value taken direct from the last layer output) is the estimate, and it would look like this for a single example:$$L = - \mathbf{y} \cdot log(\mathbf{\hat{y}})$$Where $\cdot$ is vector dot product.Your example ground truth $\mathbf{y}$ gives all probability to the first value, and the other values are zero, so we can ignore them, and just use the matching term from your estimates $\mathbf{\hat{y}}$$L = -(1\times log(0.1) + 0 \times log(0.5) + ...)$$L = - log(0.1) \approx 2.303$An important point from commentsThat means, the loss would be same no matter if the predictions are $[0.1, 0.5, 0.1, 0.1, 0.2]$ or $[0.1, 0.6, 0.1, 0.1, 0.1]$? Yes, this is a key feature of multiclass logloss, it rewards/penalises probabilities of correct classes only. The value is independent of how the remaining probability is split between incorrect classes.More commonly you will see this equation averaged over all examples:$$L = - \frac{1}{N}(\sum_{i=1}^{N} \mathbf{y_i} \cdot log(\mathbf{\hat{y}_i}))$$Many implementations will require your ground truth values to be one-hot encoded (with a single true class), because that allows for some extra optimisation. However, in principle the cross entropy loss can be calculated - and optimised - when this is not the case. |
_webmaster.67928 | I seem to be unable to access the data highlighter in Google Webmaster Tools since I attempted to start a new highlight on a page.Clicking the red Start Highlighting button to open the tagger did nothing, so I refreshed. Now, the page loads without the middle content section, then a few seconds later shows the following error: Failed to load data, please try again later.I can't get any of the middle section to load, even the list of current pages/page sets that have been highlightedthis error shows.I thought it may be a Google service outage, but other sites' data highlighters work fine. It also seems coincidental that it stopped working after I attempted to start highlightingI was able to list the existing pages and page sets fine before that, and still am able to access the service on other sites.I've tried clearing browser data and have tried Google Chrome as wellsame problem.What's happened? | Google Webmaster Tools Data Highlighter says Failed to load data, please try again later | google search console | This problem has been reported many times in the Google Product Forums:Data Highlighter Tool 'Failed to load data, please try again later' shows repeatedly when using the Data Highlighter toolData Highlighter - Failed to load data, please try again later.FAILED TO LOAD DATA MESSAGE FOR DATA HIGHLIGHTERData Highlighter: failing to load data 'Failed to load data, please try again later' shows repeatedly when using the Data Highlighter tool.It would appear to be a bug on Google's side.It has been confirmed by multiple people.It happens only some of the time.Google has not published a valid workaround or fixNone of those threads have any solutions to the problem. Some people report that the following may have solved the issue for them, but none of these works consistently:Clear the browser cacheSwitch to a different browserTry again another dayTry those possible workarounds, but other than that, it appears that Google needs to fix something on their end. If you believe that you can provide additional details to Google to help them to fix this problem, then please do so in the product forums. |
_reverseengineering.15181 | I am struggling with a stripped binary, and I would like to visualize the main() function with the VVV command (ascii-art CFG representation).Usually, the steps are the following:#> r2 ./crackme (run radare2 on the crackme).[0x00005430]> aaa (start the analysis of the binary).s main (seek to the address of main).VVV (switch to the CFG view of the binary).Unfortunately, my crackme is stripped (including the main() function). I can see the address of the main() function thanks to the first argument of the __libc_start_main() function. But, I always end-up with the following error message: Not in a function. Type 'df' to define it here--press any key--How can I work around this problem. For example, I first tried to add my own symbols on the binary to mark the start of the main() function, but I miserably failed... Any idea ?EDITHere is my attempt to add a flag to the binary:#> r2 ./ch23.bin [0x000083b8]> aaa[x] Analyze all flags starting with sym. and entry0 (aa)[ ] [aav: using from to 0x8000 0x8e64Using vmin 0x8000 and vmax 0x10880aav: using from to 0x8000 0x8e64Using vmin 0x8000 and vmax 0x10880[x] Analyze len bytes of instructions for references (aar)[x] Analyze function calls (aac)[ ] [*] Use -AA or aaaa to perform additional experimental analysis.[x] Constructing a function name for fcn.* and sym.func.* functions (aan))[0x000083b8]> pdf ;-- section_end..plt: ;-- section..text:/ (fcn) entry0 44| entry0 ();| ; UNKNOWN XREF from 0x00008018 (unk)| ; UNKNOWN XREF from 0x00008c18 (unk)| 0x000083b8 00b0a0e3 mov fp, 0 ; [14] va=0x000083b8 pa=0x000003b8 sz=800 vsz=800 rwx=--r-x .text| 0x000083bc 00e0a0e3 mov lr, 0| 0x000083c0 04109de4 pop {r1}| 0x000083c4 0d20a0e1 mov r2, sp| 0x000083c8 04202de5 str r2, [sp, -4]!| 0x000083cc 04002de5 str r0, [sp, -4]!| 0x000083d0 10c09fe5 ldr ip, [0x000083e8] ; [0x83e8:4]=0x8664| 0x000083d4 04c02de5 str ip, [sp, -4]!| 0x000083d8 0c009fe5 ldr r0, [0x000083ec] ; [0x83ec:4]=0x8470| 0x000083dc 0c309fe5 ldr r3, [0x000083f0] ; [0x83f0:4]=0x8668\ 0x000083e0 e5ffffeb bl sym.imp.__libc_start_main; int __libc_start_main(func main, int argc, char **ubp_av, func init, func fini, func rtld_fini, void *stack_end);[0x000083b8]> f main @ 0x8470[0x000083b8]> s main[0x00008470]> VVV... miserable fail ... | How to add a function symbol to a stripped executable with radare2? | disassembly;radare2 | null |
_softwareengineering.228345 | I need a simple enum declaring the Java reference types, as:public enum ReferenceType { STRONG, SOFT, WEAK, PHANTOM;}Does such enum exist somewhere in the Java API or a general utility library such as Guava ? I have not been able to find it in either place, although I found third party projects that declare it (e.g. google-guice: RefrenceType).I just try to avoid polluting my project with silly classes/enums that may exist somewhere else.Since asking this question, I found that Guava in fact used to have this, but they dropped it: Issue 1662: Feature request for enum of reference types | enum for Java reference types | java | You can find one in hibernate ReferenceType though it only contains STRONG, SOFT and WEAK but not PHANTOM.There are few others ReferenceType in eclipse net4j and Link.Type in true commons. But I think you will be better without them in case you want some modification later. |
_unix.77734 | I'm using Lubuntu 13.04 with its default window manager, Openbox. Is there a way to edit ~/.config/openbox/lubuntu-rc.xml to combine the following two keybinds in the keyboard section into one?<!-- Launch gedit --><keybind key=W-g> <action name=Execute> <command>gedit</command> </action></keybind>and <!-- Undecorate --><keybind key=C-S-d> <action name=Undecorate/></keybind>In other words, I'd like to open gedit without window decorations.I know I can have the same result by retaining the first keybind as it is and having the following entry in the applications section of lubuntu-rc.xml:<application name=gedit type=normal> <decor>no</decor></application> | Can I combine two keybinds into one in Openbox? | openbox | It is possible to combine two keybinds into one but a better way to express it would be to want to combine two actions under one keybind.However, in the specific case I described, there is a problem. Let's say I have one text editor, Leafpad, open. And Leafpad is decorated. While Leafpad is in focus, I run:<!-- Launch gedit --><keybind key=W-g> <action name=Execute> <command>gedit</command> </action> <action name=Undecorate/></keybind>What happens is this: Gedit opens but is still decorated but the Leafpad window becomes undecorated. The explanation was provided by folks here and here. From my understanding of the replies, it appears that Openbox executes both the commands but since Gedit takes a while the second command is executed first (on the active window). Another point is that Gedit does not have any provision built-in to be launched undecorated by means of --undecorated or something equivalent. |
_webmaster.38498 | My application is provided as a service that is embedded in other sites. I have google analytics installed on the login popup dialog which is a page of my application, which is opened from the host site (OAuth).About a week ago, I've noticed a sharp decrease in the number of new users registrations and a jump in the bounce rate (from ~30% to ~80%).This happened without any change in the application. I looked into technical parameters like page load time and error rates, but could not see any change in there.Any ideas what can cause this behavior? | My application's bounce rate jumped from 30% to 80% overnight | google analytics;bounce rate | null |
_datascience.20297 | I am applying H2o autoencoder for anomaly detection for multivariate time series data. I have many time series data for different metrics of network elements which are recorded every 15 minutes. I want to find out that:At which timestamp that the anomaly happensWhat is/are the main metric(s) causing the anomalyI form the data matrix with columns as metrics and rows as the values of the metrics at a specific timestamp. For example, [[9:15, v1, v2, v3...], [9:30, v4, v5, v6, ...], ...]. I then train the data with autoencoder and use h2o.anomaly to check which data points have reconstruction MSE greater than the 99% percentile as the suspected anomalies. And these give me the timestamp when the possible anomalies happen.By using this method, can I get the information of the main metrics causing the anomaly?Thanks in advance. | H2o autoencoder anomaly detection for multivariate time series data | time series;anomaly detection;autoencoder | null |
_vi.5543 | I have trouble with one specific folding expression, s1. The documentation (:h fold-expr) says:s1, s2, .. subtract one, two, .. from the fold level of the previous lineHowever this is not true for me. Create a file .vim/after/ftplugin/vim/test.vim/ with the following content: This is a demo, the fold starts here. This line has foldlevel 1 This line is folded wrong, it should have foldlevel 0, but has foldlevel 1function! VimFolds(lnum) let thisline = getline(a:lnum) if match(thisline, '^') >= 0 return '>1' elseif match(thisline, '^ ') >= 0 return 's1' else return '=' endifendfunctionsetlocal foldmethod=exprsetlocal foldexpr=VimFolds(v:lnum)set foldcolumn=3set foldminlines=0Open the file with Vim, it should be folded according to its own rules. The second line should be on foldlevel 0 according to documentation, but is on foldlevel 1.Am I understanding something wrong here on how to use this? | fold-expr not working as expected | folding | This is a demo, the fold starts here. This line has foldlevel 1 This line is folded wrong, it should have foldlevel 0, but has foldlevel 1function! VimFolds(lnum) let thisline = getline(a:lnum) if thisline =~ '^' return '>1' elseif thisline =~ '^ ' return foldlevel(a:lnum-1)-1 else return foldlevel(a:lnum-1) endifendfunctionset foldmethod=exprset foldexpr=VimFolds(v:lnum)set foldcolumn=3set foldminlines=0I don't know how to make the 's1' value work as intended either.However the code above seems to do what you want. |
_cogsci.15388 | Given: a brain cell has an average temperature, T.If: perpetual brain activity pattern, X ; has an average conductive resistance, R;Therefore:Could it be rationally assumed that activity pattern X, increases T, by a factor of R? | Brain cell temperature | neurobiology;measurement;cognitive modeling | null |
_softwareengineering.347495 | I have a web site with several web pages.Each page requires some JavaScript: i.e. different JavaScript for different pages, which some JavaScript that's common to every page.Some of the JavaScript is long (e.g. 4000 lines of code).I coded the JavaScript using the basic Module Export pattern described in Adequately Good's JavaScript Module Pattern: In-Depth article.Anyway, now I'm thinking of using a JavaScript minifier to:Combine several the JavaScript source files into oneInclude that same, single JavaScript source file on every web pageI hope that doing this would solve two problems:At design time, it's easy to reuse existing JavaScript modules (because the existing modules must be designed as reusable modules, included on and therefore available on every web page)At run-time, it's performant: because the user's browser (which includes mobile browsers) only has one JS source file to download; and that file is presumably already cached in the browser when it loads a second or a third web page (i.e. any page except the first).Is this a reasonable thing to do? Is it normal, or is it a WTF thing to do? Are there disadvantages I should consider, and are they significant?I hesitate because it implies code being loaded into a page, which isn't required by that page. OTOH that's probably what happens when you load any 3rd-party JavaScript library (i.e. you load the whole library but don't use all its functionality). | Same JavaScript on different web pages | javascript;web development;modules | null |
_webapps.80620 | I'm trying to make my location history more accurate.In the old Location History I had a chance to click on specific coordinates and remove them. (I find it that my phone reports inaccurate locations to Google's servers quite often, especially when I use the subway or when there are Wi-Fi hotspots nearby which don't have a fixed position.)Is there a way to still remove specific coordinates? | How can I remove a location which is not a place from my Google Timeline? | google maps | Go to your Location TimelineNavigate to the date you want to changeFind the stop you want to remove; click the action menu (three vertical dots)Choose Remove stop from dayThe map will still show you were in the area, but it won't call out that stop specifically. |
_cstheory.25868 | Given the symmetry group $S_n$ and two subgroups $G, H\leq S_n$, and $\pi\in S_n$, does $G\pi\cap H=\emptyset$ hold?As far as I know, the problem is known as the coset intersection problem. I am wondering what's the complexity? In particular, is this problem known to be in coAM?Moreover, if $H$ is restricted to be abelian, what does the complexity become? | Complexity of the coset intersection problem | cc.complexity theory;graph isomorphism;gr.group theory | Moderately exponential time and $\mathsf{coAM}$ (for the opposite of the problem as stated: Coset Intersection is typically considered to have a yes answer if the cosets intersect, opposite of how it's stated in the OQ.)Luks 1999 (free author's copy) gave a $2^{O(n)}$-time algorithm, while Babai (see his 1983 Ph.D. thesis, also Babai-Kantor-Luks FOCS 1983, and a to-appear journal version) gave a $2^{\tilde{O}(\sqrt{n})}$-time algorithm, which remains the best known to date. Since graph isomorphism reduces to quadratic-sized coset intersection, improving this to $2^{\tilde{O}(n^{1/4-\epsilon})}$ would improve the state of the art for graph isomorphism. |
_codereview.71143 | Earlier this academic year I had an assignment to take a project I had written outside the context of University and apply a number of refactorings to it.I chose a program I had written a while ago that saves periodic 24-bit lossless bitmap screenshots of a user-specified target window.BMPTimer Class:// Header for BMPTimer#pragma once#include <Windows.h>#include BMPWriter.h/** * BMPTimer class - a timer for periodically saving screenshots of a specified window. */class CBMPTimer{private: int ticks_so_far; // New variable added with refactor #3 - keeps track of ticks made by our timer int ms_interval; // Inteval between clicks HWND hwTarget; // Target window HANDLE hThread; // Thread for timer tick LPVOID thistimer; // Pointer to this class instance static bool timeractive; // Flag for exitting the timer threadpublic: // Stub that invokes threadproc (required for using a callback function belonging to a class) static DWORD StaticThreadProc(LPVOID); // Actual thread procedure DWORD ThreadProc(LPVOID); // Sets the exit flag condition for the thread proc void StopTimer(); // Constructor/deconstructor CBMPTimer(HWND, int); ~CBMPTimer();};#include BMPTimer.hbool CBMPTimer::timeractive;/** * Class constructor for CBMPTimer * Takes a handle to the target window for screenshotting * and an interval in milliseconds. */CBMPTimer::CBMPTimer(HWND hWnd, int ms){ // Assign member variables hwTarget = hWnd; ms_interval = ms; // This cast is necessary so that the ThreadProc function can be called from a static stub thistimer = reinterpret_cast<LPVOID>(this); hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&StaticThreadProc, thistimer, 0, NULL); // Set other member variables... timeractive = true; ticks_so_far=0;}/** * Class deconstructor for CBMPTimer * Frees dynamically allocated memory */CBMPTimer::~CBMPTimer(){ delete thistimer;}// Stub method that invokes ThreadProc.// Necessary so that ThreadProc can belong to the class and also be specified as a callback function.DWORD CBMPTimer::StaticThreadProc(LPVOID lpParam){ CBMPTimer *pThis = reinterpret_cast<CBMPTimer*>(lpParam); return pThis->ThreadProc(lpParam);}// Actual thread procedure.// Uses a CBMPWriter object to save a bitmap of the target window as long as the flag to keep running stays on.DWORD CBMPTimer::ThreadProc(LPVOID lpParam){ while (timeractive) { Sleep(ms_interval); CBMPWriter bmpW(hwTarget, ++ticks_so_far); bmpW.SaveBMP(); bmpW.~CBMPWriter(); } return EXIT_SUCCESS;}BMPWriter class:#pragma once#include <Windows.h>#include <tchar.h>#include <string>using namespace std;/** * BMPWriter class - a file writer for bitmap screenshots of a given window. */class CBMPWriter{private: char *data; // Stores the array of bits representing a bitmap of a window int len_data; // Length of data //char fname[MAX_PATH]; // Filename to write out BITMAPFILEHEADER bfHeader; // Bitmap file header structure BITMAPINFOHEADER biHeader; // Bitmap file header #2 structure BITMAPINFO bInfo; // Bitmap file header #3 structure HBITMAP hBitmap; // Handle to the bitmap object HWND hwTarget; // Target window HDC windowDC, tempDC; // Device context for target window and temporary copy in memory int count; // Refactor #3 - generate file names internally rather than use lazy class CFileNameGenerator int xd, yd; // x and y dimensions of bitmappublic: char fname[MAX_PATH]; // Filename to write out // Generate next file name of bitmap file - refactored out of CFileNameGenerator string NextFileName(); // Initialization functions for the 3 bitmap file header/signature structs void InitFH(); void InitIH(); void InitInfo(); // Class constructor - calls the initialization functions CBMPWriter(HWND, int); // Deconstructor - cleans up GDI objects and frees memory ~CBMPWriter(); // Performs the actual bitmap file write void SaveBMP();};#define _CRT_SECURE_NO_WARNINGS#include BMPWriter.h// Generates the next filename to write out the bitmap data to.string CBMPWriter::NextFileName(){ string next_filename; int temp = count; // Get the number of digits in the count variable by using logarithm base 10 int num_digits = (int)log10(temp)+1; char tmp[32]; // Write out the ascii value of the count into the string for(int i = 0; i < num_digits; i++) { tmp[num_digits-i-1]=(temp%10)+'0'; // digits 0-9 plus ascii '0' = char representation temp/=10; // divide by 10 to process next place-value } tmp[num_digits]=0; // terminate string with null char // create final filename string and return it. string countstr = tmp; next_filename=shot_; next_filename+=countstr; next_filename+=.bmp; return next_filename;}/** Initalizes the fields in the bitmap file header - file signature, header size, etc... */void CBMPWriter::InitFH(){ bfHeader.bfType = 0x4d42; // magic number- identifies the file as a valid bitmap to image viewers etc. bfHeader.bfSize = 0; // This and other 3 are reserved and always 0 bfHeader.bfReserved1 = 0; bfHeader.bfReserved2 = 0; bfHeader.bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER); // Specifies the number of bytes occupied by the headers (before the actual array of bits/pixels begins)}/** Initalizes the bitmap info header structure - bit intensity, planes, dimensions etc... */void CBMPWriter::InitIH(){ biHeader.biSize = sizeof(biHeader); biHeader.biBitCount = 24; // 24-bits = full intensity/lossless RGB image of window biHeader.biCompression = BI_RGB; // No compression biHeader.biHeight = yd; // dimensions biHeader.biWidth = xd; biHeader.biPlanes = 1; // number of planes biHeader.biSizeImage = 0; // all reserved fields below, must be 0 biHeader.biXPelsPerMeter = 0; biHeader.biYPelsPerMeter = 0; biHeader.biClrImportant = 0; biHeader.biClrUsed = 0;}// Initializes the bInfo structure (not a file header but necessary for various bitmap WinAPI functions)void CBMPWriter::InitInfo(){ bInfo.bmiHeader = biHeader;}CBMPWriter::CBMPWriter(HWND window, int tick){ // Set local variables... RECT r; hwTarget = window; count = tick; // Get the file name to save for this instance of CBMPWriter strcpy(fname, NextFileName().c_str()); // Get dimensions... GetWindowRect(hwTarget, &r); xd = r.right - r.left; yd = r.bottom - r.top; count=0; // Initialize file/bitmap headers and signatures etc InitFH(); InitIH(); InitInfo(); // Calculate length of data. len_data = ((((24 * xd + 31)&(~31)) / 8)*yd); // Generate dynamic char (byte) array based on length. data = new char[len_data]; // Get the device context of the target window windowDC = GetWindowDC(hwTarget); // Create a new device context *in memory* with identical properties as the window DC tempDC = CreateCompatibleDC(windowDC); // Get the bitmap of the window hBitmap = CreateDIBSection(windowDC, &bInfo, DIB_RGB_COLORS, (void**)&data, 0, 0); // Select it as the GDI object we want to use SelectObject(tempDC, hBitmap); // And copy it into the memory device context BitBlt(tempDC, 0, 0, xd, yd, windowDC, 0, 0, SRCCOPY);}/** * Class deconstructor for CBMPWriter * Deletes GDI objects, frees dynamic memory, etc. to prevent memory leaks */CBMPWriter::~CBMPWriter(){ DeleteDC(tempDC); ReleaseDC(hwTarget, windowDC); DeleteObject(hBitmap);}// Performs the actual write of the bitmap.void CBMPWriter::SaveBMP(){ // Create a file (if we can) HANDLE hFile = CreateFileA(fname, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile) { // If we can, write out the headers, then write out the bitmap DWORD dwWritten = 0; WriteFile(hFile, &bfHeader, sizeof(BITMAPFILEHEADER), &dwWritten, NULL); WriteFile(hFile, &biHeader, sizeof(BITMAPINFOHEADER), &dwWritten, NULL); WriteFile(hFile, data, len_data, &dwWritten, NULL); } else // If not, tell the user, and exit the class function { MessageBox(0, _T(Could not open the file.), _T(Error), MB_OK | MB_ICONSTOP); } // Free handle from memory. CloseHandle(hFile);}MsgHandler class:#pragma once#include <Windows.h>#include BMPTimer.h/** * CMsgHandler class - does the dirty work of the window procedure (handle messages etc). * Refactor #4 - existence of this class */class CMsgHandler{private: // The *target window* of the bitmap captures. Must be static as this class is created/deconstructed for each message posted to the queue. static HWND hwTarget; // The child windows of the parent screenshot taking app window. HWND hWnd, hwCmdSource, hStartBtn, hStopBtn, hSelect, hStatic2; // The identifier of the message (WM_whatever) UINT Msg; // WPARAM and LPARAM passed to the message WPARAM wParam; LPARAM lParam; // Bitmap timer class (necessary on start call) CBMPTimer *bmpT; // Return value LRESULT return_val;public: // Refactor #5 - remove the various redundant calls to FindWindowEx with all but 1 identical parameters inline HWND FindWindowQ(LPCWSTR className, LPCWSTR winText); // The various message handlers. VOID Handle_Close(); VOID Handle_Destroy(); VOID Handle_Command(); VOID Handle_Generic(); // Sub-handlers for WM_COMMAND based on command source VOID Handle_Start(); VOID Handle_Stop(); VOID Handle_Select(); // Return the return value (required for WindowProc stub) LRESULT Get_Return(); // Constructor/deconstructor CMsgHandler(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam, HWND hStaticW); ~CMsgHandler();};#include MsgHandler.h// Macros for eliminating duplicated code - simplifies method calls to FindWindowEx#define FINDBUTTON(wtxt) (FindWindowQ((TEXT(BUTTON)), (L##wtxt)))#define FINDEDIT (FindWindowQ((TEXT(EDIT)), (NULL)))HWND CMsgHandler::hwTarget;// Inline method for handling calls to FindWIndowEx - removes necessity for several duplicated calls etcinline HWND CMsgHandler::FindWindowQ(LPCWSTR className, LPCWSTR winText){ return FindWindowEx(hWnd, NULL, className, winText);}// Handles the WM_CLOSE message (destroys the window, return 0)VOID CMsgHandler::Handle_Close(){ DestroyWindow(hWnd); return_val = (LRESULT)0;}// Handles the WM_DESTROY message (posts the exit code for the window; return 0)VOID CMsgHandler::Handle_Destroy(){ PostQuitMessage(0); return_val = (LRESULT)0;}// Stub method to handle all calls not specifically supported by our class (call DefWindowProc)VOID CMsgHandler::Handle_Generic(){ return_val = DefWindowProc(hWnd, Msg, wParam, lParam);}// Handles the WM_COMMAND messageVOID CMsgHandler::Handle_Command(){ // Step 1: identify the source of the command (which button) hwCmdSource = (HWND)lParam; // Step 2: pass to the appropriate sub-handle for WM_COMMAND based on the button if (hwCmdSource == hSelect) { Handle_Select(); } if (hwCmdSource == hStartBtn) { if (hwTarget == NULL) { MessageBox(hWnd, TEXT(Please first select a target window!), TEXT(Problem), MB_OK | MB_ICONWARNING); return_val = (LRESULT)0; return; } Handle_Start(); } if (hwCmdSource == hStopBtn) { Handle_Stop(); } return_val = (LRESULT)0;}// Class constructor for CMsgHandler // sets up member variables and determines which message handler to useCMsgHandler::CMsgHandler(HWND ahWnd, UINT aMsg, WPARAM awParam, LPARAM alParam, HWND hStaticW){ hWnd = ahWnd; Msg = aMsg; wParam = awParam; lParam = alParam; hStartBtn = FINDBUTTON(Start); hStopBtn = FINDBUTTON(Stop); hSelect = FINDBUTTON(Select Window); hStatic2 = hStaticW; if (Msg == WM_CLOSE) Handle_Close(); else if (Msg == WM_DESTROY) Handle_Destroy(); else if (Msg == WM_COMMAND) Handle_Command(); else Handle_Generic();}// Sub handler for select window WM_COMMAND message source// Asks the user for the window they want to target,// prints out info about target window on app windowVOID CMsgHandler::Handle_Select(){ MessageBox(0, TEXT(If you are targetting a usual Windows application, try to target the *title bar* of the application. If you are targetting a Java or Flash applet target anywhere within the applet.\n\nPress OK and then hover your mouse over the target window within 2 seconds... (before pressing OK, you can move this message box closer to your target if need be)), TEXT(Info), MB_OK | MB_ICONINFORMATION); ShowWindow(hWnd, SW_MINIMIZE); Sleep(2000); POINT p; GetCursorPos(&p); hwTarget = WindowFromPoint(p); TCHAR wndTxt[255]; SendMessage(hwTarget, WM_GETTEXT, 255, (LPARAM)wndTxt); TCHAR sttcbuf[1024]; RECT wRect; GetWindowRect(hwTarget, &wRect); wsprintf(sttcbuf, TEXT(Target Window: %s\n(handle = 0x%.8X; rect=(%d,%d)-(%d,%d))), wndTxt, hwTarget, wRect.left, wRect.top, wRect.right, wRect.bottom); SetWindowText(hStatic2, sttcbuf); ShowWindow(hWnd, SW_RESTORE);}// Handles the Start WM_COMMAND message// 1. Toggles the enabled state of start and stop button// 2. intializes a CBMPTimer with the specified target and specified interval.VOID CMsgHandler::Handle_Start(){ EnableWindow((HWND)lParam, FALSE); EnableWindow(FINDBUTTON(Stop), TRUE); int len = GetWindowTextLength((FINDEDIT)) + 1; TCHAR *lenBuf = new TCHAR[len]; GetWindowText(FINDEDIT, lenBuf, len); int ms = _wtoi(lenBuf); if (ms == 0)ms++; bmpT = new CBMPTimer(hwTarget, ms);}// Handles a Stop WM_COMMAND message// 1. Stops the running CBMPTimer // 2. Toggles the enabled state of start and stop buttonVOID CMsgHandler::Handle_Stop(){ bmpT->StopTimer(); EnableWindow((HWND)lParam, FALSE); EnableWindow(FINDBUTTON(Start), TRUE);}CMsgHandler::~CMsgHandler(){}// Returns the stored LRESULT to WindowProc stub.LRESULT CMsgHandler::Get_Return(){ return return_val;}WinMain (global namespace):// The below files include my self-written classes for this project.#include BMPWriter.h#include BMPTimer.h#include MsgHandler.hconst TCHAR szClassName[] = TEXT(ScreenSnapperWnd);// The below two files allow for necessary Windows API and Process API functions in this project#include <Windows.h>#include <Psapi.h>#include Global.hHWND hwTarget = (HWND)0x0000000, hStaticWI = (HWND)0x00000000, hWnd, hStart, hStop, hFindTarget, hTimerMS, hStaticE;/** Refactor #1: * Given the length of WinMain, extract some methods from it, namely, the initialization of the WNDCLASSEX structure */ATOM RegisterWindowClass(HINSTANCE hInstance){ WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.hbrBackground = (HBRUSH)COLOR_WINDOW; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wcex.hInstance = hInstance; wcex.style = CS_BYTEALIGNWINDOW | CS_BYTEALIGNCLIENT | CS_GLOBALCLASS; wcex.lpszMenuName = NULL; wcex.lpszClassName = szClassName; wcex.lpfnWndProc = WindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; return RegisterClassEx(&wcex);}/** * Still Refactor #1 - extract child Window initialization from WinMain into a new method. */#define WS_RCHILD (WS_VISIBLE | WS_CHILD)VOID CreateChildWindows(){ hStaticE = CreateWindow(TEXT(STATIC), TEXT(Enter the interval between screenshots (milliseconds):), WS_RCHILD, 0, 0, 270, 20, hWnd, NULL, GetModuleHandle(NULL), NULL); hTimerMS = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT(EDIT), TEXT(5000), WS_RCHILD | ES_NUMBER, 0, 22, 270, 20, hWnd, NULL, GetModuleHandle(NULL), NULL); hFindTarget = CreateWindow(TEXT(BUTTON), TEXT(Select Window), WS_RCHILD | BS_TEXT, 10, 44, 250, 30, hWnd, NULL, GetModuleHandle(NULL), NULL); hStaticWI = CreateWindow(TEXT(STATIC), TEXT(), WS_RCHILD | SS_LEFT, 0, 88, 270, 40, hWnd, NULL, GetModuleHandle(NULL), NULL); hStart = CreateWindow(TEXT(BUTTON), TEXT(Start), WS_RCHILD | BS_TEXT, 10, 130, 125, 30, hWnd, NULL, GetModuleHandle(NULL), NULL); hStop = CreateWindow(TEXT(BUTTON), TEXT(Stop), WS_RCHILD | BS_TEXT | WS_DISABLED, 135, 130, 125, 30, hWnd, NULL, GetModuleHandle(NULL), NULL);}/** * WinMain function - entry point for the application */int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd){ MSG Msg; if(!RegisterWindowClass(hInstance)) { MessageBox(0, LWindow Registration Failed!, LError, MB_OK|MB_ICONSTOP); return -1; } hWnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, szClassName, TEXT(Screenshot Taker), WS_VISIBLE | WS_SYSMENU, 100, 100, 290, 210, NULL, NULL, GetModuleHandle(NULL), NULL); CreateChildWindows(); ShowWindow(hWnd, SW_SHOW); EnumChildWindows(hWnd, SysFontProc, 0); UpdateWindow(hWnd); while (GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam;}// Callback function that sets all child windows of the screenshot taker window to the regular system fontBOOL CALLBACK SysFontProc(HWND hWnd, LPARAM lParam){ HFONT hfDefault = (HFONT)GetStockObject(DEFAULT_GUI_FONT); SendMessage(hWnd, WM_SETFONT, (WPARAM)hfDefault, 0); return TRUE;}// Window procedure stub - required to be passed to WNDCLASSEX but invokes CMsgHandler to do all of the actual workLRESULT CALLBACK WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam){ CMsgHandler msghandler(hWnd, Msg, wParam, lParam, hStaticWI); return msghandler.Get_Return();}The .h files for the classes are first; the .cpp follows with the actual function bodies etc.Though my grade on this assignment was good (95%), I'm curious if anyone can offer an outside opinion on the quality of my post-refactored code: is there anything that still smells bad in this code? What can be improved further? Is this something I can safely call 'well-written'? | Refactorings on a Win32 Screenshot saving program | c++;image;windows | Quite a bit of code here, so this review is probably not complete:Coding style / Miscellaneous:Please keep parameter names on function prototypes. Parameter namesare a form of self documentation of the code.I would like to see a blank line between each function, both in the headerdeclarations and in the implementation. Your code is a bit cluttered in some places.Aligning things in a block such as this might also help readability(from CBMPTimer):int ticks_so_far; // New variable added with refactor #3 - keeps track of ticks made by our timerint ms_interval; // Inteval between clicksHWND hwTarget; // Target windowHANDLE hThread; // Thread for timer tickLPVOID thistimer; // Pointer to this class instancestatic bool timeractive; // Flag for exitting the timer threadThis is arguably personal preference, but I think it makes sense placingthe public section of a class first. Since we read a file from top to bottom, things at the top have more visibility. When a user of your class needs to consulta header file, what should have more visibility, private variables / implementation details,or the public interface?using namespace std; in a header file: No, no. Read this for more.Poor spacing at places, for instance:next_filename=shot_;next_filename+=countstr;next_filename+=.bmp;Always put spaces between an assignment or arithmetical operator:next_filename = shot_;next_filename += countstr;next_filename += .bmp;char fname[MAX_PATH] should be an std::string.Use more smart pointers. Manual memory management is a dated practicethat has proved time after time to lead to memory corruption bugs, dangling pointers and memory leaks.Be more mindful of your naming convention. You have mixed naming forvariables, some are using camelCase, like in hwTarget while others are using snake_case, like in ticks_so_far. Choose one notation andstick to it. Consistency is very important.If you can use C++11, then prefer the new nullptr over the NULL macro.A few security problems and potential bugs:This is not technically legal in C++:hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&StaticThreadProc, thistimer, 0, NULL);You are passing a static class method (CBMPTimer::StaticThreadProc) as the thread's start routine.CreateThread() expects a C function using the WINAPI (STD Call) calling convention. You have fixed thatby applying a very unsafe cast to the function pointer. This is a crash waiting to happen. You have to declarethe thread function as an extern C function using the adequate calling convention:extern C {DWORD WINAPI MyThreadProc(LPVOID lpParam){ CBMPTimer *pThis = reinterpret_cast<CBMPTimer*>(lpParam); return pThis->ThreadProc(lpParam);}} // extern Cdelete thistimer;, I don't even know how that is compiling. thistimer is a void pointer (LPVOID).delete shouldn't be able to delete void* because it has no type. This is probably being allowed by a Microsoft extension to the standard library.But thistimer get worse. It is actually a pointer to a CBMPTimer instance, initialized in CBMPTimer's constructor:thistimer = reinterpret_cast<LPVOID>(this);So by trying to delete it in the destructor, you are attempting to delete a pointer to the class that is already being destroyed. This is 100% Undefined Behavior. Manually calling a destructor:while (timeractive){ Sleep(ms_interval); CBMPWriter bmpW(hwTarget, ++ticks_so_far); bmpW.SaveBMP(); bmpW.~CBMPWriter(); // <--- Not a good idea and also unnecessary.}Doing this is a bad idea. There are only a few rare cases where you'll want to manually call a destructor. This is not one. The object is already going out of scope, so it will be destroyed on the next line. |
_cstheory.37450 | It is unknown whether $P\subseteq CSL$ or $P\not\subseteq CSL$, where$P$ is the set of all languages decidable in polynomial time on a deterministic Turing machine, and$CSL$ is the class of context-sensitive languages, known to be equivalent to $NSPACE(O(n))$, the languages decided by linear-bounded automata.For many open questions, there is a tendency towards one answer (a la most experts believe that $P\neq NP$). Is there something like this for this question?In particular, would either answer have unexpected consequences? I can only see expected (but unproven) consequences:If $P\subseteq CSL$, then $P\subseteq NSPACE(O(n))\subsetneq NSPACE(O(n^2))$ (space hierarchy theorem), hence $P\subsetneq PSpace$.If $P\not\subseteq CSL$, then there is a language $l\in P\setminus NSPACE(O(n))$ and therefore $l\in P\setminus NL$, hence $NL\subsetneq P$.(Acknowledgement: The second consequence of these two was pointed out by Yuval Filmus at https://cs.stackexchange.com/questions/69614/) | What is the conjectured relationship between P (PTime) and Type 1 (context-sensitive) languages? | cc.complexity theory;fl.formal languages;polynomial time | If $\mathrm{P\subseteq CSL}$, then $\mathrm{P\subseteq DSPACE}(n^2)$. By a padding argument, this implies$$\mathrm{DTIME}(t(n))\subseteq\mathrm{DSPACE}\bigl(t(n)^\epsilon\bigr)$$for every superpolynomial well-behaved function $t(n)$ and every $\epsilon>0$. I believe such a strong advantage of space over time is not expected to be true. The best currently known result in this direction is$$\mathrm{DTIME}(t(n))\subseteq\mathrm{DSPACE}(t(n)/\log t(n)),$$due to Hopcroft, Paul, and Valiant. |
_webapps.10321 | My old Yahoo account has been closed. So, I can't log in with it to unlink the Facebook account or change anything. But I'd like to link the Facebook account to my new Yahoo account. | How can I unlink my Facebook account from a closed Yahoo account? | facebook;yahoo | null |
_codereview.10681 | I have a java function that reads a csv and returns its content as a Vector<Vector<String>>.The function seems to work as I need it, but my gut feeling says it could be better (never mind the fact that it is declared throws Exception).So here it is:private static Vector<Vector<String>> readTXTFile(String csvFileName) throws Exception { BufferedReader stream = new BufferedReader( new InputStreamReader( new FileInputStream(csvFileName))); Vector<Vector<String>> csvData = new Vector<Vector<String>>(); String line; while ((line = stream.readLine()) != null) { csvData.add(new Vector<String>() ); String[] values = line.split(,); for (int v=0; v<values.length; v++) { csvData.get(csvData.size()-1).add(values[v]); } } return csvData;}BackgroundUltimately, the CSV Data will be used to fill a JTable. I could have used an String[][] for the data too, but it seemed that constructing a dynamic String[][] from a csv file would have been even more combersome (although I stand ready to be corrected on this, too). | Java function to read a CSV file | java;array;csv;vectors | The code can be simplified and improved in several ways, and the inner loop can be made tighter. Let me show you how:private static List<List<String>> readTXTFile(String csvFileName) throws IOException { String line = null; BufferedReader stream = null; List<List<String>> csvData = new ArrayList<List<String>>(); try { stream = new BufferedReader(new FileReader(csvFileName)); while ((line = stream.readLine()) != null) { String[] splitted = line.split(,); List<String> dataLine = new ArrayList<String>(splitted.length); for (String data : splitted) dataLine.add(data); csvData.add(dataLine); } } finally { if (stream != null) stream.close(); } return csvData;}A method should throw an exception as specific as possible, here it's better to use IOException instead of simply ExceptionWhenever possible, return interface types instead of concrete classes. Using List is preferred to using Vector, this allows you the flexibility to change the implementation of the collection laterTalking about collections: Vector is thread-safe and synchronized in many of its public methods, that can cause a performance hit. If you don't need that, it's better to use ArrayList, it's a drop-in replacement and won't incur in the performance penalty of synchronization. There's a simpler way to instantiate a BufferedReader, using a FileReader instead of using an InputStreamReader plus a FileInputStream. Besides, FileReader will take care of pesky details regarding character encodingThere's a simpler way to add elements to the last List added to csvData, as shown in the codeThere's a simpler way to iterate through the String[] returned by split(), using an enhanced loopDon't forget to close your streams! preferably inside a finally blockIf you don't need to add more elements to the returned List<List<String>>, you can use the following alternate version. It's faster because it avoids copying the String[] of split elements, but it won't allow adding new elements, as per the contract of asList():private static List<List<String>> readTXTFile(String csvFileName) throws IOException { String line = null; BufferedReader stream = null; List<List<String>> csvData = new ArrayList<List<String>>(); try { stream = new BufferedReader(new FileReader(csvFileName)); while ((line = stream.readLine()) != null) csvData.add(Arrays.asList(line.split(,))); } finally { if (stream != null) stream.close(); } return csvData;} |
_softwareengineering.191576 | I'm curious, is there a standard approach to dealing with long lists in the Python community, and in particular, is there any antipathy toward doing blank lines followed by comments to break up a particularly long list, e.g. of tuples, or in a dict, etc.?For example, I'm developing a GUI application in wxPython, and am defining the keyboard shortcut mappings to . Is this fairly Pythonic?accelerator_table = wx.AcceleratorTable([ # Case accelerators (CTRL, ord('S'), EventIds.SAVE_CASE), (CTRL_SHIFT, ord('S'), EventIds.RENAME_CASE), (CTRL, wx.WXK_DELETE, EventIds.REMOVE_CASE), (CTRL_SHIFT, wx.WXK_DELETE, EventIds.DELETE_CASE), # Project accelerators (CTRL_ALT_SHIFT, ord('S'), EventIds.RENAME_PROJECT), (ALT, wx.WXK_DELETE, EventIds.REMOVE_PROJECT), (ALT_SHIFT, wx.WXK_DELETE, EventIds.DELETE_PROJECT), # Help accelerators (NORMAL, wx.WXK_F1, EventIds.HELP), (NORMAL, wx.WXK_F2, EventIds.LAUNCH_MANUAL), (NORMAL, wx.WXK_F12, EventIds.ABOUT), ...])The details aren't particularly important, but I'd like to write in a style that will not annoy other programmers along the way, and therefore to decide right now whether this pattern is worth keeping around.Edit: Just to clarify: I'm not intending to put anything beyond that single blank line between sections in the list. That seems like it should minimize any confusion on the part of someone reading through the code. | Python code style - blank lines in long list | coding style;python;whitespace | Looking at the OP's initial approach, it is immediately obvious to me what it's doing. I don't see that there are readability or maintainability problems with this at all, nor do I see that it violates any commonly-accepted Python conventions or idioms. It's clear, and it uses minimal syntactic boilerplate and extraneous operations to achieve its goal. I recommend sticking with this approach.The implementation suggested by Demian's answer seems to create more problems than it solves. Returning a list from a property is usually not a good idea, because it creates an interface that will look identical to an attribute, but will exhibit bizarre behavior if used as such, e.g. t.file.extend(t.project) will not do what most users would expect, and will fail silently, causing potentially confounding bugs.The OP could use instance attributes or class fields instead of properties, but I'm not sure an object-oriented approach has much utility here (i.e. it seems to be using class syntax without employing actual OOP concepts).But the suggestion to separate the tuple-list aggregate into multiple smaller lists, that are then concatenated and passed to wx.AcceleratorTable, seems sensible. The right approach is mostly a matter of preference, though I still prefer the OP's initial approach because it involves less list manipulation, and doesn't have any readability issues that I see. |
_unix.373362 | I'm using the Kali Linux but the apt-get install is not working to install any application on my system.Someone provide me a link to source.list file. | apt-get not working on my kali linux | kali linux | Open a terminal follow these instructions:Type sudo -iType in your password.Type touch /etc/apt/sources.listType chmod 644 /etc/apt/sources.listType echo deb http://http.kali.org/kali kali-rolling main contrib non-free > /etc/apt/sources.listType apt-get updateNow install whatever it is that you want to install. |
_hardwarecs.2575 | I just got a new LG 31MU97-B that I'd like to hook up to my PC and Mac, but I can't find a [mini-/]displayport KVM switch that supports full Cinema 4k (4096x2160) at 60Hz, only UHD (3840x2160).I'm hoping there's something that my Google searches have missed, or someone else has had luck with a UHD-spec'd KVM still outputting Cinema 4k by sheer luck.Thanks for your help! | KVM switch for Cinema 4k? | monitors;kvm;display port | I found something! After looking for a few months, I came across this press release for the Aten 2-Port USB DisplayPort KVM Switch that specifically mentions support for displayport resolutions up to 4096x2160 @60Hz.I found it for sale on newegg and Amazon, and it looks like it's been out for while, but both sites only listed support for UHD resolution (3840x2160). I got it, plugged it in, and it worked great! Full resolution and refresh rate on both my computers. |
_unix.291789 | I've had Windows 10 and Fedora 24 installed, dual-booting, and it has been fine, but I just installed Kali in the remaining 200 GB, and the bootloader it installed can't boot Fedora. If I go into my UEFI setup and boot from the bootloader that Fedora installed, it boots perfectly, but if I try to boot Fedora from the bootloader that Kali installed, it says it's in emergency mode, and I get a login prompt, but no GUI whatsoever. I'd like to be able to boot my three operating systems in the same place. Is there any way to fix this? | Can't boot Fedora from Kali's Grub | fedora;windows;grub2;kali linux;dual boot | null |
_cstheory.19869 | I am now considering about studying functional programming from the viewpoint of category theory. There are a lot of books about functional programming and category theory, I want some suggestions regarding some comprehensive books and reference materials (like online notes, courses etc)that would contain category theory viewpoint rather than plain functional programming. I have a solid background in Abstract Algebra,commutative algebra, functional programming and bit of category theory too. | Learning road map for functional programming from the viewpoint of category theory | reference request;functional programming;advice request;ct.category theory | There's no agreed upon bible for CT for computer science in the same way as for mathematicians (Mac Lane), probably because the field is younger and a bit broader. It really depends on whether you want to understand . Here are a few computer science concepts with category theory counterparts:Simple types (which correspond to Cartesian Closed Categories)dependent types (Locally Cartesian Closed Categories)Abstract data types (categorical algebras, coalgebras, as described in e.g. Uustalu & Vene)Programing with effects (Monads, monoidal categories, building on the foundational observations of Moggi)Ressource aware programing (Closed Monoidal Categories (?))CPS translations can be interpreted through the lens of the Yoneda lemma (see here for a brief explanation)I'm missing a few, there are applications of category theory from everything to domain theory to database management. |
_codereview.43618 | I just want to checking if this kind of routing is good or bad?I implement the routing of my web appl to something like this.All page will be pointing to the index.phpin index.php I have this code$url = array_values(array_filter( explode( '/', strtolower($_SERVER[REQUEST_URI]) ) ) ); switch( $url[0] ) { case admin : { if( !$this->us->isAdmin ) { $this->GoToLoginPage(); } array_shift( $uri ); $department = new Admin( $uri ); } break; case article : { if( count( $uri ) == 2 ) { displayArticle( $uri[1] ); } else { displayError(); } } break; default : { displayIndex(); } break;}I just want to know is there any pro and con of doing something like this. | Is my routing good or bad? in PHP | php | Separate your logic and site specific functionality like this:function Router{ $url = array_values(array_filter(explode('/', strtolower($_SERVER[REQUEST_URI])))); switch($url[0]){ case admin: $this->Admin($url); break; case article: $this->Article($url); break; default: displayIndex(); }}function Admin($uri){ if( !$this->us->isAdmin ) { $this->GoToLoginPage(); } array_shift( $uri ); $department = new Admin( $uri );}function Article($uri){ if( count( $uri ) == 2 ) { displayArticle( $uri[1] ); } else { displayError(); }}It's much cleaner, and easier to update. |
_unix.364018 | I need to some strings in a file in the following fashionOld file:Real/Test1Real/Test1Real/Test2Real/Test3Real/Test3Real/Test4New File:Real/Test1 a1 b1 c1 d1Real/Test1 a1 b1 c1 d1Real/Test2 a2 b2 c2 d2Real/Test3 a3 b3 c3 d3Real/Test3 a3 b3 c3 d3Real/Test4 a4 b4 c4 d4I have an intermediate file which has the old string in the column 1 and then the new string, something like this.Test1 a1 b1 c1 d1Test2 a2 b2 c2 d2Test3 a3 b3 c3 d3Test4 a4 b4 c4 d4Could anyone please help with this?With my very primitive knowledge, I tried following:(while read n1 n2 do set n1 n2 sed -i s/$n1/$n1 $n2/g old > final done)where old and intermediate inputs are the content mentioned above.Thanks a lot ! | replace string in a loop | awk;sed;perl | perl -lne ' @ARGV and $h{$1}=s/(\S+)//r,next; s|/(\S+)\K|$h{$1}|;print;' intermediate.file old.fileResultsReal/Test1 a1 b1 c1 d1Real/Test1 a1 b1 c1 d1Real/Test2 a2 b2 c2 d2Real/Test3 a3 b3 c3 d3Real/Test3 a3 b3 c3 d3Real/Test4 a4 b4 c4 d4ExplanationUsing the intermediate file (@ARGV is > 0) we populate the hash using the first field as the key and the remaining fields as the corresponding value.When we process the old file (@ARGV = 0), we look at the string after the slash and use that to pullup the hash value and put it back in the current line. |
_unix.81176 | I know there are a million questions on getting the process ID, but this one seems to be unique. Google has not given me the answer, so I hope stackexhange will help rather than close this question.When Java is involved it seems trickier to find a process ID (pgrep doesn't work afaik). Furthermore, I need to automate this in a bash script. One issue I've encountered is that when I use ps aux | grep the grep process itself always shows up, so handling the results in a simple bash script is not trivial enough for me to figure out a good solution on my own (with my limited bash skills).Some things I have tried:Example 1 - this returns a process even though there is no application by that name:$ ps aux | grep -i anythingnotrealuser2 3040 0.0 0.0 4640 856 pts/3 S+ 18:17 0:00 grep --color=auto -i anythingnotrealExample 2 - this returns nothing even though java_app is currently running:$ pgrep java_appIt returns nothing. However, here's proof that java_app is running:$ ps aux | grep java_apptester2 2880 0.7 2.8 733196 58444 ? Sl 18:02 0:07 java -jar /opt/java_app2/my_java_app.jartester2 3058 0.0 0.0 4644 844 pts/3 S+ 18:19 0:00 grep --color=auto java_appWhat I need is a solution I can plug into a bash script that will tell me if the java application of interest (for which I know the jar file name and path) is currently running. (If it is running, I need to ask the user to close it before my script continues.) | Find the process id of a java application in a bash script (to see if the target application is already running) | bash;shell script;java;process management;bash script | By default, pgrep only matches the command, not the arguements. To match the full command line, you need the -f option.$ pgrep -f java_appFrom the pgrep manpage:-f The pattern is normally only matched against the process name. When -f is set, the full command line is used |
_webapps.15822 | I'm using Mail (the Mac OS X app, v4.5) to access my Google Mail account, but every mail sent to my Gmail address arrives twice in Mail. In the global inbox for the Gmail accountAnd one in the IMAP folder for the Gmail account in the All messages folder(In my German version it's the Alle Nachrichten folder)I thought it was because I used filters and labels in Gmail to pre-organize my Mail, but I disabled both filters and labels and the issue still persists. I want to avoid deleting the All messages folder in Mail since I'm afraid I won't be able to access all my mails in my Gmail account from Mail anymore. Is this a known issue? I know people who use Gmail with Mail who don't have this problem, but I couldn't find out what they had set differently.EDIT: It appears matthiasr is right. Apple Mail simply can't handle Gmail. I tried Sparrow, another e-Mail client for Mac which can, however, handle GMail quite nicely. Works like a charm. Unless anyone can provide a workaround of some sort for Apple Mail, I would mark matthiasr's answer as accepted. | Duplicate e-Mails in Mail (Mac OS X) in GMail inbox | email;mac;gmail imap | This is the expected behaviour of GMail via IMAP, and is documented here.The underlying problem is that the GMail paradigm of having one gigantic pile of mail (All Mail) with tags (and INBOX is just another tag, just one that every new message has attached) does not map well to the folder paradigm underlying IMAP.Inside GMail, it's completely normal to have a mail show up in Inbox, All Mail and a bunch of other tags as well. IMAP clients (including Apple Mail) don't really expect this and do not realize that these are the same message.Not much you can do about it, other than hiding the [GMail] hierarchy of folders. |
_computergraphics.85 | Bicubic sampling is pretty good for up sampling an image and making it larger, but is it a good choice for down sampling as well? Are there better choices? | Algorithms for down sampling an image? | texture | When Sean and I wrote stb_image_resize we chose Mitchell for downsizing. Mitchell is similar to Cubic, you can read about the cubic class of sampling filters in Mitchell Netravali 1988. They are all pretty similar and will get you very similar results.I can't find any written record between Sean and I of why we decided to go with Mitchell, but if memory serves we just resampled a bunch of images and used the algorithm that we thought looked best. I wouldn't say that there is one authoritative or best filter, you should use the one that looks best on your data.Edit: Like joojaa says, a windowed sinc filter is also good, if not quite as cheap. You can find some implementations here. |
_softwareengineering.157019 | My background is as follows. I've been programming since I was young, worked in BASIC, then Asm for M68K, then C, C++, and now I've spent the past 5 years in .NET becoming a rather good .NET developer. Somewhere along the line, I realized I have no clue how the internet works, I don't know how TCP/IP works, I have no clue what HTML is capable of, or how PHP plays into the picture, or why Ruby on Rails should make me happy. I have no experience with LAMP or IIS, and I only have an inkling of a clue what Sharepoint is.In short: I'm internetstupid. I am intelligent and a capable developer, but I lack even rudimentary skills (routing, web hosting, hosting a custom DNS for intranet domain resolving, etc.) I have no clue where to start on web development learning. Here's the good news! I know what I'd like to learn to do (at least for now!)I want to be able to develop my own personal domain to host WSDL services, to power my applications, to showcase my work, to host my living resume, to market my brand so to speak.Stackoverflow, I beg you, help this disconnected but talented developer become part of the current era instead of being a relic stuck in the previous great golden age of software!Note: I'd prefer to stay wedded to MS for now for the most part as I'm already familiar with the .NET ecosystem. I'm okay branching out, but not ready to do so (I think?) If you can convince me otherwise that's fine. | What are some good ways for an experienced .NET client developer to start learning web development? | web development;.net | I agree with @ElYusubov that you should slow down just a bit. It takes years to learn all the topics you mentioned. Let's break your list down:Internet Fundamentals: You can find out superficially how computer networking works by reading a little about the OSI model. Now that you know how data travels from one computer to the another computer, you can read about how applications make use of that data. For example, you may want to read about how a browser and a Web server communicates (e.g. using HTTP). HTTP carries certain content that the Web server generates, and the browser consumes. One such content is HTML. There is a free video on PluralSight that talks about how IIS (since you prefer MS technology) and Internet Explorer communicate.Next, you can watch more HTML videos that explore the more advanced concepts of what HTML(5) (Some of these videos are not free, and I haven't watched them). There are plenty of books that talk about HTML5.PHP (or rather, the PHP libraries), Ruby on Rails, ASP.NET, Java Spring Framework, etc. are all frameworks that help developers write Web applications. If you prefer Microsoft technologies, the obvious choice is to deep dive into ASP.NET. Microsoft Web site has many videos and books online on ASP.NET. I like the book: Pro ASP.NET MVC Framework.Let's forget about LAMP for the moment, since they are not part of the inner circle of Microsoft ecosystem.Let's also wait on the Web Service part (WSDL). Instead, you can write your living resume application! You can start by going to the ASP.NET tutorial site. |
_unix.2533 | I know that you can only have 4 primary partitions on a hard drive. But if you're using less than 4, is there a benefit/penalty for using logical partitions? | Primary vs Logical partition | partition | null |
_cs.248 | A simple game usually played by children, the game of War is played by two people using a standard deck of 52 playing cards. Initially, the deck is shuffled and all cards are dealt two the two players, so that each have 26 random cards in a random order. We will assume that players are allowed to examine (but not change) both decks, so that each player knows the cards and orders of cards in both decks. This is typically note done in practice, but would not change anything about how the game is played, and helps keep this version of the question completely deterministic.Then, players reveal the top-most cards from their respective decks. The player who reveals the larger card (according to the usual order: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace) wins the round, placing first his card (the high card) at the bottom of his deck, and then his opponent's card (the low card) at the bottom of the deck (typically, the order of this isn't enforced, but to keep the first version of this question deterministic, such an ordering will be enforced).In the event of a tie, each player reveals four additional cards from the top of their decks. If the fourth card shown by one player is higher than the fourth card shown by another player, the player with the higher fourth card wins all cards played during the tie-breaker, in which case the winner's cards are first placed at the bottom of the winner's deck (in first-in, first-out order; in other words, older cards are placed at the bottom first), followed by the loser's cards (in the same order).In the event of subsequent ties, the process is repeated until a winner of the tie is determined. If one player runs out of cards and cannot continue breaking the tie, the player who still has cards is declared the winner. If both players run out cards to play at the same time the game is declared a tie.Rounds are played until one player runs out of cards (i.e., has no more cards in his deck), at which point the player who still has cards is declared the winner.As the game has been described so far, neither skill nor luck is involved in determining the outcome. Since there are a finite number of permutations of 52 cards, there are a finite number of ways in which the decks may be initially dealt, and it follows that (since the only state information in the game is the current state of both players' decks) the outcome of each game configuration can be decided a priori. Certainly, it is possibly to win the game of War, and by the same token, to lose it. We also leave open the possibility that a game of War might result in a Tie or in an infinite loop; for the completely deterministic version described above, such may or may not be the case.Several variations of the game which attempt to make it more interesting (and no, not all involve making it into a drinking game). One way which I have thought of to make the game more interesting is to allow players to declare automatic trumps at certain rounds. At each round, either player (or both players) may declare trump. If one player declares trump, that player wins the round regardless of the cards being played. If both players declare trump, then the round is treated as a tie, and play continues accordingly.One can imagine a variety of rules limiting players' ability to trump (unlimited trumping would always result in a Tie game, as players would trump every turn). I propose two versions (just off the top of my head; more interesting versions along these lines are probably possible) of War based on this idea but using different trump limiting mechanisms:Frequency-War: Players may only trump if they have not trumped in the previous $k$ rounds.Revenge-War: Players may only trump if they have not won a round in the previous $k$ rounds.Now for the questions, which apply to each of the versions described above:Is there a strategy such that, for some set of possible initial game configurations, the player using it always wins (strongly winning strategy)? If so, what is this strategy? If not, why not?Is there a strategy such that, for some set of possible initial game configurations, the player using it can always win or force a tie (winning strategy)? If so, what is this strategy? If not, why not?Are their initial game configurations such that there is no winning strategy (i.e., a player using any fixed strategy $S$ can always be defeated by a player using fixed strategy $S'$)? If so, what are they, and explain?To be clear, I am thinking of a strategy as a fixed algorithm which determines at what rounds the player using the strategy should trump. For instance, the algorithm trump whenever you can is a strategy, and an algorithm (a heuristic algorithm). Another way of what I'm asking is this:Are there any good (or provably optimal) heuristics for playing these games?References to analyses of such games are appreciated (I am unaware of any analysis of this version of War, or of essentially equivalent games). Results for any $k$ are interesting and appreciated (note that, in both cases, $k=0$ leads to unlimited trumping, which I have already discussed). | Analyzing a modified version of the card-game War | algorithms;optimization | If I understand correctly, all information about the game is available to both players. That is, the starting configuration and all of the possible moves are known by both players (mainly because both players can look at the cards of the other player). This makes game is a zero-sum game of perfect information. Thus there exists is a perfect strategy available to both players that would achieve the best outcome in each game for that player. This was proven in 1912 by the German mathematician Ernst Zermelo.I do not know what the strategy is, but one could imagine building a big game tree for it and getting a computer to find the strategy for me using the min-max algorithm.The tree for each game would have as root the hands of the two players. The branches in the tree corresponds to the moves of the players. In the simplest case, these consist of simply laying down the requisite cards. In the more advanced cases, the 'trump' move can be made. Internal nodes of the tree record what the current configuration of cards is along with any information about the state wrt 'trumps'. The leaves of the tree correspond to the end game positions, which will be labelled with, say, +1 for a win to Player 1, 0 for a tie, and -1 for a win to Player 2. Ignore looping games for now.Now the min-max algorithm will work as follows (from Player 1's perspective). Assume that it looks at a node where Player 1 makes a move and that the nodes below are annotated with a +1, 0, or -1 (the payoff) along with the choices the player needs to make to get the given result. Player 1 simply selects the node with the largest payoff, records that payoff and the choice required to get that. For the node where Player 2 is making the move, the node with the minimum payoff is chosen, and the choice is recorded. This reflects that Player 2 is aiming for the lowest score to win. This is propagated to the of the tree. The choices recorded at each node correspond correspond to the best strategy a player can make. The final payoff determines who wins. This is ultimately a function in terms of the payoff, though the exact choice of moves may vary. Potentially looping configurations can be incorporated into the game tree by simply adding loops that return to an already seen configuration (when computing from the top). For such nodes you take the greatest fixed point if it is a node where Player 1 plays and the least fixed point when Player 2 plays.Note that if you had not made the assumption that both players could examine both decks, then this approach would not apply. The game would then involve chance and the selected strategy would be game specific.Whether or not there is a strong or weak winning strategy for one of the players depends on the outcome of the min-max algorithm applied to all trees. But there sure are a lot of them .... Computing the tree for one is probably fairly easy, since there are not very many choices made through the game. |
Subsets and Splits