id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_codereview.71171 | I'm doing an easy problem in codechef. Here's the problem statement for maxcount:Given an array A of length N, your task is to find the element which repeats in A maximum number of times as well as the corresponding count. In case of ties, choose the smaller element first.OK, I cheated. I used std:map because I want to play with it. Please review my code:#include<iostream>#include<map>int main() { int test_cases{}; std::cin >> test_cases; for (auto i = 0; i < test_cases; ++i) { std::map<int,int> count; std::size_t size{}; std::cin >> size; int x{}; for (std::size_t i = 0; i < size; ++i) { std::cin >> x; count[x] = ++count[x]; } int number{}; int numberCount{}; for (auto& i : count) { if (i.second > numberCount) { number = i.first; numberCount = i.second; } else if (i.second == numberCount) { if (i.first < number) { number = i.first; } } else { continue; } } std::cout << number << << numberCount << '\n'; }}How can I make this better and faster? | Count of Maximum - CodeChef | c++;c++11;programming challenge | Simplify: count[x] = ++count[x]; // Why not just; ++count[x];Variable name length:for (auto i = 0; i < test_cases; ++i) {Have you ever tried searching for all occurrences of the variable i in the resulting loop. The number of false positives will be a pain in the arse. Name your loop variables so you can find them easily.Hiding variables names: for (std::size_t i = 0; i < size; ++i) {Though not technically illegal. This becomes a maintenance problem. It's OK for you today as you just wrote the code. But for anybody else (or you in years time) this is can be a pain. Try and give your variables unique meaningful names (self documenting code is a brilliant practice but it requires variable names to be meaningful).The whole loop where you search for the largest repeat: for (std::size_t i = 0; i < size; ++i) {This can be done inline while you were counting. I would not have a second loop to work it out after the fact.I would simplify this condition:} else if (i.second == numberCount) { if (i.first < number) {// I find it easier to read as:} else if (i.second == numberCount) && (i.first < number) {This seems a bit redundant: } else { continue; }Personally I think initializing integers with {} looks terrible (and is slightly confusing).std::size_t size{};std::size_t size = 0; // Much easier to read.Whats the point in initizliaing a variable just before you write over it? std::size_t size{}; // Why initialize it here std::cin >> size; // Only to trash the initialization here.Address Comments: int number{}; int numberCount{}; for (std::size_t i = 0; i < size; ++i) { std::cin >> x; std::size_t& countV = count[x]; ++countV; if (countV > numberCount || (countV == numberCount && x < number)) { number = x; numberCount = countV; } } |
_unix.320778 | Just wrote my first Makefile and I can't figure why GNUmake recompiles everything each time I call make. Here it is:# MakefileCC = c++ROOTFLAGS = $(shell root-config --cflags)MGDOFLAGS = $(shell mgdo-config --cflags)CLHEPFLAGS = $(shell clhep-config --include)ALLFLAGS = $(ROOTFLAGS) $(MGDOFLAGS) $(CLHEPFLAGS)ROOTLIBS = $(shell root-config --glibs) -lSpectrumMGDOLIBS = $(shell mgdo-config --libs)CLHEPLIBS = $(shell clhep-config --libs)ALLLIBS = $(ROOTLIBS) $(MGDOLIBS) $(CLHEPLIBS)EXEC = tier1browser selectEvents currentPlotall : $(EXEC)selectEvents : selectEvents.cc mkdir -p bin && \ $(CC) $(ALLFLAGS) -o bin/$@ $< $(ALLLIBS)currentPlot : currentPlot.cc mkdir -p bin && \ $(CC) $(ROOTFLAGS) -o bin/$@ $< $(ROOTLIBS) -fopenmp -Ofasttier1browser : tier1Browser.cxx tier1BrowserDict.cxx mkdir -p bin && \ $(CC)-4.9 $(ALLFLAGS) -I. -o bin/$@ $< lib/tier1BrowserDict.cxx $(ALLLIBS) tier1BrowserDict.cxx : tier1Browser.h tier1BrowserLinkDef.h mkdir -p lib && \ cd lib && \ rootcling -f $@ $(MGDOFLAGS) $(CLHEPFLAGS) -c ../tier1Browser.h ../tier1BrowserLinkDef.h; \ cd ...PHONY : all cleanclean : rm -rf bin/* lib/*What's wrong?The final folder hierarchy:bin/currentPlotbin/selectEventsbin/tier1browserlib/tier1BrowserDict.cxxlib/tier1BrowserDict_rdict.pcmMakefilecurrentPlot.ccselectEvents.cctier1Browser.cxxtier1Browser.htier1BrowserLinkDef.hAny other hint for a newbye to make it more efficient and elegant? | Make recompiling unchanged files | make | You ask Makefile about a dependancy on current dircurrentPlot : currentPlot.ccmake is expecting a file name currentPlot in current dir and you are building in bin dir (-o bin/$@). |
_codereview.147834 | Please refrain from negative comments about the code being poor and inefficient and not idiomatic. I know that much, and that's why I'm here.I need a function, that takes a byte array and length and returns a byte array.The function need to do the following:Drop any leading zeroes in the byte arrayIf the array length is shorter than passed length parameter, pad the array with leading zeroes up to the passed lengthI'm not worried to much about efficiency (e.g. removing a zero only for adding it back later), although I don't mind improvements here, but what I'm really after is to make the code more javascript idiomatic. Can I use Array.map or Array.filter here, for example?function normalize(byteArray, length) { var padding = 0; while(padding < byteArray.length && byteArray[padding] == 0) { padding++; } byteArray = byteArray.slice(padding); while(byteArray.length < length) { byteArray = [0].concat(byteArray); } return byteArray;}Context: the byte array passed to this function comes for a BigInteger value. BigInteger has toByteArray method that produces the array, that needs to be fixed up by the function in question. toByteArray method usually does not produce arrays longer than needed for underlying integer, but sometimes it adds an extra zero byte in front. From the integer perspecive it's all the same, but where the resulting array is going to be consumed (in the printing/formatting function) a certain length is expected, so that the data can be laid out properly. Thus, this function. | Padding with leading zeros or removing leading zeroes to make sure that array is at least given length | javascript | null |
_cs.70520 | I am learning Lambda Calculus from the book by Hindley and Seldin . They start the formal postulation of lambda calculus as follow : (a) all variables and atomic constants are -terms (called atoms); (b) if M and N are any -terms, then (MN) is a -term (called an application); (c) if M is any -term and x is any variable, then (x.M) is a-term (called an abstraction).In the second postulate $MN$ has been termed as a $\lambda$ term . How to define $MN$ , what does it mean ? Is it an operation?Is there any scope of defining operations in lambda calculus which are associative and/or distributive ? | Any notions of operations in basic postulates of lambda calculus | lambda calculus | null |
_codereview.38513 | Moved to Code Review as per comments received on https://stackoverflow.com/questions/20907502/can-this-while-loop-be-made-cleanerIs there a way to make the following while loop a little more optimized? What bugs me in particular is the fact that I have to repeat code (closing buffers and returning a value) both inside and outside the if condition and I wanted to get opinions on whether there might be a better /more performance-oriented way to handle such code.While I've posted the entire method, the part I'm more interested in comments on is how the while loop can be optimized. Ofcourse, comments on the remainder of the code are also welcome, but not essential. private String getRandomQuote(int lineToFetch) throws IOException { //1. get path AssetManager assets = getApplicationAssets(); String path = null; path = getAssetPath(assets); //2. open assets InputStream stream = assets.open(path); InputStreamReader randomQuote = new InputStreamReader(stream); //3. Get BufferedReader object BufferedReader buf = new BufferedReader(randomQuote); String quote = null; String line = null; int currLine = 0; //4. Loop through using the new InputStreamReader until a match is found while ((line = buf.readLine()) != null) { // Get a random line number if (currLine == lineToFetch) { quote = line; Log.v(LINE, line); randomQuote.close(); buf.close(); return quote; } else currLine++; } randomQuote.close(); buf.close(); return quote;} | Can this while loop be made cleaner | java;performance;android | null |
_unix.70653 | When I run the time command in shell time ./myapp I get an output like the following:real 0m0.668suser 0m0.112ssys 0m0.028sHowever,when I run the command \time -f %e ./myapp I lose precision and I get:2.01sIf I use the %E command I also lose precision in the same way. How do I change it to have more precision again, but still only have the seconds being outputted?I based my research in this Linux / Unix Command: time and on this question | Increase %e precision with /usr/bin/time shell command | shell;scripting;time | I'm assuming you understand that both these commands are calling a different version of time, right?bash's built-in version% timeGNU time aka. /usr/bin/time% \timeThe built-in time command to bash can be read up on here:% help timetime: time [-p] PIPELINE Execute PIPELINE and print a summary of the real time, user CPU time, and system CPU time spent executing PIPELINE when it terminates. The return status is the return status of PIPELINE. The `-p' option prints the timing summary in a slightly different format. This uses the value of the TIMEFORMAT variable as the output format.The GNU time, /usr/bin/time, is usually more useful than the built-in.As to your precision problem it's covered here in this github gist, specifically:Why is bash time more precise then GNU time?The builtin bash command time gives milisecond precision of execution, and GNU time (usually /usr/bin/time) gives centisecond precision. The times(2) syscall gives times in clocks, and 100 clocks = 1 second (usually), so the precision is like GNU time. What is bash time using so that it is more precise?Bash time internally uses getrusage() and GNU time uses times(). getrusage() is far more precise because of microsecond resolution.You can see the centiseconds with the following example (see 5th line of output):% /usr/bin/time -v sleep .22222 Command being timed: sleep .22222 User time (seconds): 0.00 System time (seconds): 0.00 Percent of CPU this job got: 0% Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.22 Average shared text size (kbytes): 0 Average unshared data size (kbytes): 0 Average stack size (kbytes): 0 Average total size (kbytes): 0 Maximum resident set size (kbytes): 1968 Average resident set size (kbytes): 0 Major (requiring I/O) page faults: 0 Minor (reclaiming a frame) page faults: 153 Voluntary context switches: 2 Involuntary context switches: 1 Swaps: 0 File system inputs: 0 File system outputs: 0 Socket messages sent: 0 Socket messages received: 0 Signals delivered: 0 Page size (bytes): 4096 Exit status: 0More resolution can be had using bash's time command like so & you can control the resolution:# 3 places % TIMEFORMAT='%3R'; time ( sleep .22222 )0.224From the Bash manual on variables:TIMEFORMATThe value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The % character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.%%A literal %.%[p][l]RThe elapsed time in seconds.%[p][l]UThe number of CPU seconds spent in user mode.%[p][l]SThe number of CPU seconds spent in system mode.%PThe CPU percentage, computed as (%U + %S) / %R.The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used.The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included.If this variable is not set, Bash acts as if it had the value$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed. |
_unix.295210 | I'm trying to fetch html tags and their attributes from a webpage with linux command line tools. Here's the concrete case:Here's the task: Get all 'src' attributes of all 'script' tags of the website 'clojurescript.net'This should happen with as little ceremony as possible, almost as simple as using grep to fetch some lines of a text.curl -L clojurescript.net | [the toolchain in question script @src]http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.jshttp://kanaka.github.io/cljs-bootstrap/web/jqconsole.min.jshttp://kanaka.github.io/cljs-bootstrap/web/jq_readline.js[...further results]The tools I tried are: hxnormalize / hxselect, tidy, xmlstarlet. With none I could get a reliable result. This task was always straightforward when using libraries of several programming languages.So what's the state of the art of doing this in the CLI?Does is make sense to convert HTML to XML first, in order to have acleaner tree representation?Often HTML is written with many syntactic mistakes - is there a default approach (which is used by common libraries) to correct/clean this loose structure?Using CSS selectors with the additional option of only extracting an attribute would be ok. But maybe XPATH might be a better selection syntax for this. | basic webscraping from the CLI | command line;html | null |
_softwareengineering.314190 | I would like to have a caching solution for a variety of function calls.All of the function calls fit the following signature public ResponseType ProcessRequest(RequestType request); About half the time the cache key can be applied very simply, in a generic manner by pulling a key from the serialized string. The other half the time the cache key will need to be calculated very specifically for the data in the request, using specific fields that only that request includes. If the response should be cached is almost always certainly done based on the data of the response object. I decided down an interceptor because it can be turned on and off and be wrapped around the function so that the function call itself has no clue it's happening, and this needs to be applied to a lot of different function calls all over the place. here is what I have so far: public interface ICacheProvider{ object GetCachedItem( string cacheKey ); void AddItemToCache( object item, string key );}public class CacheProvider{ private readonly ConcurrentDictionary< string, object > _cacheDictionary; private CacheProvider() { _cacheDictionary = new ConcurrentDictionary< string, object >(); } public object GetCachedItem( string cacheKey ) { return _cacheDictionary.ContainsKey( cacheKey ) ? _cacheDictionary[ cacheKey ] : null; } public void AddItemToCache( object item, string key ) { _cacheDictionary.TryAdd( key, item ); }}public interface ICacheKey{ string GetCacheKey();}public interface IIsCacheable{ bool IsCacheable();}public class CacheInterceptor : IInterceptor{ private readonly ICacheProvider _cacheProvider; public CacheInterceptor( ICacheProvider cacheProvider ) { _cacheProvider = cacheProvider; } public void Intercept( IInvocation invocation ) { var request = invocation.Arguments.First() as ICacheKey; var requestCacheKey = request.GetCacheKey(); var cachedResponse = _cacheProvider.GetCachedItem( requestCacheKey ); if( cachedResponse != null ) invocation.ReturnValue = cachedResponse; else { invocation.Proceed(); var response = invocation.ReturnValue as IIsCacheable; if( response.IsCacheable() ) _cacheProvider.AddItemToCache( response, requestCacheKey ); } }}There is also currently the concept of a Transaction object which has a Request and Response object. I've thought about applying the concept of caching to that but would be akward with a method interceptor because i would have to fetch the transaction from the transaction manager which is a weird static dependency thing for a lot of other stuff and i'm trying to get rid of that as well.The problems with my proposed solution I would like to address: - I don't think this example conforms to the SOLID principles which is why I think I many of the other concerns. Please tell me why and how one would fix this?having to implement two separate interfaces for cacheing ICacheKey/IIsCacheable seems like a bit much. My request and response object types have to be aware of the cache solution? on one hand this makes sense because they know how the data is structured. On the other hand the idea of caching is a seperate concern then how the data is stored and should therefore be in another section? | Creating a generic Cache solution for function calls using SOLID principles in C# | c#;caching | null |
_unix.365825 | If I have the folder ~/1234567 and I type one of the following:ls ~/123cd ~/12then press tab, everything's groovy. But if, on either of those commands, I type 1234 before hitting tab, the 4th char is replaced with / and editing text becomes strange; if I hit return it's as if anything after ~ is ignored. This is repeatable in different locations in the filesystem, and does not depend on which other files/folders are at that location.This works as expected on bash on the same box. I'm using rhel6.9, and version 93u+ 2012-08-01 of ksh.I only have this problem if I use ~ and I don't have it if I use the ~username form; just ~/xxxx. | ksh tab completion not working if I've typed exactly 4 chars before pressing tab | ksh;autocomplete | null |
_webapps.108641 | Is it possible to auto-unlist videos AFTER they've been streamed or have I to manually do this myself when the stream has ended? Or even better, can I set it so people can send me superchats on an unlisted stream? | Help with unlisted streaming | youtube;youtube live | If you use Stream Now, you can automatically make your stream unlisted once completed in the stream options. |
_unix.93594 | I built kernel 3.11.3 following the instructions here.There were no issues in the build. The steps I followed automatically made entries in grub and copied the image to /boot too.At boot time, when I choose the new kernel, booting gets stuck with the following message[ 1.563345] MODSIGN: Problem loading in-kernel X.509 certificate (-129)[1.734622] ata3: softreset failed (device not ready)[1.735638[ ata1: softreset failed (device not ready)But I get the same message when booting with my original kernel (kernel-3.9.5-301.fc19.x86_64) and it immediately disappears and boots normally./boot/grub2/grub.cfg looks like this ## DO NOT EDIT THIS FILE## It is automatically generated by grub2-mkconfig using templates# from /etc/grub.d and settings from /etc/default/grub#### BEGIN /etc/grub.d/00_header ###if [ -s $prefix/grubenv ]; then load_envfiif [ ${next_entry} ] ; then set default=${saved_entry} set next_entry= save_env next_entry set boot_once=trueelse set default=${saved_entry}fiif [ x${feature_menuentry_id} = xy ]; then menuentry_id_option=--idelse menuentry_id_option=fiexport menuentry_id_optionif [ ${prev_saved_entry} ]; then set saved_entry=${prev_saved_entry} save_env saved_entry set prev_saved_entry= save_env prev_saved_entry set boot_once=truefifunction savedefault { if [ -z ${boot_once} ]; then saved_entry=${chosen} save_env saved_entry fi}function load_video { if [ x$feature_all_video_module = xy ]; then insmod all_video else insmod efi_gop insmod efi_uga insmod ieee1275_fb insmod vbe insmod vga insmod video_bochs insmod video_cirrus fi}terminal_output consoleset timeout=5### END /etc/grub.d/00_header ###### BEGIN /etc/grub.d/10_linux ###menuentry 'Fedora (3.11.3Mephisto) 19 (Schrdingers Cat)' --class fedora --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.9.5-301.fc19.x86_64-advanced-ebc305eb-2826-4aa0-91ae-f74f3e12b496' { load_video set gfxpayload=keep insmod gzio insmod part_msdos insmod ext2 set root='hd0,msdos7' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos7 --hint-efi=hd0,msdos7 --hint-baremetal=ahci0,msdos7 --hint='hd0,msdos7' b6603ac8-e004-4cd6-b141-9bc95409e32a else search --no-floppy --fs-uuid --set=root b6603ac8-e004-4cd6-b141-9bc95409e32a fi linux /vmlinuz-3.11.3Mephisto root=/dev/mapper/fedora-root ro rd.lvm.lv=fedora/swap rd.md=0 rd.dm=0 vconsole.keymap=guj rd.luks=0 vconsole.font=latarcyrheb-sun16 rd.lvm.lv=fedora/root rhgb quiet LANG=en_US.UTF-8 initrd /initramfs-3.11.3Mephisto.img}menuentry 'Fedora, with Linux 3.9.5-301.fc19.x86_64' --class fedora --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.9.5-301.fc19.x86_64-advanced-ebc305eb-2826-4aa0-91ae-f74f3e12b496' { load_video set gfxpayload=keep insmod gzio insmod part_msdos insmod ext2 set root='hd0,msdos7' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos7 --hint-efi=hd0,msdos7 --hint-baremetal=ahci0,msdos7 --hint='hd0,msdos7' b6603ac8-e004-4cd6-b141-9bc95409e32a else search --no-floppy --fs-uuid --set=root b6603ac8-e004-4cd6-b141-9bc95409e32a fi linux /vmlinuz-3.9.5-301.fc19.x86_64 root=/dev/mapper/fedora-root ro rd.lvm.lv=fedora/swap rd.md=0 rd.dm=0 vconsole.keymap=guj rd.luks=0 vconsole.font=latarcyrheb-sun16 rd.lvm.lv=fedora/root rhgb quiet initrd /initramfs-3.9.5-301.fc19.x86_64.img}menuentry 'Fedora, with Linux 0-rescue-7725dfc225d14958a625ddaaaea5962b' --class fedora --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-0-rescue-7725dfc225d14958a625ddaaaea5962b-advanced-ebc305eb-2826-4aa0-91ae-f74f3e12b496' { load_video insmod gzio insmod part_msdos insmod ext2 set root='hd0,msdos7' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos7 --hint-efi=hd0,msdos7 --hint-baremetal=ahci0,msdos7 --hint='hd0,msdos7' b6603ac8-e004-4cd6-b141-9bc95409e32a else search --no-floppy --fs-uuid --set=root b6603ac8-e004-4cd6-b141-9bc95409e32a fi linux /vmlinuz-0-rescue-7725dfc225d14958a625ddaaaea5962b root=/dev/mapper/fedora-root ro rd.lvm.lv=fedora/swap rd.md=0 rd.dm=0 vconsole.keymap=guj rd.luks=0 vconsole.font=latarcyrheb-sun16 rd.lvm.lv=fedora/root rhgb quiet initrd /initramfs-0-rescue-7725dfc225d14958a625ddaaaea5962b.img}### END /etc/grub.d/10_linux ###### BEGIN /etc/grub.d/20_linux_xen ###### END /etc/grub.d/20_linux_xen ###### BEGIN /etc/grub.d/20_ppc_terminfo ###### END /etc/grub.d/20_ppc_terminfo ###### BEGIN /etc/grub.d/30_os-prober ###### END /etc/grub.d/30_os-prober ###### BEGIN /etc/grub.d/40_custom #### This file provides an easy way to add custom menu entries. Simply type the# menu entries you want to add after this comment. Be careful not to change# the 'exec tail' line above.### END /etc/grub.d/40_custom ###### BEGIN /etc/grub.d/41_custom ###if [ -f ${config_directory}/custom.cfg ]; then source ${config_directory}/custom.cfgelif [ -z ${config_directory} -a -f $prefix/custom.cfg ]; then source $prefix/custom.cfg;fi### END /etc/grub.d/41_custom ###/etc/fstab looks like this## /etc/fstab# Created by anaconda on Tue Jan 1 11:58:46 2002## Accessible filesystems, by reference, are maintained under '/dev/disk'# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info#/dev/mapper/fedora-root / ext4 defaults 1 1UUID=b6603ac8-e004-4cd6-b141-9bc95409e32a /boot ext4 defaults 1 2/dev/mapper/fedora-home /home ext4 defaults 1 2/dev/mapper/fedora-swap swap swap defaults 0 0/dev/sda1 /mnt/media ntfs-3g gid=admin,umask=0007 0 0/dev/sda5 /mnt/setups ntfs-3g gid=admin,umask=0007 0 0/dev/sda6 /mnt/documents ntfs-3g gid=admin,umask=0007 0 0I'm using Fedora 19 on a x86_64 architecture | Unable to boot using self built kernel | boot;compiling;linux kernel | cd to the source directory, type 'make clean', then 'make localmodconfig' then build the kernel as you did before. When you do 'make install' grub.cfg will be autogenerated. |
_unix.75668 | The RFC: Uniform Resource Identifier (URI) Scheme for Secure File TransferProtocol (SFTP) and Secure Shell (SSH)presents the SSH URI as:ssh://[<user>[;fingerprint=<host-key fingerprint>]@]<host>[:<port>]Are there any known reasons why the OpenSSH ssh command doesn't follow this standard with the hostname option? It does not accept a port after a colon.Example of a URI I was expecting to work:$ ssh user@host:2222ssh: Could not resolve hostname host:2222: Name or service not known | Why doesn't the ssh command follow RFC on URI? | ssh;openssh | ssh predates the more general URI format (1998) by several years (1995 IIRC). |
_codereview.138643 | I am working on some sampling to collect data for my research on SOLID Principles. One of my sample consists proceeding code snippet:public abstract class Notify{ public abstract void NotifyClient();}public class OnPremisesClient : Notify{ public override void NotifyClient() { Console.WriteLine(You're getting these notifications because you opted....); }}public class CloudClient : Notify{ public override void NotifyClient() { Console.WriteLine(You're getting these notifications because you opted....); if (IsOnPremisesToo) NotifyClientAsOnPremisesClient(); } public void NotifyClientAsOnPremisesClient() { Console.WriteLine(Awesome! You are also using On premises services...); } public bool IsOnPremisesToo { get; set; }}Calling class is:public class Program { public static void Main(string[] args) { var premisesClient = new OnPremisesClient(); var cloudClient = new CloudClient(); ProcessNotifications(new List<Notify> { premisesClient, cloudClient }); } private static void ProcessNotifications(List<Notify> list) { HandleItems(list); } static void HandleItems(IEnumerable<Notify> notifications) { foreach (var notification in notifications) { if (notification is CloudClient) { var cloudClient = notification as CloudClient; cloudClient.IsOnPremisesToo = true; } notification.NotifyClient(); } } }In the preceding code snippet, I am trying to notify the client as per the type of Notify client could be a OnPremisesClient or CloudClient.This code-snippet looks neat and clean, but I would like to discuss which SOLID principle it violates. After going through few SOLID resources, I thought it violates SRP as it uses if. In the future, if there will be new client like GalaxyClient, then this code need a new condition. There might be more violations.Are SOLID principles really violate in the give code-snippet or just I am thinking it violates SOLID? I would appreciate it if someone tells the which principles are violating with reasoning. What would be the new code or what are changes should made to this code so, it'd follow SOLID Principles? | Sampling to collect data | c#;object oriented | The code in example is violating following principles:Single Responsibility Principle(SRP):The responsibility of Notifying is spread thin across Clients and the classes are not clear with their intentions and it is also not reflecting through the behaviours. Now, it is not clear whether the client is also supposed to do other jobs.Liscov Substitute Principle(LSP):'Is-A' Relationship should be replaced with 'Is-Substitue-for' relationship. notification is CloudClient is violating LSP.Dependency Inversion Principle(DIP): is violated since program class is dependent on client implementations and Notify class.IMO, code can be restructured as follows. Please note, it can be also improved with better DI Implementation. By judging the code listing, I am not clear what is intended output of this program. Whether it is sending two different notifications or three notifications. Still,trying to provide the answer as per my understanding and assumptions below. Please let me know in comments the intent of the program so that I can modify the program as per the intent.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace CodeSmellQuestion{ public class Notification { private readonly List<INotify> _providerList; public Notification(List<INotify> providerList) { _providerList = providerList; } public void SendAll() { foreach (var notificationProvider in _providerList) { notificationProvider.Notify(); } } } public interface INotify { void Notify(); } public class OnPremiseNotifier : INotify { public void Notify() { Console.WriteLine(You're getting these notifications because you opted for OnPremise Notifications....); } } public class CloudNotifier : INotify { public void Notify() { Console.WriteLine(You're getting these notifications because you opted for Cloud Notifications....); } }} |
_unix.210948 | I tried to use the ls command and got an error:bash: /bin/ls: cannot execute binary fileWhat can I use instead of this command? | What to use when the ls command doesn't work? | linux;command line;ls | You can use the echo or find commands instead of ls:echo *or:find -printf %M\t%u\t%g\t%p\n |
_unix.108345 | I built Firefox 26 on Mint 16 because the Ubuntu 10.04 build utilities are too old to build it. It does need to run on 10.04, however, since that's the target OS I'm building for. It built and runs just fine on Mint 16.When moving the package over to 10.04 and attempting to run, I get errors because the OS uses a different libc version than Firefox was built against.The actual error is:/lib/libc.so.6: version `GLIBC_2.17' not foundI've been doing a lot of research trying to solve this, and so far have discovered the following:I can point a binary at an alternate path for library files withexport LD_LIBRARY_PATH=/opt/libI placed the libc.so.6 from Mint 16 into /opt/lib on 10.04 and ran the above command. But after changing that variable, i get:error while loading shared libraries: __vdso_time: invalid mode for dlopen(): Invalid argumentNot just for firefox, but for every command, including things like ls. A bit more research suggests that I need a set of library files to make this work, not just libc.so.6. The problem is, I don't know which ones I need to copy over?Then I discovered ldd. ldd ./firefox shows:./firefox: /lib/libc.so.6: version `GLIBC_2.17' not found (required by ./firefox) linux-vdso.so.1 => (0x00007fffe9289000) libpthread.so.0 => /lib/libpthread.so.0 (0x00007f80ee456000) libdl.so.2 => /lib/libdl.so.2 (0x00007f80ee252000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f80edf3d000) libm.so.6 => /lib/libm.so.6 (0x00007f80edcba000) libc.so.6 => /lib/libc.so.6 (0x00007f80ed934000) /lib64/ld-linux-x86-64.so.2 (0x00007f80ee68b000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f80ed71c000)And I thought, maybe I just need to copy all of those on the list. Except I couldn't find a linux-vdso anywhere on Mint 16, and it's vdso that is being complained about.So my question is, which libraries do I need to move from Mint 16 to Ubuntu 10.04 into /opt/var, to make Firefox run on 10.04? | Which library files are needed to run a binary with an alternate libc version? | ubuntu;compiling;libraries;firefox;dependencies | null |
_scicomp.19395 | I have developed a pseudospectral solver of the Navier-Stokes equations using FFTW. I tested my formulation of right hand sides (RHS) of the NS equations against standard trigonometric functions (sines, cosines and their combinations). For example, I set density = sin 5xx_velocity = 5cos 5y + 6sin7zy_velocity = 4sin4y + cos xz_velocity = 1pressure = cos zSupplying these values to the solver, it computed the RHS of the NS equations. I did the same by hand and compared the results with that obtained by the solver. Results were to good agreement. The maximum error between the exact answer and that computed by the solver was of the order of E-13 for a 128*128*128 grid.Next I used a different function of the following form:density = constant1+constant2*(tanh(x-constant3)-tanh(x-constant4))x_velocity = 0y_velocity = 0z_velocity = 0temperature = 1pressure -> from ideal gas equation connecting density, temperature and pressureThe density was adjusted suitably based on the constants, to have a period of 2*pi. On calculating the RHS of the x-momentum Navier Stokes based on these values given and comparing it with my answer (calculated by hand), I obtained a maximum error of the order of E-03. Further, using these values as initial values of the variables and moving forward in time by a Runge-Kutta 4 scheme, I get values of the density that seem to diverge very quickly. After about 30 time steps, I get NaNs.Is there a specific reason why I notice a decrease in precision when non trigonometric periodic functions are used ?Is 1. related to why my code seems to produce unstable results when marching forward in time ?I wouldn't mind pasting the code here but it's pretty large.I thought I would plot the initial density and its variation. But turns out I can't as I do not have enough reputation to do so.The initial plot (@t = 0.0s) is a density plot that looks like a rectangular wave with the tanh functions used to smoothen the wave at the various corners.At around t = 0.10s (the time step is 0.01s so, after 10 iterations), it develops spikes and becomes non-differentiable (still continuous). | precision loss in non-trigonometric, periodic functions using FFTW and NaNs after marching forward in time (Fortran) | fortran;navier stokes;precision;fourier transform;fftw | There are three issues that are likely to cause such problems in pseudospectral methods:Gibbs oscillationsAliasingTime step too largeIn any case you likely develop oscillations in the solution until some point ends up with a negative density, resulting in a NaN when computing the pressure or sound speed or some other term. The solution to 3 is obvious, decrease the time step until the time integration is stable. The other two are more nuanced.Gibbs oscillationsGibbs oscillations arise when computing the Fourier series of discontinuous functions. Gibbs oscillations arise in the derivatives if the function is non-smooth. If you have large jumps in your initial conditions then the Fourier series will match the values at grid points exactly, but the derivative will have large oscillations, leading to loss of precision in the derivative (right hand side) computations. See the image below for a demonstration of this, the values match but the derivative does not. As a rule of thumb, jumps must be smoothed out over about 10 grid to prevent this behavior.Even if your initial conditions are smooth on the scale of the grid, the state variables may quickly steepen. In compressible Navier-Stokes, the viscous terms act to prevent shocks from forming, but if your simulation is not sufficiently resolved you will still develop jumps in your simulation. Sufficiently resolved means having grid spacing small enough to capture the viscous dissipation, which can be estimated by looking at the Kolmogorov scale, see this PDF. This quickly leads to large, non-physical oscillations and a divergent solution.AliasingAliasing occurs in pseudospectral methods due to the presence of nonlinear terms (e.g. $u u_x$) in the evolution equation. Computation of the derivatives in spectral space assumes that you are resolving a certain number of wavelengths. However, nonlinear terms continuously generate higher and higher wavenumbers. In a discrete problem, these higher wavenumbers are aliased back to affect the lower wavenumbers that can actually be represented at the chosen resolution. This corrupts the lower wavenumber values and can quickly lead to oscillations, non-physical results, and the simulation blowing up.A simple demonstration of how nonlinear terms generate higher wavenumbers, and how those wavenumbers are aliased to lower wavenumbers is shown in the following scenario (see image below):Take a grid of 7 points on the interval [0,1). Let $a = \cos(6\pi x )$ and $b = \sin(6\pi x)$. These terms both have (angular) frequencies of $6\pi$. The term$$ab = \cos(6\pi x )\sin(6\pi x ) = \frac{1}{2}\sin(12\pi x)$$has frequency $12\pi$. This frequency cannot be resolved on the chosen grid, but the values of $ab$ on the grid are equal to the values of $-\sin(2\pi x)/2$ on the grid. So instead of a $12\pi$ frequency component (which is not captured in the discretized space), the result of $ab$ appears as a $2\pi$ frequency component.There are multiple options available to prevent aliasing from corrupting your results, commonly termed dealiasing. The most common methods are zero padding (3/2-rule, effectively increasing grid resolution before nonlinear multiplications and then discarding the higher frequencies), 2/3-rule truncation (zeroing out the highest wavenumbers before nonlinear multiplications, original paper), or filtering procedures (e.g. this method).Additionally, there is evidence that for well resolved simulations dealiasing is not crucial since the highest wavenumbers components (which may produce aliasing) are small due to the viscous dissipation.This presentation (PDF) also provides a good overview of dealiasing, including some of the history. |
_unix.336878 | I have strange issue with alarms, which seems not to be supported.I can use rtc0 timer, but not alarms.Trying to do root@w812a_kk:/ # busybox rtcwake -s 10rtcwake: /dev/rtc0 not enabled for wakeup events1|root@w812a_kk:/ #then trying to compile a code which does timer, and alarm, I get invalid argument onioctl(fd, RTC_AIE_ON, 0);I also see that wakeup entry is missing:/sys/devices/platform/mt-rtc/rtc/rtc0/sys/devices/platform/mt-rtc/rtc/rtc0/dev/sys/devices/platform/mt-rtc/rtc/rtc0/date/sys/devices/platform/mt-rtc/rtc/rtc0/name/sys/devices/platform/mt-rtc/rtc/rtc0/time/sys/devices/platform/mt-rtc/rtc/rtc0/power/sys/devices/platform/mt-rtc/rtc/rtc0/since_epoch/sys/devices/platform/mt-rtc/rtc/rtc0/device/sys/devices/platform/mt-rtc/rtc/rtc0/subsystem/sys/devices/platform/mt-rtc/rtc/rtc0/hctosys/sys/devices/platform/mt-rtc/rtc/rtc0/max_user_freq/sys/devices/platform/mt-rtc/rtc/rtc0/uevent/sys/class/rtc/rtc0How can I enable alarms ?ThanksRan | Timer - without alarm and wakeup support? | android;time | null |
_unix.199202 | Without programs open, my computer uses about 512M of memory. Yesterday, I had nothing open, yet 2 GB of mem use (used - cache = 2153): total used free shared buffers cachedMem: 3261 2875 386 30 199 523-/+ buffers/cache: 2153 1108Swap: 8187 0 8187Top showed no processes taking this up:top - 23:10:38 up 1 day, 14:35, 3 users, load average: 0,31, 0,94, 1,29Tasks: 172 total, 3 running, 169 sleeping, 0 stopped, 0 zombie%Cpu(s): 6,5 us, 4,2 sy, 0,0 ni, 89,1 id, 0,1 wa, 0,0 hi, 0,1 si, 0,0 stKiB Mem: 3340164 total, 2937728 used, 402436 free, 201484 buffersKiB Swap: 8384444 total, 180 used, 8384264 free. 531636 cached Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 2520 halfgaar 20 0 3869744 173620 38568 S 1,6 5,2 52:20.03 plasma-desktop 1535 root 20 0 246420 108512 40420 S 2,0 3,2 22:36.65 Xorg 2665 halfgaar 20 0 1354660 50624 15116 R 0,0 1,5 0:10.08 krunner 2513 halfgaar 20 0 2966468 48564 19280 S 0,0 1,5 0:34.62 kwin 2306 halfgaar 20 0 1329360 41448 12488 S 0,0 1,2 0:09.80 kded4 2675 halfgaar 20 0 796712 37360 13804 S 0,0 1,1 0:04.23 kmix 2619 halfgaar 20 0 649136 34160 14204 S 0,0 1,0 0:00.95 akonadi_mailfil 2629 halfgaar 20 0 621348 33860 13876 S 0,0 1,0 0:00.88 akonadi_sendlat 2562 halfgaar 20 0 1242180 33212 2504 S 0,2 1,0 3:20.05 mysqld 2611 halfgaar 20 0 649132 33048 14140 S 0,0 1,0 0:01.29 akonadi_archive18552 halfgaar 20 0 508376 32948 24108 S 2,6 1,0 0:02.23 konsole 2645 halfgaar 20 0 506340 32204 8796 S 0,0 1,0 0:05.13 mintUpdate 2626 halfgaar 20 0 552648 31768 14152 S 0,0 1,0 0:00.93 akonadi_notes_a 2430 halfgaar 20 0 556864 30052 9484 S 0,0 0,9 0:10.57 ksmserver 2546 halfgaar 20 0 866520 28528 12584 S 0,0 0,9 0:04.34 knotify4 2302 halfgaar 20 0 382404 26896 10112 S 0,0 0,8 0:01.17 kdeinit4 2304 halfgaar 20 0 387792 23516 4892 S 0,0 0,7 0:00.55 klauncher 2648 halfgaar 20 0 541576 22824 13864 S 0,0 0,7 0:01.36 polkit-kde-auth 2623 halfgaar 20 0 390412 19216 13712 S 0,0 0,6 0:00.79 akonadi_newmail 2615 halfgaar 20 0 340388 18200 13276 S 0,0 0,5 0:00.75 akonadi_maildis 2621 halfgaar 20 0 303972 17884 13272 S 0,0 0,5 0:00.70 akonadi_migrati 2612 halfgaar 20 0 306052 17856 13188 S 0,0 0,5 0:00.71 akonadi_followu 2606 halfgaar 20 0 327700 16772 12600 S 0,0 0,5 0:00.53 akonadi_agent_l 2613 halfgaar 20 0 321704 16740 12576 S 0,0 0,5 0:00.52 akonadi_agent_l 2614 halfgaar 20 0 327680 16560 12420 S 0,0 0,5 0:00.54 akonadi_agent_l 2325 halfgaar 20 0 735344 14928 10116 S 0,0 0,4 0:04.63 kactivitymanage 2313 halfgaar 20 0 282096 14832 9488 S 0,0 0,4 0:00.74 kglobalaccel 2554 halfgaar 20 0 276912 14472 10148 S 0,0 0,4 0:02.04 kuiserverJust to try, I dropped caches:echo 3 > /proc/sys/vm/drop_cachesAnd memory usage dropped: total used free shared buffers cachedMem: 3261 850 2411 30 1 79-/+ buffers/cache: 770 2491Swap: 8187 0 8187How can this be? Why is cache being stored in a way the kernel thinks it's not cache? Can it be the cache of my ecryptfs encrypted home dir? I did just run a backup of that, so a lot of files and meta data on it were cached.Linux Mint 17.1Kernel 3.13.0-37 | What memory is not used by processes and freed by `echo 3 > /proc/sys/vm/drop_caches`? | linux;memory;cache | Writing a 1 to drop_caches only drops the ( data ) cache. The 3 also drops the dentry cache, or cache of names of files on the disk. If you had recently been working with directories containing many small files, that would account for it. |
_webmaster.76556 | At my company, our website is hosted with GoDaddy's shared hosting service. I was tidying up the html folder today and noticed a file called hitnodes.php which I hadn't noticed before. It was only 16 lines long, and the code seemed innocuous, and just printed out the hostname of the server we're on and a bunch of dots.I was pretty sure we didn't put it there, which lead me to believe it was from GoDaddy, so I called their support to see if they knew what it was. The guy I talked to just said oh, I'll delete that, and when I asked what it was, he said that he wasn't allowed to tell me (!), and that he had just deleted it. When I pressed him as to why there was a file in our site that he couldn't tell us about, he just said it had to do with server maintenance and he couldn't tell me anything else about it.So half out of concern that this could be part of some exploit that he didn't want to spook me about, and half out of pure curiosity, I've been trying to find out what this script is for, but the most I could turn up was this page talking about a method to quickly check for errors on a 4GH or Grid system. I didn't really follow what the author of that blog was talking about, and I was hoping that someone here might have a good explanation for the purpose of this script and how it works, and maybe some idea of why the GoDaddy representative was being so cagey about it. If it was just to check if a node was having problems, why not say Oh, that was so we could quickly see if the server was having problems.? Not exactly state secrets...Here's the code reproduced for your scrutiny:<?php if ( $_SERVER[OS] == Windows_NT ) { $hostname = strtolower($_SERVER[COMPUTERNAME]); } else { $hostname = `hostname`; $hostnamearray = explode('.', $hostname); $hostname = $hostnamearray[0]; } if ( !preg_match(/[0-9]{2,4}/, $hostname, $match) ) die(Failed to detect node); $node = $match[0]; if ( preg_match(/^0/, $node) ) $node += 1000; header(Content-Length: . $node); $response = $hostname . <br />Padding: ; $response = $response . str_repeat('.', $node - strlen($response)); echo $response;?> | What is 'hitnodes.php' on a GoDaddy shared hosting server? | php;godaddy;shared hosting | This is a file used by GoDaddy's hosting department to periodically test if accounts on their Fourth-Generation Hosting (4GH) systems are reachable. 4GH was GoDaddy's precursor to cloud hosting, as can be read about here:Web Hosting pools the resources of many servers and your site's content resides on multiple servers. This networked system helps achieve a high reliabilitybeyond 99.9%for your website because if one server shuts down, only a fraction of the total resources are lost.In this system configuration, each account can be accessed via a 4 different nodes on a grid hosting system (hence the abbreviation 4GH), allowing for redundancy and performance increases via load balancing over standard hosting.The hitnodes.php script for Linux (and hitnodes.aspx for Windows) is aptly named, since it's used by their hosting department to see if sites are reachable (i.e., can be hit) on these nodes. By taking a look at the page size returned by this script, their IT department (and you as well), can see what node a site is being served on. Most 4GH accounts end up getting migrated to different server configurations depending on usage (as an upgrade), so they likely use this script for gauging that as well.I've seen this file in accounts before, and as the GoDaddy representative relayed, it can just be deleted without any consequences. I'm sure the rep did not want to elaborate further on how this script is used because placing files in accounts is usually not very well received by customers, and I suppose it could be used to test if a hack or DDoS was successful for a particular node/server. I do not think 4GH accounts are sold by GoDaddy anymore, since they've replaced them with cPanel (for Linux) and Plesk (for Windows) accounts instead of using their in-house control panel, so this file likely won't be seen as much in the future. |
_unix.260202 | In order to reduce my notebook's power consumption I am using PowerTOP 2.5.hardware: Thinkpad W540os: Linux Mint 17.3 Rosakernel: 3.16.0-38-genericI noticed that cinnamon and i915 are the primary causes for cpu wakeups:Any idea how I could configure them differently so they cause less cpu wakeups? | Reduce CPU wakeups by cinnamon and i915 | graphics;cinnamon;power management;laptop;i915 | null |
_unix.38110 | Why am I receiving this error message on Kubuntu since I upgraded to 12.04 and how can I make it stop appearing? It appears as a pop up balloon above the system tray.Mail Dispatcher Agent: Could not access the outbox folder (Unknow error. (Failed to fetch the resource collection.)). | Mail Dispatcher Agent: Could not access the outbox folder (Unknow error. (Failed to fetch the resource collection.)) | ubuntu;kde;email;kubuntu | This forum thread discusses the issue and includes various solutions/workarounds, such as deleting /.config/akonadi,Rather than removing the akonadi configuration, I edited ~/.config/akonadi/aknoadiserverrc and changed StartServer=true to StartServer=false, and then rebooted (although logging out and back in should have been sufficient). (1)or this oneHi, I had the same problem here, also on a Kubuntu system that has undergone many distribution upgrades.I found the following solution without having to delete Akonadi's configuration or disabling it completely: In the Akonadi configuration dialog (where you configure the Akonadi ressources), I had an e-mail ressource named Local Folder. Deleting it made the startup warning go away. (2) |
_codereview.47124 | This code animates my main game sprite by increasing the animation frame. First I check if the character is moving, then I increase the animation counter until it reaches the desired speed, and then if so, I increase the animation frame.How can I make it more elegant and optimised in terms of speed? if (moving){ anispeed++; if (anispeed==animaxspeed){ anispeed=0; animationframe++; if (animationframe==3) animationframe=0; } | Game sprite animation | java;animation | null |
_cogsci.7871 | The Word Wide Web Consortium (W3C) has a formula for the contrast ratio of any two arbitrary colors, which they use to set minimum standards for text legibility: http://www.w3.org/TR/WCAG20-TECHS/G18.htmlStep 1 of the process is relatively straight-forward - it uses a well known conversion from sRGB to XYZ and keeps the Y component for the next step. Step 2 is the same for the second color.My question comes in step 3, where the ratio is determined as (L1 + 0.05) / (L2 + 0.05) with L1 and L2 being the luminances of the lighter and darker colors from steps 1 and 2. Where does the magic constant 0.05 come from? It's obvious that some constant offset is needed, otherwise pure black would have infinite contrast against every other color. But how is it derived?Also, does this contrast ratio reasonably describe how easy it is to discern text against a background? Or is there a different formula that would be better?I ask because it seems to favor black over white - where I see better results with white text, the formula suggests black is better. I'd like a clearer understanding. | What is the source for the W3C's Contrast Ratio formula? | vision | null |
_codereview.79279 | As nobody has provided input, I have updated the question. (The next one is coming soon)Coding to this interface:namespace ThorsAnvil{ namespace Serialization {class ParserInterface{ public: enum class ParserToken {Error, DocStart, DocEnd, MapStart, MapEnd, ArrayStart, ArrayEnd, Key, Value}; std::istream& input; ParserToken pushBack; ParserInterface(std::istream& input) : input(input) , pushBack(ParserToken::Error) {} virtual ~ParserInterface() {} ParserToken getToken(); void pushBackToken(ParserToken token); virtual ParserToken getNextToken() = 0; virtual std::string getKey() = 0; virtual void getValue(short int&) = 0; virtual void getValue(int&) = 0; virtual void getValue(long int&) = 0; virtual void getValue(long long int&) = 0; virtual void getValue(unsigned short int&) = 0; virtual void getValue(unsigned int&) = 0; virtual void getValue(unsigned long int&) = 0; virtual void getValue(unsigned long long int&)= 0; virtual void getValue(float&) = 0; virtual void getValue(double&) = 0; virtual void getValue(long double&) = 0; virtual void getValue(bool&) = 0; virtual void getValue(std::string&) = 0;}; }}The Json Implementation is:JsonParser.h#ifndef THORS_ANVIL_SERIALIZATION_JSON_PARSER_H#define THORS_ANVIL_SERIALIZATION_JSON_PARSER_H#include Serialize.h#include JsonLexer.h#include <istream>#include <string>#include <vector>namespace ThorsAnvil{ namespace Serialization {class JsonParser: public ParserInterface{ enum State {Error, Init, OpenM, Key, Colon, ValueM, CommaM, CloseM, OpenA, ValueA, CommaA, CloseA, Done}; JsonLexerFlexLexer lexer; std::vector<State> parrentState; State currentEnd; State currentState; bool started; std::string getString(); template<typename T> T scan(); public: JsonParser(std::istream& stream); virtual ParserToken getNextToken() override; virtual std::string getKey() override; virtual void getValue(short int& value) override; virtual void getValue(int& value) override; virtual void getValue(long int& value) override; virtual void getValue(long long int& value) override; virtual void getValue(unsigned short int& value) override; virtual void getValue(unsigned int& value) override; virtual void getValue(unsigned long int& value) override; virtual void getValue(unsigned long long int& value) override; virtual void getValue(float& value) override; virtual void getValue(double& value) override; virtual void getValue(long double& value) override; virtual void getValue(bool& value) override; virtual void getValue(std::string& value) override;}; }}#endifJsonParser.cpp#include JsonParser.h#include JsonLexemes.h#include UnicodeIterator.h#include <map>#include <cstdlib>// enum class ParserToken {Error, MapStart, MapEnd, ArrayStart, ArrayEnd, Key, Value};using namespace ThorsAnvil::Serialization;using ParserToken = ParserInterface::ParserToken;JsonParser::JsonParser(std::istream& stream) : ParserInterface(stream) , lexer(&stream) , currentEnd(Done) , currentState(Init) , started(false){}ParserToken JsonParser::getNextToken(){ /* Handle States were we are not going to read any more */ if (!started) { started = true; return ParserToken::DocStart; } if (currentState == Done) { currentState = Error; return ParserToken::DocEnd; } if (currentState == Error) { return ParserToken::Error; } // Convert Lexer tokens into smaller range 0-12 static std::map<int, int> tokenIndex = {0, 0}, {'{', 1}, {'}', 2}, {'[', 3}, {']', 4}, {',', 5}, {':', 6}, {ThorsAnvil::Serialize::JSON_TRUE, 7}, {ThorsAnvil::Serialize::JSON_FALSE, 8}, {ThorsAnvil::Serialize::JSON_NULL, 9}, {ThorsAnvil::Serialize::JSON_STRING, 10}, {ThorsAnvil::Serialize::JSON_INTEGER, 11}, {ThorsAnvil::Serialize::JSON_FLOAT, 12} }; // State transition table; static State stateTable[][13] = { /* Token -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 */ /* Error */ { Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error }, /* Init */ { Error, OpenM, Error, OpenA, Error, Error, Error, Error, Error, Error, Error, Error, Error }, /* OpenM */ { Error, Error, CloseM, Error, Error, Error, Error, Error, Error, Error, Key, Error, Error }, /* Key */ { Error, Error, Error, Error, Error, Error, Colon, Error, Error, Error, Error, Error, Error }, /* Colon */ { Error, OpenM, Error, OpenA, Error, Error, Error, ValueM, ValueM, ValueM, ValueM, ValueM, ValueM }, /* ValueM*/ { Error, Error, CloseM, Error, Error, CommaM, Error, Error, Error, Error, Error, Error, Error }, /* CommaM*/ { Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Key, Error, Error }, /* CloseM*/ { Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error }, /* OpenA */ { Error, OpenM, Error, OpenA, CloseA, Error, Error, ValueA, ValueA, ValueA, ValueA, ValueA, ValueA }, /* ValueA*/ { Error, Error, Error, Error, CloseA, CommaA, Error, Error, Error, Error, Error, Error, Error }, /* CommaA*/ { Error, OpenM, Error, OpenA, Error, Error, Error, ValueA, ValueA, ValueA, ValueA, ValueA, ValueA }, /* CloseA*/ { Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error }, /* Done */ { Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error, Error }, }; // Read the next token and update the state. int token = lexer.yylex(); int index = tokenIndex[token]; currentState = stateTable[currentState][index]; switch(currentState) { // These states should be impossible to get too case Init: throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Got into Init State); case Done: throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Got into Done State); // The states that we actually want to return case Error: return ParserToken::Error; case Key: return ParserToken::Key; case ValueM: return ParserToken::Value; case ValueA: return ParserToken::Value; // Punctuation. // Parse it but it is not the actual result // So try and get the next token. case Colon: return getNextToken(); case CommaM: return getNextToken(); case CommaA: return getNextToken(); // We are going into a containing object. // Push the state we want when the containing // object is complete then set the state we will // need if we open another container. case OpenM: parrentState.push_back(currentEnd); currentEnd = ValueM; return ParserToken::MapStart; case OpenA: parrentState.push_back(currentEnd); currentEnd = ValueA; return ParserToken::ArrayStart; // We are leaving the containing object. // Pop the state we previously saved. case CloseM: currentEnd = currentState = parrentState.back(); parrentState.pop_back(); return ParserToken::MapEnd; case CloseA: currentEnd = currentState = parrentState.back(); parrentState.pop_back(); return ParserToken::ArrayEnd; // Anything else just break. default: break; } // If we hit anything else there was a serious problem in the // parser itself. throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Reached an Unnamed State);};std::string JsonParser::getString(){ if (lexer.YYLeng() < 2 || lexer.YYText()[0] != '' || lexer.YYText()[lexer.YYLeng()-1] != '') { throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Not a String value); } // Remember to drop the quotes return std::string(make_UnicodeWrapperIterator(lexer.YYText() + 1), make_UnicodeWrapperIterator(lexer.YYText() + lexer.YYLeng() - 1));}std::string JsonParser::getKey(){ return getString();}template<typename T>inline T JsonParser::scan(){ char* end; T value = scanValue<T>(lexer.YYText(), &end); if (lexer.YYText() + lexer.YYLeng() != end) { throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Not an integer); } return value;}void JsonParser::getValue(short& value) {value = scan<short>();}void JsonParser::getValue(int& value) {value = scan<int>();}void JsonParser::getValue(long& value) {value = scan<long>();}void JsonParser::getValue(long long& value) {value = scan<long long>();}void JsonParser::getValue(unsigned short& value) {value = scan<unsigned short>();}void JsonParser::getValue(unsigned int& value) {value = scan<unsigned int>();}void JsonParser::getValue(unsigned long& value) {value = scan<unsigned long>();}void JsonParser::getValue(unsigned long long& value) {value = scan<unsigned long long>();}void JsonParser::getValue(float& value) {value = scan<float>();}void JsonParser::getValue(double& value) {value = scan<double>();}void JsonParser::getValue(long double& value) {value = scan<long double>();}void JsonParser::getValue(bool& value){ if (lexer.YYLeng() == 4 && strncmp(lexer.YYText(), true, 4) == 0) { value = true; } else if (lexer.YYLeng() == 5 && strncmp(lexer.YYText(), false, 5) == 0) { value = false; } else { throw std::runtime_error(ThorsAnvil::Serialize::JsonParser: Not a bool); }}void JsonParser::getValue(std::string& value){ value = getString();} | Serialization: Step 1 Json Parser | c++;json | null |
_unix.280511 | I have to compare two MySql database data, I want to compare two MySql schema and find out the difference between both schema.I have created two variables Old_Release_DB and New_Release_DB. In Old_Release_DB I have stored old release schema than after some modification like I deleted some column, Added some column, Renamed some column, changed column property like increase datatype size (ex: varchar(10) to varchar(50)). Than it became new release schema that I have stored in New_Release_DB.Now I want to Table Name, list of column name which has changed in New_Release_DB, and changes along with column name.Example,Table_A Column_Name Add(if it is added),Table_A Column_Name Delete(if it is deleted),Table_A Column_Name Change(if its property has changed)I am trying it in Shell script in Linux, But I am not getting it. Please let me know If I can use other script like python or java. | How to compare two tables and find the difference between in Linux using shell script? | linux;shell script | null |
_scicomp.14469 | Is it possible to simulate interaction of Smart Fluids with Solids? Is there a software capable of doing so?What I Know:The two software that I know of are Autodesk Simulation Mechanical and Computational Fluid Dynamics. The brochures and information about these software do not mention Smart Fluids anywhere.What I need to Know:Alternative Open Source Software that can do the job specified. If they can't, then I would like to know a way to do so.What I need to Do: Study effects of electric current on Smart Fluids flowing through solid cracks.PS:Is it possible to include Radiation and Radioactivity in the scenario also?Thanks to everyone who read this question. Please comment to point out my mistakes as I am relatively new to Stack Exchange and would like to know how to use it properly. | Simulating interaction of Smart Fluids with Solids | fluid dynamics;simulation;electromagnetics;open source | null |
_codereview.68782 | Edit: I am hoping to get some review / make sure I am understanding dynamic programming correctly.I am trying to print out all additive numbers up to digits n using dynamic programming. Additive numbers are those like 123, 1235, etc., where the sum of every 2 digits from left to right is equal to the third digit. In this definition, non-trivial additive numbers must necessarily be at least 3 digits long, though for numbers of 2 digits or less one could trivially print out all digits 0-99. Furthermore, this definition implies the set of additive numbers is finite and relatively tiny. If there is a better definition of an additive number or I have misunderstood it, feel free to point out. I believe dynamic programming is a good approach to this problem, because the solutions of n - 1 need to be re-used to compute the solutions to n. A brute force algorithm is possible, but I think far more inefficient. Here is my solution in Python. It will print them all out and also return the trellis that contains the solutions for each digit. Note that for n >= 9, there are no more additive numbers.# -*- coding: utf-8 -*-Dynamic programmingBASE_CASE = 3def print_additive_numbers(n=BASE_CASE): Prints all additive numbers up to n digits Additive numbers are numbers of the form 123, 1235, etc. where the sum of every 2 digits is equal to the third digit in the digit expansion of the number. We use dynamic programming to iteratively generate additive numbers for increasing digits, as the solutions to n = 3 are re-used for n = 4, n = 5, etc. Args: n: the maximum number of digits for each representation Returns: A dictionary mapping each number of digits to all possible additive numbers. if n < BASE_CASE: raise ValueError, additive numbers always have 3 or more digits #build the initial trellis trellis = {} trellis[BASE_CASE] = {} for i in xrange(1, 9): row = [] for j in xrange(0, 9): if i + j <= 9: print str(i) + str(j) + str(i + j) row.append(str(j) + str(i + j)) trellis[BASE_CASE][i] = row for m in xrange(BASE_CASE + 1, n + 1): trellis[m] = {} for key in trellis[m - 1].keys(): row = [] for digits in trellis[m - 1][key]: first_digit = int(digits[-2]) second_digit = int(digits[-1]) new_digit = first_digit + second_digit if new_digit <= 9: row.append(digits + str(new_digit)) print str(key) + digits + str(new_digit) trellis[m][key] = row return trellist = print_additive_numbers(9) | Dynamic Programming for printing additive numbers up to digits n | python;dynamic programming | null |
_unix.258197 | I have the following string:col1|col2|col3+++++++++++A|1|a B|2|b C|3|c D|4|d (3 rows)I want to split this string so as to remove the string in the beginning till the last + symbol and then remove the tail end which is (XYZ rows)so the string becomes A|1|a B|2|b C|3|c D|4|dNow, I want to split this string into multiple arrays that look like thisA 1 a B 2 b C 3 c D 4 dso that I can iterate over each row using for loop to do some processing.How can I do this using sed or grep?I tried this for the first pass but it didn't workecho $string | sed 's/([0-9])rows//' | sed 's/[^+]//'but it didn't work. | How to replace string within parenthesis using using sed | text processing | By variable expansion in bash:str=col1|col2|col3+++++++++++A|1|a B|2|b C|3|c D|4|d (3 rows)str=${str% (*}str=${str##*+}str=${str// /}str=${str//|/ }Or by sedsed 's/.*+\(.*\S\)\s\+(.*/\1/;y/ |/\n /' <<\eofcol1|col2|col3+++++++++++A|1|a B|2|b C|3|c D|4|d (3 rows)eofA 1 aB 2 bC 3 cD 4 d |
_unix.121674 | Gnome desktop environment stopped working after change in libudev.so.0 in /lib/x86_64-linux-gnu/ and showing error:cannot open shared librariesI am trying too hard to get rid of this problem but unable to solve. I have 64 bit kali debian based linux(~).Now I donot have any files realted to libudev.so.* in /lib/x86_64-linux-gnu/. From this my gdm is also not working. | Gnome desktop environment stopped working in kali linux(debian based) | debian;gdm;kali linux | Solved after long try by just making live cd of kali linux and copy libudev.so.0.13.0, libudev.so.0(link) and paste it in /lib/x86_64-login-gnu/. |
_webapps.99617 | It looks like that non-UK visitors are being auto-redirected from https://bbc.co.uk to http://bbc.com. (Notice how the latter site isnt HTTPS, which makes it doubly annoying.)Is there a way to prevent this? I would like to browse their UK site. | How to prevent BBC UK from auto-redicrecting to the international site? | bbc | null |
_softwareengineering.147861 | My goal is to include modules sources files into War file.I read this explanation on the maven official site:http://maven.apache.org/plugins/maven-assembly-plugin/examples/multimodule/module-source-inclusion-simple.htmlI wonder if it's the only way to include all sources files contained within all modules.Can't the simple maven-plugin-war do the same ? | Including Module Source files into War file using Maven | java;web applications;maven | The Maven plugins for packaging can be confusing to work with. You could write a small ANT script and call it from a plugin execution. I sometimes do this if I have complex packaging requirements. It's not elegant, but it gives you full control of the packaging process. |
_unix.3575 | Is this possible? | Display transfer speed when performing cp from the command line? | command line;cp;file transfer | null |
_unix.59949 | At least every Linux system that I worked with used the convention to switch to the non-graphical consoles by Ctrl-Alt-F1, Ctrl-Alt-F2 and so on.Recently, I installed CentOS 6.3 on a machine. The installation is non-customized and uses Gnome 2.To my surprise Alt-F4 switches to console. Alt-F1 then brings you back to the XServer. How can I change the keybinding to Ctrl-Alt instead of simply Alt?It also seems to bypass Gnome's key bindings. In Gnome, I tried to define Alt-F4 as close window, but it does not work but still switches to the console. | CentOS: Avoid that ALT-F4 switches to console | centos;xorg;keyboard shortcuts | The problem vanished after a restart. I can only speculate about the reasons. It is possible to set CTRL per software. Maybe that happened. I didn't mess around with keymap or anything like that, so I don't know what caused the problem.Sorry, for the false alarm. :-(Edit:From time to time, the problem repeats. It vanishes with a restart. I still don't know why.Update:Had the problem again on two Arch Linux systems. It occurred exactly after a Linux kernel update, but before the system was rebooted. After the reboot, the problem was gone on both systems. |
_softwareengineering.15842 | I am thinking about creating a silverlight application, and I lack the skills to create a good looking UI.Today's graphic designers usually know HTML and CSS and thus save me the trouble of doing something I am not very good with.Is this the same case with XAML?Do I have to hire two employees for this job? | Are XAML UI designers common today? | design;gui | Silverlight is a pretty cool technology, but I'm seriously concerned about its future. However, if you want a cool UI done in XAML... you have several options. Hire a Silverlight/WPF dev and hope they also design / See #3Hire a UX designer with XAML skillzHire a great graphic designer and then hire #1 OR you can use the built-in Ai/PSD to XAML tools in Expression Studio (design).Tons of options, if you are a small company you may even qualify for Bizspark ( a free version of Expression Studio). Good luck. |
_vi.11602 | I've turned on vim's relative line numbers, it starts from 0 but doing somthing like 10dd means I only get up to line 9, leaving the last one behind (becuase it's 10 including the current line). Yes, I know, It's only a super simple equation (10 + 1) but it's time taken up when I just want to check the number in the gutter and instantly get the number.Is there a way to change the number the relative numbers start on? From 0 to 1? I've googled but I can't find anything and I did check out VIM's help page on the 'relativenumber' and 'number_relativenumber' sections but I couldn't see anything on it (or I probably missed it if it's there).So is there any way to do this or is just not possible? | In VIM, Change the number that relative lines numbers start from | options;line numbers | Well, vim is open source. If you clone it from:git clone https://github.com/vim/vim.gitYou can make the following changes to src/screen.c to do what you want:diff --git a/src/screen.c b/src/screen.cindex 20a778a68..38d4368a9 100644--- a/src/screen.c+++ b/src/screen.c@@ -2521,8 +2521,8 @@ fold_line( else { /* 'relativenumber', don't use negative numbers */- num = labs((long)get_cursor_rel_lnum(wp, lnum));- if (num == 0 && wp->w_p_nu && wp->w_p_rnu)+ num = labs((long)get_cursor_rel_lnum(wp, lnum)) + 1;+ if (num == 1 && wp->w_p_nu && wp->w_p_rnu) { /* 'number' + 'relativenumber': cursor line shows absolute * line number */@@ -3745,8 +3745,8 @@ win_line( else { /* 'relativenumber', don't use negative numbers */- num = labs((long)get_cursor_rel_lnum(wp, lnum));- if (num == 0 && wp->w_p_nu && wp->w_p_rnu)+ num = labs((long)get_cursor_rel_lnum(wp, lnum)) + 1;+ if (num == 1 && wp->w_p_nu && wp->w_p_rnu) { /* 'number' + 'relativenumber' */ num = lnum;But sorry, examining the source confirms there's no existing option available to do what you want. |
_unix.47682 | I'm currently installing Archlinux on my new computer but Windows seems to be installed using UEFI and I'm quite in a rush right now and I don't have time to install Archlinux using EFISTUB or something like that (it seems very painfull to perform).So here is my question : Is there a live persistant distribution based on Archlinux (and quite easy to install) ?Except FaunOS because I can't find it anywhere on the internet (it seems that the project has been discontinued). In the best case I would like to have a Gnome3 desktop. Can someone help me ? =) | Is there an Arch based live persistant distribution? | arch linux;live usb | Archbang and Manjaro both are distroes based on Arch-Linux with an easy to use install script, both have ability to be used as a Live system using a CD/DVD drive or any USB drive;In USB mode there are some way to install ArchBang as a persistent system.Here is a tutorial on how to make a live persistent distribution. Take look at chakra, it has a very nice installer. |
_softwareengineering.140331 | I wrote some sorting algorithms for a class assignment and I also wrote a few tests to make sure the algorithms were implemented correctly. My tests are only like 10 lines long and there are 3 of them but only 1 line changes between the 3 so there is a lot of repeated code. Is it better to refactor this code into another method that is then called from each test? Wouldn't I then need to write another test to test the refactoring? Some of the variables can even be moved up to the class level. Should testing classes and methods follow the same rules as regular classes/methods?Here's an example: [TestMethod] public void MergeSortAssertArrayIsSorted() { int[] a = new int[1000]; Random rand = new Random(DateTime.Now.Millisecond); for(int i = 0; i < a.Length; i++) { a[i] = rand.Next(Int16.MaxValue); } int[] b = new int[1000]; a.CopyTo(b, 0); List<int> temp = b.ToList(); temp.Sort(); b = temp.ToArray(); MergeSort merge = new MergeSort(); merge.mergeSort(a, 0, a.Length - 1); CollectionAssert.AreEqual(a, b); } [TestMethod] public void InsertionSortAssertArrayIsSorted() { int[] a = new int[1000]; Random rand = new Random(DateTime.Now.Millisecond); for (int i = 0; i < a.Length; i++) { a[i] = rand.Next(Int16.MaxValue); } int[] b = new int[1000]; a.CopyTo(b, 0); List<int> temp = b.ToList(); temp.Sort(); b = temp.ToArray(); InsertionSort merge = new InsertionSort(); merge.insertionSort(a); CollectionAssert.AreEqual(a, b); } | Is it OK to repeat code for unit tests? | testing;unit testing;code quality | Test code is still code and also needs to be maintained.If you need to change the copied logic, you need to do that in every place you copied it to, normally.DRY still applies. Wouldn't I then need to write another test to test the refactoring?Would you? And how do you know the tests you currently have are correct?You test the refactoring by running the tests. They should all have the same results. |
_unix.169928 | I am reading a tutorial that wants me to place a script file called script.sh into a folder called /etc/profile.d/. However, when I try to save the script.sh file in that directory, the gedit tool gives me an error stating that I do not have privileges to save in that folder. So I saved script.sh on the desktop temporarily. I cannot even view the contents of the /etc/ folder through the GUI. (Unless it is empty and I am seeing truly empty contents.) I can run the terminal as root by typing su - root, but what do I type to either move the script.sh file from the desktop to /etc/profile.d/script.sh or to open gedit in a way that lets me save it to /etc/profile.d/script.sh? | moving a file to a folder with root privileges in CentOS 7 | centos;files;root;gedit | If you have the sudo package try gksudo nautilus, otherwise use sudo mv -v /home/username/Desktop/script.sh /etc/profile.d/script.sh For more, try man mvsudo elevates the command following it temporarily to perform tasks like you describred. |
_webmaster.18336 | An SEO told me that he recently read of a Google SEO tool that shows actual QUESTIONS (rather than queries = Google keyword tool) that are typed into Google, based on the keywords one enters. Unfortunately, he could not remember the name of the tool nor where it was that linked to it. Since I run a Q&A site, such a tool would be extremely valuable to me for keyword optimization. Does anyone know of such a tool, or anything that is similar? Thank you in advance. | Google SEO tool that shows search questions based on keywords? | seo;google;keywords | This person might have been referring to WordTracker's Questions Tool. |
_softwareengineering.355941 | I'm a long-time Java programmer familiar with the Java Memory Model. I'm starting to learn C#, and based on what I've learned so far, the C# memory model seems to be very similar to the JMM. This validates my previous understanding that the JMM reflects the characteristics of architectures supported by the JVM. The language requirements reflect the weakest guarantees of all the supported architectures.But one difference I've noticed is in the way developers from Java and C# backgrounds talk about architectures. Where Java programmers speak of improperly synchronized code manifesting bugs on some architectures, C# programmers tend to be more specific. For example, this article names Itanium as having a weak memory model:The mainstream x86 and x64 processors implement a strong memory model where memory access is effectively volatile. ... The Itanium processor implements a weaker memory model.I've only worked on x86 and x64, and I never knew what architectures imposed the mysterious requirements of the JMM that never seemed to matter when I tried to demonstrate the effects of violating them. Now I know of one.What other architectures have weak memory models? | What architectures have weak memory models? | architecture;memory | Nearly all RISCs have weak memory ordering models. (Memory ordering is a better term for this because memory model is too broad.) That means an ordering between memory accesses shall be explicitly requested with barrier AKA fence instructions. For x86 (any bitness), most barriers (but not all) are implicit.Just in case, a Memory ordering topic is a good start. Another example of good description is C++ memory order constants. |
_opensource.650 | The point of using the GNU Affero General Public License (Version 3) is that it allows users who interact with the licensed software over a network to receive the source for that program (FSF).Section 13 of the AGPLv3.0 contains:[] if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version []It says if you modify. Does this really mean that the source only has to be made available if it was modified (assuming that I dont offer/distribute the application itself, i.e., its binary, at all)? Or am I missing something, maybe somewhere else in the license?In other words: I install a Web application licensed under the AGPLv3.0 on my server.I dont modify this application at all. I allow people to use it over the Web.Do I have to offer the source code of this application? | Do I have to offer the source of an AGPL (v3.0) licensed Web app even if I didnt modify it? | licensing;agpl 3.0;source code | I wrote to the FSF's licensing team about this question:[...] Does this [section 13] mean that if I run a *completely unmodified* AGPL-licensed program as a network service, I am *not* required to offer the source code to network users?And I received this response (bracketed phrase added by me):[...] If you haven't modified the software then you are not required to add that functionality [i.e., to download the source]. Of course, if the functionality to download the source is already in the unmodified software, it will already be there for everyone to enjoy.So, if you use an unmodified AGPL application that doesn't have download-source functionality, you are not required to add one or otherwise offer the source to users. If you do modify the software, of course, you are required to add a mechanism to allow users to download your modified source.As a practical matter, an author who cares about source-sharing enough to license code under the AGPL would probably include a mechanism or link to download the source in the original program. This is kind of an edge case, because it only applies when both (1) you want to use the AGPL software unmodified, and (2) the AGPL software doesn't already include a download-source mechanism. If either of those conditions is false, the software must (or already does) include a way to download the source. |
_webapps.22965 | In Gmail, I have the smart labels 'Bulk', 'Forums', 'Notifications'. I have a daily reminder email sent everyday that is now getting marked as 'Bulk' which is a correct categorization, however I want these to still show up in my inbox, without all the other 'Bulk' mail also showing in the inbox.Is there a way to do this? | How to prevent certain 'Bulk' labeled email from skipping the inbox? | gmail;gmail labels | I found that there wasn't a way, even with re-categorizing like the blog post suggests, to get messages to not end up in the Bulk label. Disabling smart filters and writing my own specific filters to move messages to a Bulk folder was the only way. |
_webmaster.29842 | I did everything asked of me in the following link: http://support.google.com/websiteoptimizer/bin/answer.py?hl=en&answer=77075But am still not seeing my Google Optimizer stats inside Google Analytics.Do both of my Account Ids have to be set differently or the same??? | How do I integrate Google Website Optimizer into my Google Analytics account? | google analytics;google website optimizer | null |
_unix.284123 | Do all threads of a specific process share the same status (D, R, S, ...) or may there be differences among these threads?If so, where in /proc do I find information about the status of a certain thread? I am reading the process status from the /proc/<PID>/status files at the moment. | Status of a threads vs. status of a process | process;thread | Different threads can certainly be in a different scheduler state at the same time. In fact, if they're all in the same state, that's a coincidence (except for stopped (Z), because that affects the whole process).The subdirectory /proc/PID/task contains a subdirectory per thread of the process. The files in this directory are mostly the same as in the per-process directory. Some of the information is just duplicated (e.g. memory-related information, environment, privileges, etc.). Information that's specific to a thread, such as the scheduler state (running/sleeping/IO/), can differ. |
_softwareengineering.203674 | So I've done a lot of research and found that Codecademy has been mentioned several times on other forums. I got stuck in and chose JavaScript through Codecademy most probably thinking it was 'Java' and I'm now slightly concerned that I have made a bad choice.. due to the fact that I see posts mentioning JavaScript teaches bad habits and so on...Should I stop and learn other languages offered on 'Codecademy'?Should I stop using codecademy altogether?Or finally should I just wait until I start my degree and pose as a blank canvas?All opinions wanted, thank you.P.s I'm not entirely certain what jobs I will be applying for in the future but to give some indication I don't believe it will be website development and more so on the game or application designing side of things | Should I be learning JavaScript before studying computer science? | java;javascript | null |
_cstheory.11620 | This is a generalisation of the following post: Existence of colouring matrices.As the base case turned out to be fairly straightforward (in essence, precisely equal to the existence of Sperner families), I am feeling a bit more optimistic about the general case as well. Let's see how far we can get.DefinitionLet's switch from the matrix notation to a function notation. Again, $[i] = \{1,2,...,i\}$.A function $f\colon [c]^d \to [k]$ is a $d$-dimensional $c$-to-$k$ colouring function, in notation $f\colon c \leadsto_d k$, if the following holds for all $x_1, x_2, ..., x_{d+1} \in [c]$ with $x_1 \ne x_2 \ne ... \ne x_{d+1}$: $$f(x_1,x_2,...,x_d) \ne f(x_2,x_3,...,x_{d+1}).$$We write $c \leadsto_d k$ if $f\colon c \leadsto_d k$ for some $f$.Now $c \leadsto k$ in the previous question is exactly equal to $c \leadsto_2 k$ in this question, as it is trivial to interpret a colouring matrix as a $2$-dimensional colouring function.An exampleThe $1$-dimensional case is trivial. We already saw examples of $2$-dimensional colouring functions in the previous question. Here is a simple example of a $3$-dimensional colouring function $f\colon k+1 \leadsto_3 k$, for any $k \ge 3$:$f(x,y,z) = y$ if $y \ne k+1$,$f(x,y,z) = \min ( \{1,2,3\} \setminus \{x,z\} )$ if $y = k+1$.(This can be interpreted as a greedy graph colouring algorithm, in the case of $2$-regular graphs; $y$ is the old colour of a node $v$, $x$ and $z$ are the old colours of its two neighbours, and $f(x,y,z)$ is the new colour of node $v$. In essence, nodes of colour $k+1$ pick the smallest free colour that is available in their neighbourhood.)CompositionLower-dimensional colouring functions can be easily composed into higher-dimensional colouring functions. For example, assume that $$f_1\colon c_0 \leadsto_2 c_1, \quad f_2\colon c_1 \leadsto_2 c_2.$$ Now we can construct a colouring function $$g\colon c_0 \leadsto_3 c_2$$ as follows: $$g(x,y,z) = f_2(f_1(x,y), f_1(y,z)).$$To see that this construction is correct, it is sufficient to note that $w \ne x \ne y \ne z$ implies $f_2(w, x) \ne f_2(x,y) \ne f_2(y,z)$, which implies $f_1(f_2(w, x), f_2(x,y)) \ne f_1(f_2(x, y), f_2(y,z))$.As we observed in the previous post, we have, for example, $$20 \leadsto_2 6 \leadsto_2 4.$$ Therefore we also have $$20 \leadsto_3 4.$$However, this is not optimal! There is a computer-generated construction that shows that $$24 \leadsto_3 4.$$ Note that this is not possible to achieve by merely composing any $2$-dimensional colouring functions.(If we construct $d$-dimensional colouring functions by composing $2$-dimensional colouring functions, we do get an asymptotically optimal solution; for example, $c \leadsto_2 \Theta(\log c)$, $c \leadsto_3 \Theta(\log \log c)$, etc. However, this question is really about exact constants, especially for small values of $c, k, d$.)QuestionsOf course ideally we would like to understand precisely when we have $c \leadsto_d k$. But here are some more down-to-earth questions; resolving any of those would be helpful:Is there a simple (human-generated) function $f\colon 24 \leadsto_3 4$? Or anything substantially better than $20 \leadsto_3 4$?Is there a simple (human-generated) proof that $25 \leadsto_3 4$ does not hold?More generally, can we construct optimal $3$-dimensional colouring functions?Edit: Here is yet another example of a relevant question:By composition, we have $24 \leadsto_5 3$. Can we do better, for example, does $25 \leadsto_5 3$ hold?NotesThe existence of colouring functions is closely related to the chromatic number of a certain graph. For example, you can construct a graph $G(c,d)$ in which each $d$-tuple $(x_1,x_2,...,x_d) \in [c]^d$ is a node, and there are edges between nodes $(x_1,x_2,...,x_d)$ and $(x_2,x_3,...,x_{d+1})$ for all $x_1 \ne x_2 \ne ... \ne x_{d+1}$. Now the chromatic number of $G(c,d)$ is at most $k$ if and only if $c \leadsto_d k$. However, while this interpretation is helpful from the perspective of understanding the asymptotics, I do not know if it helps with the above questions. | Existence of colouring matrices a generalisation | co.combinatorics;lower bounds;dc.distributed comp | null |
_unix.331973 | I have an old Acer S2W 3300 U scanner that I used to use in Linux some ten years ago. Tried to install it in an updated Slackware64 linux box, but the kernel doesn't seem to be able to identify it. # uname -a Linux leao 4.4.38 #2 SMP Sun Dec 11 16:11:02 CST 2016 x86_64 Intel(R) Xeon(R) CPU E3-1246 v3 @ 3.50GHz GenuineIntel GNU/Linux# grep -v '^#' /etc/sane.d/snapscan.conf | head -6 firmware /usr/share/sane/snapscan/u176v046.bin/dev/usb/scanner0 bus=usb# ls -l /usr/share/sane/snapscan/u176v046.bin -rwxr-xr-x 1 lupe lupe 31385 nov 12 00:44 /usr/share/sane/snapscan/u176v046.bin# dmesg | tail[ 452.508560] usb 1-13: unable to read config index 0 descriptor/start: -110[ 452.508563] usb 1-13: can't read configurations, error -110[ 452.661561] usb 1-13: new full-speed USB device number 12 using xhci_hcd[ 457.825481] usb 1-13: unable to read config index 0 descriptor/start: -110[ 457.825484] usb 1-13: can't read configurations, error -110[ 457.978466] usb 1-13: new full-speed USB device number 13 using xhci_hcd[ 462.990385] usb 1-13: unable to read config index 0 descriptor/start: -110[ 462.990389] usb 1-13: can't read configurations, error -110[ 463.143374] usb 1-13: new full-speed USB device number 14 using xhci_hcdCan I have any hope to make this work? | Unable to enumerate USB device | linux;kernel;usb;scanner | null |
_unix.28781 | If want to express the following test in shell (sh) :if ( a == 1 && ( b == 1 || b == 2 )) { ... }So far, the best I have been able to write is this :if [[ $a -eq 1 ]]; then if [[ $b -eq 1 || $b -eq 2 ]]; then ... fifiI don't know how to compound && and || with correct precedence. Googling has not given me any answer (tutorials only give basic examples, if any)What is the syntax to combine those two if into one ? | What is the syntax of a complex condition in shell? | shell | Note that [[ ]] is not in either Bourne or POSIX sh. For true sh syntax, there are several ways to do this.Using only one [ ] pairif [ 1 -eq $a -a \( 1 -eq $b -o 2 -eq $b \) ]; then # ...fior Avoiding the POSIX -a and -o options1if [ 1 -eq $a ] && { [ 1 -eq $b ] || [ 2 -eq $b ]; }; then # ...fi1 One reason for avoiding -a and -o is maximum portability - not all test or [ implementations can handle more than 4 arguments, which is precisely what you get if you chain expressions with -a and -o and \( \). |
_cs.58028 | Is the number of possible programs usually finite or infinite? I'm playing with the idea of generating all possible programs for a language - is that even a finite number or must we be more specific, finite RAM etc? | Number of possible programs in a language | programming languages | When considering such questions we usually disregard limitations of real computers and think about a programming language theoretically.A general-purpose programming language (any language used in practice falls into this category) has infinitely many programs. Furthermore, all programs can be generated systematically. Implementing a program which generates all programs may be a useful learning experience, but has little actual value. The number of all programs of length $n$ is exponential in $n$ and so is unfeasable, except for fairly small values of $n$. |
_codereview.159173 | I think I have pretty much the best code you can get when it comes to this particular task, but I'm always open to improvement. This code will check everything I can think of to make sure that it will actually work and if it is an isosceles triangle. It will make sure that none of the sides are 0, it will check whether the lengths of the sides are even possible and it will make sure that the user actually inputted a number.import timeprint(I am going to ask you for three numbers. These numbers can be integers or decimals. They will be the sides of a triangle, and I will tell you if it is an isosceles triangle or not.)time.sleep(2.5)while 2>1: try: side1 = float(input(How long is the first side of the triangle? )) if float(side1) == 0.0: print(This is an impossible triangle!) time.sleep(2.5) break else: 0 except ValueError: print(That's not a number...) time.sleep(2.5) break time.sleep(0.25) try: side2 = float(input(How long is the second side? )) if float(side2) == 0.0: print(This is an impossible triangle!) time.sleep(2.5) break else: 0 except ValueError: print(That's not a number...) time.sleep(2.5) break time.sleep(0.25) try: side3 = float(input(How long is the third side? )) if float(side3) == 0.0: print(This is an impossible triangle!) time.sleep(2.5) break else: 0 except ValueError: print(That's not a number...) time.sleep(2.5) break time.sleep(1) if side1 == side2 == side3: print(This is not an isosceles triangle!) elif float(side1)>float(side2) and float(side1)>float(side3): if (float(side2)+float(side3))<(float(side1)-0.000001): print(This is an impossible triangle!) else: if side1 == side2: print(This is an isosceles triangle!) elif side1 == side3: print(This is an isosceles triangle!) elif side2 == side3: print(This is an isosceles triangle!) elif side1 != side2 and side1 != side3: print(This is not an isosceles triangle!) elif side2 != side1 and side2 != side3: print(This is not an isosceles triangle!) elif side3 != side1 and side3 != side2: print(This is not an isosceles triangle!) elif float(side2)>float(side1) and float(side2)>float(side3): if (float(side1)+float(side3))<(float(side2)-0.000001): print(This is an impossible triangle!) else: if side1 == side2: print(This is an isosceles triangle!) elif side1 == side3: print(This is an isosceles triangle!) elif side2 == side3: print(This is an isosceles triangle!) elif side1 != side2 and side1 != side3: print(This is not an isosceles triangle!) elif side2 != side1 and side2 != side3: print(This is not an isosceles triangle!) elif side3 != side1 and side3 != side2: print(This is not an isosceles triangle!) elif float(side3)>float(side2) and float(side3)>float(side1): if (float(side1)+float(side2))<(float(side3)-0.000001): print(This is an impossible triangle!) else: if side1 == side2: print(This is an isosceles triangle!) elif side1 == side3: print(This is an isosceles triangle!) elif side2 == side3: print(This is an isosceles triangle!) elif side1 != side2 and side1 != side3: print(This is not an isosceles triangle!) elif side2 != side1 and side2 != side3: print(This is not an isosceles triangle!) elif side3 != side1 and side3 != side2: print(This is not an isosceles triangle!) time.sleep(2.5) break | Decide whether a triangle is isosceles or not | python;python 3.x;mathematics | The major thing that stood out to me was the sheer amount of repetition in your code. This will be the main concern of my review.Your code isn't modular; it's just a long script of calculations and printing. What if you ever wanted to do the calculations based off of data from a file? Or the internet? Create a function that calculates whether or not a given triangle is isosceles, pass the data to it, and have it return True/False. I'm of the opinion that the more functions you have, the better (within reason). It gives you more small bits of code that can be reused in other places.One major improvement you can make that will instantly neaten up your code is changing the way you take input from the user. When asking for input, you write out a full try/except for each side, even though they're really all the same. That can be reduced down to a single function that safely asks the user for input:def ask_side_length (side_message): while True: try: length = float(input(How long is the + side_message + side of the triangle?)) if length <= 0.0: print(This is an impossible triangle!) else: return length except ValueError: print(That's not a number...)This could be generalized, but for the sake of the review, I'm going to leave it like this. You could, for practice, create a function that accepts general input from a user, validates it, and loops when validation fails. Then ask_side_length could be defined in terms of that function. A few changes I made:The code is now a function. That means you now have a reusable bit of code you can use anywhere you want, without needing to retype it or copy and paste.I'm using the True constant, since a Boolean comparison to achieve the same seems convoluted. This isn't code-golf! Shorter code does not necessarily mean better code. I'm looping while this single request for input is bad. Previously, your entire program would stop if any input was bad. Bad input happens! Just ask again.I excluded negative inputs as well, since I don't think a negative side-length makes sense in most contexts.Now you can just call this function 3 times:side1 = ask_side_length(first)side2 = ask_side_length(second)side3 = ask_side_length(third)Practice turning repetitious code into a function. Really, that cannot be stressed enough. This will save you and your readers from tears. |
_unix.204508 | I have three Linux machines that connected as the following: Linux_machine1 --> Route_linux_machine --> Linux_machine2How to ssh from Linux_machine1 to Linux_machine2 Only VIA Route_linux_machineLike Route_linux_machine is route get-way to Linux_machine2 | How to connect between two Linux machines VIA Linux router machine | linux;route | It depends on what the Route_linux_machine is.Route_linux_machine is a routerIf it's only a router (means, no SSH service/account there): then you should add some iptables rules to redirect network traffic. For instance, something like:iptables -t nat -A PREROUTING -d linux_machine2_alias \ -p TCP --dport 22 -j DNAT --to-destination linux_machine2:22(where linux_machine2_alias is another IP address, owned by route_linux_machine)Then, from your machine, you have to SSH to linux_machine2_alias (which actually is the router) who will redirect it to linux_machine2.Route_linux_machine is a SSH gatewayIf you have a SSH account on Route_linux_machine, then you can make an SSH tunnel.ssh user@route_linux_machine -L2222:linux_machine2:22Then, the 2222 port of your own machine will be redirected to the port 22 of linux_machine2 via route_linux_machine. You'd just have to do:ssh user@localhost -p 2222While it looks like you're connecting to your own machine (localhost), you will actually be redirected to linux_machine2.As an alternative, if you don't want to use tunnel, you can use nested ssh commands:ssh -t -A user@route_linux_machine ssh user@linux_machine2It will prompt you first for route_linux_machine password, then linux_machine2 password. |
_softwareengineering.279681 | I currently have a MySQL Relational Database with a users table with the following attributes:ID (Primary key)NameUsername (Unique)PasswordEmail (Unique)DescriptionProfile Picture File PathI am really struggling with the normalization of the user's information since username and email are unique. Is this table normalized, if so, is it BCNF? or 3NF? | MySQL Database normalization for a user model | database design;normalization | null |
_webapps.46704 | It's usually fairly easy to edit the text of a post you made on Facebook you simply click the button on the upper right area of the post and it offers you the option of Edit or Delete. However, if you've added a photo and you then try to edit the text, your option is only limited to whether you wish to alter or delete the photo. The option to edit text is not offered.Any way around this? | Editing the text of a Facebook post that includes a photo | facebook | null |
_unix.279775 | In my script, the following code successfully produces a timestamp variable for $n in the format 2016-04-28T15:47:48for n in $(perl parsetime.pl | sed s/.....$//)doecho $nresult is:2016-04-28T15:47:48However, I now want to use this variable to calculate the time 15 minutes earlier. Someone else provided me the syntax to produce the timestamp in the correct format (which worked)-this was achieved like this:/opt/bin/date --date '-15 minutes 2016-04-28T15:39:27' +%Y-%m-%dT%H:%I:%Sresult is:2016-04-28T09:09:27However, my issue is now, when I try to use the $n variable instead of writing out the actual timestamp I get the message like this I get an error message.for n in $(perl parsetime.pl | sed s/.....$//)do/opt/bin/date --date '-15 minutes $n' +%Y-%m-%dT%H:%I:%S result:/opt/bin/date: invalid date `-15 minutes $nWhat am I doing wrong? How can I incorporate the $n variable into the code correclty? | Correct syntax for inputting date variable into date calculation code | linux;bash;shell script;timestamps | The problem is here:'-15 minutes $n'Single quotes stop variable substitution, so you're literally passing $n in rather than the contents of the variable. Write:/opt/bin/date --date -15 minutes $n '+%Y-%m-%dT%H:%I:%S'instead. |
_scicomp.19210 | I'm currently taking a course in computational physics. I'm new to computational physics and programming in general. I'm using numerical recipes to try and integrate the radial Schrodinger equation with a Lennard-jones potential.$$\left[ \frac{\hbar^2}{2m}\frac{d^2}{dr^2} + \left( E-V(r)-\frac{\hbar^2 l (l+1)}{2mr^2}\right) \right] u_l(r)=0$$$$V(r)= \epsilon \left[ \left( \frac{\rho}{r} \right)^{12}-2\left(\frac{\rho}{r}\right)^6 \right]$$Numerical recipes has a function called odeint which will use a fifth-order Runge-Kutta algorithm to integrate an ordinary differential equation for you. The function has an adjustable step-size which appears to be causing problems in my code. Namely, my step-size is going to zero, which causes numerical recipes to throw an error and exit prematurely. I am doing the integration from $r_{min}=\frac{\rho}{2}$ to $r_{max}=5\rho$ numerically, and up to my minimum value analytically in order to take care of the singularity at zero. I have attached my code below, and more information on odeint and how it works can be found at: http://www.itp.uni-hannover.de/Lehre/cip/odeint_c.pdf. Can anyone help me understand where I'm going wrong?#include <stdio.h>#include <math.h>#define NRANSI#include nr.h#include nrutil.h#define N 2float dxsav,*xp,**yp; /* defining declarations */int kmax,kount;int nrhs; /* counts function evaluations *//* Schrodinger equation and L-J parameters */double alpha = 6.12; double rho = 3.57;double epsilon = 5.9;double l = 1.0;double energy = 3;double rmin=1.785;double rmax=17.85;void derivs(float x,float y[],float dydx[]){ nrhs++; printf(xodeint check: x=%f\n, x); dydx[1] = y[2]; dydx[2]=alpha*((l*(l+1)/(alpha*x*x))+epsilon*(pow(rho/x,12)-2*pow(rho/x,6))-energy)*y[1];}int main(void){ int i,nbad,nok; float eps=1.0e-4,h1=0.1,hmin=0,x1=rmin,x2=rmax,*ystart; ystart=vector(1,N); xp=vector(1,200); yp=matrix(1,10,1,200); ystart[1]=0.93583; ystart[2]=0.17385; nrhs=0; kmax=100; dxsav=(x2-x1)/20.0;// printf(%f\n, h1); odeint(ystart,N,x1,x2,eps,h1,hmin,&nok,&nbad,derivs,rkqs); printf(\n%s %13s %3d\n,successful steps:, ,nok); printf(%s %20s %3d\n,bad steps:, ,nbad); printf(%s %9s %3d\n,function evaluations:, ,nrhs); printf(\n%s %3d\n,stored intermediate values: ,kount); printf(\n%8s %18s %15s\n,r,integral,x^2); for (i=1;i<=kount;i++) printf(%10.4f %16.6f %14.6f\n,xp[i],yp[1][i],xp[i]*xp[i]); free_matrix(yp,1,10,1,200); free_vector(xp,1,200); free_vector(ystart,1,N); return 0;}#undef NRANSIThis outputs Numerical Recipes run-time error...stepsize underflow in rkqs...now exiting to system... | Integrating radial Schrodinger equation with Lennard-Jones potential using Runge-Kutta with adaptive step size ends up with a step-size of zero | quantum mechanics;runge kutta | I know this problem well from my own research: it is given by the fact that the equation is very stiff. Thus, it is likely that you're doing nothing wrong (--although I haven't inspected your code). So where does the stiffness come from? The problemIn order to solve the equation numerically, it is common to pick a grid and use finite-differences to discretize the functions and operators. For simplicity, let's say your grid is equally spaces with a spacing of $\Delta x$. Usually, one wants to choose $\Delta x$ small in order to achieve a good approximation.Now for an analysis of the terms in your equation: The kinetic energy term (i.e. the derivative) leads to upper energies of $\mathcal O(\frac{1}{\Delta x^2})$, as the largest frequency which is representable on the grid is $\mathcal O(\frac{1}{\Delta x})$. (I'm lazy so I write $\mathcal O$ here--you surely know the formulas). This term is contained in any Schrdinger equations and does not really pose a problem.Now let's consider the potential functions. Those are diagonal on the grid, so a function $1/r^k$ will have a largest energy of $1/(\Delta x^k)$. In your equation, you have a maximum $k$ of $12$. It is this term which primarily kills your propagation.ExplanationWhy does this term poses a large problem? Consider your complete discretized Hamiltonian matrix $H$ (which is symmetric), and an expansion of your wavefunction in terms of your grid. The explicit solution of the Schrdinger equation is given by$$\psi(t) = \exp(i H t) \psi(t=0)\,.$$Note that there is no time-ordering operator as the Hamiltonian is time-independent. Now make an eigendecomposition of your Hamiltonian, $H = U E U^\dagger$. Then, the exponential may be represented as $\exp(i H t) = U \exp(i E t) U^\dagger$. If you now have a very large eigenenergy $e_{max}$ in your diagonal matrix $E$, then you have a term like $exp(ie_{max} t)$ in your propagation.Here enters the Shannon theorem (or alternatively the Fourier transformation), which states that in order to sample this function well, it should be $\Delta t \sim 1/e_{max}$. Otherwise, you get weird things like aliasing effects, which spoil your solution.For the sake of convenience, one can approximate the maximal eigenenergies the complete Hamiltonian as the sum of the maximal eigenenergies of it's terms. With this, you see that the time step needs to be as small as $\Delta t \sim 1/\Delta x$. That is, if your $\Delta x$ is $10^{-2}$ (no units here, you know them), you'd need a time step of $\sim 10^{-24}$. Adaptive stepize integrators will thus lower and lower the stepsize, until they arrive their underflow constant.This is a rather un-mathematical treatment so don't quote me on the numbers, but it intuitively explains the occuring effects.Suggested solutionThere is a simple alternative which I think is suited to your problem, which is often called the spectral method. It is applicable if your grid has a small to medium size -- say up to $N=10000$ gridpoints -- which I guess is the case here. Then, in fact, it is the method of choice for your problem.The solution is then simply to calculate the matrix exponential $\exp(iHt)$ as sketched above, and apply it to your initial wavefunction vector. The costs are $\mathcal O(N^3)$ for the diagonalization, but you need to execute it only once. Plus, by this you get the exact numerical solution -- the solution all those ODE methods try to achieve.The downside is that this approach is only applicable when the Hamiltonian is time-independent. Otherwise, when it changes over time, you'd need to diagonalize it often anew. |
_webmaster.10496 | For the image title of my website medium-small(150x50) white background with some effects on title (example: google title image)I saved the image in .gif and .png with result:.gif size = 3.09 kB.png size = 7.59 kBThe .png is 2x bigger than .gif.Everyone are saying me to use .PNG, but why I should use it if .gif are better | GIF vs PNG which to use? | png;gif | PNG almost always gives better compression than GIF, but you need to make sure you're saving the image as an 8-bit PNG. Often graphics programs will save as a 24-bit PNG, which may be why you're seeing the results you are. If you say what program you are using we may be able to advise how to save as an 8-bit PNG.You can also run the resulting file through either pngout or pngcrush which will reduce the file size even further.Really the only reason to use GIF over PNG these days is if you need animation. |
_unix.75344 | From Xfce Docs:In case you want to override the DPI (dots per inch) value calculated by the X-server, you can select the checkbox and use the spin box to specify the resolution to use when your screen renders fonts.But how does X-server do its calculation? What assumptions are made in the process and can some of the parameters be overridden?It may know how many pixels I have on my display, but is that enough? | How does X-server calculate DPI? | xorg;x11;display settings;resolution;x server | null |
_codereview.108592 | I read the following question: Searching an element in a sorted array and I thought that I could give it a try in Python.Given a sorted list of integers and an integer. Return the (index) bounds of the sequence of this element in the list.Example:l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 6, 7, 8, 9, 9, 9, 9]0 not found in list1:(0, 0)2:(1, 2)3:(3, 5)4:(6, 11)5 not found in list6:(12, 12)7:(13, 13)8:(14, 14)9:(15, 18)Here is my program (using Python 3).It uses a dichotomic search and returns the bounds to help the search of the start and end of the sequence.def main(): l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 6, 7, 8, 9, 9, 9, 9] print(l) for i in range(10): try: print(find_sequence(i, l)) except Exception as e: print(str(e))def find_sequence(x, l): Return a tuple (begin, end) containing the index bounds of the sequence of x left, found, right = dichotomic_search(x, l) begin = outside_bound(x, l, left, found) end = outside_bound(x, l, right, found) return begin, enddef outside_bound(x, l, outside, inside): Return the outside bound of the sequence if l[outside] == x: return outside middle = -1 previous_middle = -2 while middle != previous_middle: previous_middle = middle middle = (outside + inside) // 2 if l[middle] == x: inside = middle else: outside = middle return insidedef dichotomic_search(x, l): Return a tuple of indexes (left, found, right) left: leftmost index where x might be found found: index where x is right: rightmost index where x might be found left = 0 right = len(l) - 1 if l[left] > x or l[right] < x: raise Exception(str(x) + ' not found in list') if l[left] == x: return left, left, right if l[right] == x: return left+1, right, right # we know that l[left]!=x while left < right: middle = (left + right) // 2 if l[middle] == x: return left, middle, right elif l[middle] < x: left = middle + 1 # to prevent fixed point elif l[middle] > x: right = middle # impossible to do -1 because of the integer division raise Exception(str(x) + ' not found in list')if __name__ == __main__: main()I'm not so fond of the middle != previous_middle, but I didn't find a more elegant way (yet). | Locating a sequence in a sorted array | python;python 3.x;reinventing the wheel;binary search | null |
_unix.304297 | /etc/pam.d/ has several files and running auth-config updates many of those. I need to know exactly which file needs to be updated to support LDAP based login using SSH / Console. | Files that need to be updated in /etc/pam.d/ for nss-pam-ldapd support for SSH | centos;pam;ldap;nss | Typically there will be a file under /etc/pam.d/ called sshd, but it usually only contains a few lines similar to this:auth include system-remote-loginaccount include system-remote-loginpassword include system-remote-loginsession include system-remote-loginThese are references to the other files in the /etc/pam.d/ directory that contain the PAM directives common to all security functions on your machine. If you want LDAP authentication for SSH only, you would change the sshd file itself. If you are trying to setup LDAP authentication for the entire system (i.e. local login as well as SSH), you will need to edit the common PAM files for all logins.A typical sshd configuration file for LDAP auth would look something like this:auth files ldapaccount files ldappassword files ldapsession files ldapHowever, this assumes you aren't using SSSD and only want LDAP authentication for SSHD and no other services. This configuration allows local logins on the target server to work in the event LDAP authentication fails for whatever reason. You may or may not want that behavior. Be aware also that depending on how your LDAP server is configured, this may result in user logins being sent in cleartext over the network.Here is a comprehensive setup guide for LDAP authentication on CentOS, but it is geared towards using LDAP for both local logins as well as services (including SSH). |
_codereview.78307 | I'm trying to have a HTML / CSS structure for flexible layouts for forms. I tried to look at Bootstrap codes for help with this (without actually using Bootstrap itself). I've gone with something along these lines:http://cssdeck.com/labs/stidyuic* {padding: 0; margin: 0; box-sizing: border-box;}body {width: 80%; margin: 0 auto; margin-top: 30px;}.form-row { display: block;}.form-group:first-child { padding-left: 0px;}.form-group { margin-bottom: 20px; float: left; padding-left: 20px;}.col-6 { width: 50%;}.col-3 { width: 25%;}label { display: block; margin-bottom: 10px; font-weight: bold;}.form-control { display: block; width: 100%; height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.42857; color: #555; vertical-align: middle; background-color: #FFF; background-image: none; border: 1px solid #CCC; border-radius: 4px; box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.075) inset; transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;}input, button, select, textarea { font-family: inherit; font-size: inherit;}form { display: block; margin-top: 0em;}<div class=form-row> <div class=col-6 form-group> <label class=control-label>Title</label> <input class=form-control placeholder=Test size=4 type=text> </div> <div class=col-3 form-group> <label class=control-label>Category</label> <select class=form-control> <option value=A> A </option> <option value=B> B </option> </select> </div> <div class=col-3 form-group> <label class=control-label>Type</label> <select class=form-control> <option> A </option> <option> B </option> <option> C </option> </select> </div></div>I want to be able to do the following:Have anywhere from 1 to four inputs on each row.Have the label above the formModify the form layout with CSS when the resolution changes (media query)Questions:Is it a sensible approach to use this code structure in order toachieve this?Is taking Bootstraps form structure a logical approach to this problem? | HTML and CSS markup for flexible form layout | html;css;form;layout | Your code looks perfectly fine. In fact, it all validates by the validators at W3C perfectly fine, with one exception - your HTML file should be structured like this:<!DOCTYPE html><html> <head> <meta charset=UTF-8 /> <title>Your Page Title Here</title> <!-- other code here --> </head> <body> <!-- your display code here --> </body></html>The validators can be found here:HTML validatorCSS validatorYour code seems perfectly fine the way it is, and I would say the only thing wrong with it is from the user's perspective. You have the Category menu overlapping the Title menu, which is not good; you should adjust your columns to prevent this. |
_codereview.136105 | I'm starting with implementing a TCP/IP stack for embedded systems which will be done in C++ and I've found I need a good way to work with protocol headers involved (e.g. ARP, IP, TCP). Major requirements are:Portable, C++(11) standard compliant (e.g. no structure packing, independent of CPU endianness).Completely correct (e.g. no potential strict-aliasing violations).Minimal boilerplate for both definition of headers and access.Ability to read and write fields of headers in arbitrary memory locations (no need to work on a copy of data).Efficient (e.g. no runtime metainformation about headers).I've produced a solution which relies heavily on template metaprogramming. The code is below, it's quite some number of lines, though much of it is comments. The full code along with required headers can be found in my open-source project here. Below is also some example code which demonstrates how it can be used.I'd like to get some feedback about how to make it better, in any respect. For example to make usage less verbose; currently, it still needs a bit more typing than pointer->field. Or any ideas about the interactions between the Val, Ref and ConstRef classes.Code:/** * This class is specialized for different field types * to define type-specific behavior, e.g. how to * encode a logical value into bytes and how to decode * bytes into a value. */template <typename Type, typename Dummy=void>struct StructTypeHandler;#define APRINTER_STRUCT_REGISTER_TYPE(Type, TypeHandler) \template <> \struct StructTypeHandler<Type, void> { \ using Handler = TypeHandler; \};template <typename TType>struct StructField { using Type = TType;};/** * Base class for protocol structure definitions. * * Notable features of the system are: * - Automatic endianness handling (big endian encoding is used). * That is, the user always interacts with logical values while * the framework manages the byte-level representaion. * - Can reference structures in existing memory (no need for pointer * casts violatign strict aliasing). * - Support for nested structures. * - Ability to define custom field types. * * Structures should be defined through the APRINTER_TSTRUCT macro which * results in a struct type inheriting StructBase. Example: * * \code * APRINTER_TSTRUCT(MyHeader, * (FieldA, uint32_t) * (FieldB, uint64_t) * ) * \endcode * * Each field specified will result in a type within this structure that * is used as an identifier for the field (e.g. MyHeader::FieldA). * * There will be three classes within the main structure providing * different ways to work with structure data: * - Val: contains structure data as char[]. * - Ref: references structure data using char *. * - ConstRef: references structure data using char const *. * * Note that the structure type itself (MyHeader) has no runtime use, it * is a zero-sized structure. * * Note, internally APRINTER_TSTRUCT will expand to something like this: * * struct MyHeader : public StructBase\<MyHeader\> { * struct FieldA : public StructField\<uint32_t\>; * struct FieldB : public StructField\<uint64_t\>; * using StructFields = MakeTypeList\<FieldA, FieldB\>; * }; */template <typename TStructType>class StructBase {private: using StructType = TStructType; template <typename This=StructBase> using Fields = typename This::StructType::StructFields; template <int FieldIndex, typename Dummy=void> struct FieldInfo; template <typename Dummy> struct FieldInfo<-1, Dummy> { static size_t const StructSize = 0; }; template <int FieldIndex, typename Dummy> struct FieldInfo { using PrevFieldInfo = FieldInfo<FieldIndex-1, void>; using Field = TypeListGet<Fields<>, FieldIndex>; using Handler = typename StructTypeHandler<typename Field::Type>::Handler; using ValType = typename Handler::ValType; static size_t const FieldOffset = PrevFieldInfo::StructSize; static size_t const FieldSize = Handler::FieldSize; static size_t const StructSize = FieldOffset + FieldSize; }; template <typename Field, typename This=StructBase> using GetFieldInfo = FieldInfo<TypeListIndex<Fields<This>, Field>::Value, void>; template <typename This=StructBase> using LastFieldInfo = FieldInfo<TypeListLength<Fields<This>>::Value-1, void>;public: class Ref; class ConstRef; class Val; /** * Gets the value type of a specific field. * * Example: ValType\<MyHeader::FieldA\> is uint32_t. * * @tparam Field field identifier */ template <typename Field> using ValType = typename StructTypeHandler<typename Field::Type>::Handler::ValType; /** * Gets the reference type of a specific field. * Support for this depends on the type handler (e.g. nested structures). */ template <typename Field> using RefType = typename StructTypeHandler<typename Field::Type>::Handler::RefType; /** * Gets the const-reference type of a specific field. * Support for this depends on the type handler (e.g. nested structures). */ template <typename Field> using ConstRefType = typename StructTypeHandler<typename Field::Type>::Handler::ConstRefType; /** * Returns the size of the structure. */ inline static constexpr size_t Size () { return LastFieldInfo<>::StructSize; } /** * Reads a field. * * @tparam Field field identifier * @param data pointer to the start of a structure * @return field value that was read */ template <typename Field> inline static ValType<Field> get (char const *data, Field) { using Info = GetFieldInfo<Field>; return Info::Handler::get(data + Info::FieldOffset); } /** * Writes a field. * * @tparam Field field identifier * @param data pointer to the start of a structure * @param value field value to set */ template <typename Field> inline static void set (char *data, Field, ValType<Field> value) { using Info = GetFieldInfo<Field>; Info::Handler::set(data + Info::FieldOffset, value); } /** * Returns a reference to a field. * Support for this depends on the type handler (e.g. nested structures). */ template <typename Field> inline static RefType<Field> ref (char *data, Field) { using Info = GetFieldInfo<Field>; return Info::Handler::ref(data + Info::FieldOffset); } /** * Returns a const reference to a field. * Support for this depends on the type handler (e.g. nested structures). */ template <typename Field> inline static ConstRefType<Field> ref (char const *data, Field) { using Info = GetFieldInfo<Field>; return Info::Handler::const_ref(data + Info::FieldOffset); } /** * Returns a Ref class referencing the specified memory. * * @param data pointer to the start of a structure */ inline static Ref MakeRef (char *data) { return Ref{data}; } /** * Returns a ConstRef class referencing the specified memory. * * @param data pointer to the start of a structure */ inline static ConstRef MakeRef (char const *data) { return ConstRef{data}; } /** * Reads a structure from the specified memory location and * returns a Val class containing the structure data. * * @param data pointer to the start of a structure * @return a Val class initialized with a copy of the data */ inline static Val MakeVal (char const *data) { Val val; memcpy(val.data, data, Size()); return val; } /** * Class which contains structure data. * These can be created using StructBase::MakeVal or from * the Val conversion operators in Ref and ConstRef. */ class Val { public: using Struct = StructType; /** * Reads a field. * @see StructBase::get */ template <typename Field> inline ValType<Field> get (Field) const { return StructBase::get(data, Field()); } /** * Writes a field. * @see StructBase::set */ template <typename Field> inline void set (Field, ValType<Field> value) { StructBase::set(data, Field(), value); } /** * Returns a reference to a field. * @see StructBase::ref */ template <typename Field> inline RefType<Field> ref (Field) { return StructBase::ref(data, Field()); } /** * Returns a const reference to a field. * @see StructBase::ref */ template <typename Field> inline ConstRefType<Field> ref (Field) const { return StructBase::ref(data, Field()); } /** * Returns a Ref referencing this Val. */ inline operator Ref () { return Ref{data}; } /** * Returns a ConstRef referencing this Val. */ inline operator ConstRef () const { return ConstRef{data}; } public: /** * The data array. */ char data[LastFieldInfo<>::StructSize]; }; /** * Structure access class referencing external data via * char *. * Can be initialized via StructBase::MakeRef or Ref{data}. */ class Ref { public: using Struct = StructType; /** * Reads a field. * @see StructBase::get */ template <typename Field> inline ValType<Field> get (Field) const { return StructBase::get(data, Field()); } /** * Writes a field. * @see StructBase::set */ template <typename Field> inline void set (Field, ValType<Field> value) const { StructBase::set(data, Field(), value); } /** * Returns a reference to a field. * @see StructBase::ref */ template <typename Field> inline RefType<Field> ref (Field) const { return StructBase::ref(data, Field()); } /** * Returns a ConstRef referencing the same memory. */ inline operator ConstRef () const { return ConstRef{data}; } /** * Reads and returns the current structure data as a Val. */ inline operator Val () const { return MakeVal(data); } /** * Copies the structure referenced by a ConstRef * over the structure referenced by this Ref. * Note: uses memcpy, so don't use with self. */ inline void load (ConstRef src) const { memcpy(data, src.data, Size()); } public: char *data; }; /** * Structure access class referencing external data via * char const *. * Can be initialized via StructBase::MakeRef or ConstRef{data}. */ class ConstRef { public: using Struct = StructType; /** * Reads a field. * @see StructBase::get */ template <typename Field> inline ValType<Field> get (Field) const { return StructBase::get(data, Field()); } /** * Returns a const reference to a field. * @see StructBase::ref */ template <typename Field> inline ConstRefType<Field> ref (Field) const { return StructBase::ref(data, Field()); } /** * Reads and returns the current structure data as a Val. */ inline operator Val () const { return MakeVal(data); } public: char const *data; };};/** * Macro for defining structures. * @see StructBase */#define APRINTER_TSTRUCT(StructName, Fields) \struct StructName : public APrinter::StructBase<StructName> { \ APRINTER_TSTRUCT__ADD_END(APRINTER_TSTRUCT__FIELD_1 Fields) \ using StructFields = APrinter::MakeTypeList< \ APRINTER_TSTRUCT__ADD_END(APRINTER_TSTRUCT__LIST_0 Fields) \ >; \};#define APRINTER_TSTRUCT__ADD_END(...) APRINTER_TSTRUCT__ADD_END_2(__VA_ARGS__)#define APRINTER_TSTRUCT__ADD_END_2(...) __VA_ARGS__ ## _END#define APRINTER_TSTRUCT__FIELD_1(FieldName, FieldType) \struct FieldName : public APrinter::StructField<FieldType> {}; \APRINTER_TSTRUCT__FIELD_2#define APRINTER_TSTRUCT__FIELD_2(FieldName, FieldType) \struct FieldName : public APrinter::StructField<FieldType> {}; \APRINTER_TSTRUCT__FIELD_1#define APRINTER_TSTRUCT__FIELD_1_END#define APRINTER_TSTRUCT__FIELD_2_END#define APRINTER_TSTRUCT__LIST_0(FieldName, FieldType) FieldName APRINTER_TSTRUCT__LIST_1#define APRINTER_TSTRUCT__LIST_1(FieldName, FieldType) , FieldName APRINTER_TSTRUCT__LIST_2#define APRINTER_TSTRUCT__LIST_2(FieldName, FieldType) , FieldName APRINTER_TSTRUCT__LIST_1#define APRINTER_TSTRUCT__LIST_1_END#define APRINTER_TSTRUCT__LIST_2_END/** * Structure field type handler for integer types using * big-endian representaion. * These type handlers are registered by default for signed and * unsigned fixed-width types: intN_t and uintN_t (N=8,16,32,64). * * Relies on ReadBinaryInt and WriteBinaryInt. */template <typename Type>struct StructBinaryTypeHandler { static size_t const FieldSize = sizeof(Type); using ValType = Type; inline static ValType get (char const *data) { return ReadBinaryInt<Type, BinaryBigEndian>(data); } inline static void set (char *data, ValType value) { WriteBinaryInt<Type, BinaryBigEndian>(value, data); }};#define APRINTER_STRUCT_REGISTER_BINARY_TYPE(Type) \APRINTER_STRUCT_REGISTER_TYPE(Type, StructBinaryTypeHandler<Type>)APRINTER_STRUCT_REGISTER_BINARY_TYPE(uint8_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(uint16_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(uint32_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(uint64_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(int8_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(int16_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(int32_t)APRINTER_STRUCT_REGISTER_BINARY_TYPE(int64_t)/** * Type handler for structure types, allowing nesting of structures. * * It provides: * - get() and set() operations using StructType::Val. * - ref() operations using StructType::Ref and StructType::ConstRef. */template <typename StructType>struct StructNestedTypeHandler { static size_t const FieldSize = StructType::Size(); using ValType = typename StructType::Val; using RefType = typename StructType::Ref; using ConstRefType = typename StructType::ConstRef; inline static ValType get (char const *data) { return StructType::MakeVal(data); } inline static void set (char *data, ValType value) { memcpy(data, value.data, sizeof(value.data)); } inline static RefType ref (char *data) { return RefType{data}; } inline static ConstRefType const_ref (char const *data) { return ConstRefType{data}; }};template <typename Type>struct StructTypeHandler<Type, EnableIf<__is_base_of(StructBase<Type>, Type), void>> { using Handler = StructNestedTypeHandler<Type>;};Example code:APRINTER_TSTRUCT(HeaderFoo, (FieldA, int8_t) (FieldB, int64_t))APRINTER_TSTRUCT(HeaderBar, (FieldC, int8_t) (FieldD, uint32_t) (FieldFoo, HeaderFoo))void main (){ // Create a FooHeader::Val (a type which contains data), set field values. HeaderFoo::Val foo; foo.set(HeaderFoo::FieldA(), 30); foo.set(HeaderFoo::FieldB(), -55); // Change it via FooHeader::Ref (a type which references data). HeaderFoo::Ref foo_ref = foo; foo_ref.set(HeaderFoo::FieldA(), 61); // Get values via FooHeader::ConstRef (a type which references const data). // Note: Val, Ref and ConstRef all suppport get(). HeaderFoo::ConstRef foo_cref = foo; printf(% PRIi8 % PRIi64 \n, foo_cref.get(HeaderFoo::FieldA()), foo_cref.get(HeaderFoo::FieldB())); // Allocate memory for a HeaderBar as char[] and initialize // parts of it through HeaderBar::Ref. char bar_mem[HeaderBar::Size()]; HeaderBar::Ref bar_ref = HeaderBar::MakeRef(bar_mem); bar_ref.set(HeaderBar::FieldC(), -75); bar_ref.set(HeaderBar::FieldD(), 70000); // Initialize the nested HeaderFoo from foo. // This goes like this: // - Get a reference to the contained HeaderFoo via .ref(), // obtaining a HeaderFoo::Ref. // - Call load() on the HeaderFoo::Ref to copy data from a // HeaderFoo::ConstRef, which is created from HeaderFoo::Val // automatically by a conversion operator. bar_ref.ref(HeaderBar::FieldFoo()).load(foo); // Get the nested HeaderFoo from bar_ref as a value. // This will be a HeaderFoo::Val. // Change the original to prove it's a copy. auto foo_copy = bar_ref.get(HeaderBar::FieldFoo()); bar_ref.ref(HeaderBar::FieldFoo()).set(HeaderFoo::FieldA(), 4); printf(% PRIi8 % PRIi8 \n, bar_ref.ref(HeaderBar::FieldFoo()).get(HeaderFoo::FieldA()), foo_copy.get(HeaderFoo::FieldA()));} | Library for manipulation of binary protocol headers | c++;serialization;template meta programming;portability | null |
_unix.191582 | I want to connect to PostgreSQL 9 from Drupal 7.to install drupal files using the following steps.wget http://ftp.drupal.org/files/projects/drupal-7.15.tar.gz tar zxvf drupal-7.15.tar.gz sudo mv drupal-7.15/* /var/www/ cd /var/www/ cp sites/default/default.settings.phpsites/default/settings.phpchmod a+w sites/default/settings.php chmod a+w sites/defaultto install PostgreSQL database.createuser --pwprompt --encrypted --no-adduser --no-createdbusername createdb --encoding=UNICODE --owner=username databasenameto input my_domain in Firefox. It ran across the message: Maybe it is a problem that Drupal installation program can not access the PostgreSQL database. How to fix it? | How to connect to PostgreSQL 9 from Drupal 7? | postgresql;drupal | By just reading the title of this question, I thought it was about How to connect from a Drupal site to some external database in PostGress format. However the details of the question are about How to use Postgress as the DBMS for hosting the database required for a Drupal site. Consider rephrasing the question title accordingly.To actually answer this question, consider looking at Install Drupal with PostgreSQL. Here is a quote from that link:Drupal is an excellent PHP content management system. It supports both MySQL and PostgreSQL as the back end database for content management. Unfortunately, PostgreSQL comes up short in the documentation department: it is not even mentioned in the Drupal INSTALL.txt file. So here we do our small part for the cause and provide some instructions to get Drupal up and running with PostgreSQL. |
_softwareengineering.198589 | When the context class can accept a null strategy, is there another way to do it without check if its null?Is this considered a good strategy design implementation?class MainApp{ static void Main(){ Context context = new Context(); while(true){ Strategy strategy = createConcreteStrategy(Console.ReadLine()); context.setStrategy(strategy); context.run(); } } static void createConcreteStrategy(string input){ if( input == strategyA ){ return new StrategyA(); } if( input == strategyB ){ return new StrategyB(); } return null; }}abstract class Strategy { public abstract void doSomething(); }class Context{ Strategy strategy; ClassX x; public Context(){} public void setStrategy(Strategy strategy){ this.strategy = strategy; } public void run(){ if( strategy != null ){ data = strategy.doSomething(); x.setData(data); } }} | design strategy pattern with null checking | design;design patterns;null | There is absolutely a way to avoid checking for null here! Use the null object pattern, i.e.class NullStrategy: Strategy { public void doSomething() { }}and then the default case in createConcreteStrategy is return new NullStrategy() instead of return null, and then you no longer have to check if strategy is null in run.If you don't want to call x.setData with a null argument, then you could pass x to the strategy. Here's one possible implementation:class NullStrategy: Strategy { public void doSomething(ClassX x) { // don't do anything with x }}class RealStrategy: Strategy { public void doSomething(ClassX x) { var data = someOperation(); x.setData(data); }}Pushing an if-statement into an instance of Strategy makes sense to me in this situation. |
_unix.87560 | This may be a silly question, but I ask it still. If I have declared a shebang#!/bin/bash in the beginning of my_shell_script.sh, so do I always have to invoke this script using bash[my@comp]$bash my_shell_script.shor can I use e.g.[my@comp]$sh my_shell_script.shand my script determines the running shell using the shebang? Is it the same happening with ksh shell? I'm using AIX. | Does the shebang determine the shell which runs the script? | scripting;executable;shebang | The shebang #! is an human readable instance of a magic number consisting of the byte string 0x23 0x21, which is used by the exec() family of functions to determine whether the file to be executed is a script or a binary. When the shebang is present, exec() will run the executable specified after the shebang instead.Note that this means that if you invoke a script by specifying the interpreter on the command line, as is done in both cases given in the question, exec() will execute the interpreter specified on the command line, it won't even look at the script.So, as others have noted, if you want exec() to invoke the interpreter specified on the shebang line, the script must have the executable bit set and invoked as ./my_shell_script.sh.The behaviour is easy to demonstrate with the following script:#!/bin/kshreadlink /proc/$$/exeExplanation:#!/bin/ksh defines ksh to be the interpreter.$$ holds the PID of the current process. /proc/pid/exe is a symlink to the executable of the process (at least on Linux; on AIX, /proc/$$/object/a.out is a link to the executable).readlink will output the value of the symbolic link.Example:Note: I'm demonstrating this on Ubuntu, where the default shell /bin/sh is a symlink to dash i.e. /bin/dash and /bin/ksh is a symlink to /etc/alternatives/ksh, which in turn is a symlink to /bin/pdksh.$ chmod +x getshell.sh$ ./getshell.sh /bin/pdksh$ bash getshell.sh /bin/bash$ sh getshell.sh /bin/dash |
_unix.11639 | Would anyone have any tips on optimizing video to FLV conversion using ffmpeg so I would get a medium quality video which is not very large?I have a video site where users can upload videos which will be converted to FLV and displayed. Those videos are shown at the size 420x350. I'm using FFMPEG to convert then to FLV, through the following command:ffmpeg -i $in $outI find the result to be pretty low quality and whenever I try to change settings, the output will be a very large file. For instance, I've tried this: ffmpeg -i $in -sameq -ar 11025 -ab 32 -deinterlace -nr 500 -r 20 -g 500 -s 420x350 -aspect 4:3 -me_range 20 -b 270k -f flv -y $out | FFMPEG video to FLV conversion optimization | ffmpeg | null |
_unix.325488 | I'm using find to prune old files, lots of them.. this takes minutes / hours to run and other server processes encounter IO performance issues. find -mtime +100 -delete -printI tried ionice but it didn't appear to help. ionice -c 3 What can one do to 1. speed up the find operation and 2. to avoid impacting other processes?The FS is ext4.. is ext4 just bad at this kind of workload?Kernel is 3.16Storage is 2x 1TB 7200rpm HDDs in RAID 1.There's 93GB in 610228 files now, so 152KB/file on average.Maybe I just shouldn't store so many files in a single directory? | Deleting old files is slow and 'kills' IO performance | linux;debian;ext4 | null |
_unix.294654 | I was trying to check the amount of hard drive by typing df -hIts showing me below status since long time. svn_manager@fileserver:~$ df -h ^C^C^C^C^C^C^C^C^C^Z^Z^Z^X^X^C^C^C^C^C^C^C^CI have 1 network shared folder mounted and 1 usb drive attached but both the shared function working from other pc.I tried to kill by using Crtl+c | Crtl+z | Crtl+d but no success.Closing the terminal work but when i reopen the terminal and run it again its having same issue.Please advise. | df -h unable to show the command output on a Linux System | disk usage | null |
_codereview.20375 | I have this method that basically takes a string and does different thingsdepending on what the string starts with. Is there a cleaner way to write this method?public String analyze(BotMessage message){ String lcmsg = message.message().toLowerCase(); //Not a command if(!lcmsg.startsWith(!)) return -1; //Message from whatever if(lcmsg.startsWith(!ping)) return pong!; if(lcmsg.startsWith(!tournament)) return tournament(message); //message from skype if(message.skype()) { if(lcmsg.startsWith(!settournament)) return settournament(message); if(lcmsg.startsWith(!promote)) return promote(message); if(lcmsg.startsWith(!checkin)) return checkin(message); if(lcmsg.startsWith(!checkout)) return checkout(message); if(lcmsg.startsWith(!checkedin)) return checkedin(message); if(lcmsg.startsWith(!updatetournament)) return updatetournament(); } return -1;} | Conditional execution based on input string's prefix | java;strings | I don't like too much the fact that you use a String as the returned type of your function.What about using a class hierarchy or exceptions?I see opportunities to create a hierarchy even for the messages. Why don't you create a BotMessage and a SkypeMessage?Both should have the logic to decide what to do in the base case, maybe in an analyze method. The analyze method of the SkypeMessage should, in addition, manage the Skype-specific aspects.Finally you should simplify the code and remove the list of if statements.Introduce a new set of objects to parse the messages. These objects should have a match method that check whether the string matches with their definition, and a performAction method that generates the return value. |
_webapps.106171 | I am looking to build a form that asks a customer for a list of items (in this case locations and their website) on page 1, and on page 2 I want some elaboration on the specfics for the website.I am trying to capture the domain field from my table as a calculated value in the 2nd recurring section or table. However I can only get all entries or none. What i'd like is this:table 1:entry 1: location|variable|variable|websiteentry 2: location|variable|variable|websiteetc.table 2:entry 1: (calc)location from table1.entry1|(calc)website from table1.entry1|variable|variableentry 2: (calc)location from table1.entry2|(calc)website from table1.entry2|variable|variableetc.I have tried the following:=Form.SECTION1.TABLE1.Where(ItemNumber = Form.SECTION2.TABLE2.ItemNumber).Select(Website)(basically I am trying to dynamically generate the ItemNumber = 1, 2, 3, etc. by equating this to the current ItemNumber in the table)If this would work with recurring sections I'd be just as happy.is there any way to accomplish this? | Reference a line/item from a recurring section/table in another recurring section/table | cognito forms | null |
_codereview.145348 | In our latest Veracode scan for an application, I have come across the issue of Improper Resource Shutdown or Release. It is pointing at a function. Here's what the code looks like:Imports System.Data.SqlClientPublic Class DAL Public Shared ConnString As String = ConfigurationManager.ConnectionStrings(connection).ConnectionStringPublic Shared Function CheckSecurity(ByVal strUserID As String, ByVal strOperation As String, ByVal strAppID As String) As Boolean Dim sbSQL As New StringBuilder Dim MyConnection As SqlConnection = New SqlConnection() Dim sqlCmd As SqlCommand = New SqlCommand MyConnection.ConnectionString = ConnString sbSQL.Clear() sbSQL.AppendLine(EXEC dbo.CheckSecurity @UserID, @AppID, @Operation) sqlCmd.CommandText = sbSQL.ToString sqlCmd.Connection = MyConnection With sqlCmd.Parameters .Clear() .Add(@UserID, SqlDbType.VarChar, 15).Value = strUserID .Add(@AppID, SqlDbType.VarChar, 50).Value = strAppID .Add(@Operation, SqlDbType.VarChar, 50).Value = strOperation End With Try If getDataTableFromSqlCmd(sqlCmd).Rows.Count > 0 Then CheckSecurity = True Else CheckSecurity = False End If Catch ex As Exception Throw New ApplicationException(SECURITY ACCESS ERROR) Finally If MyConnection.State = ConnectionState.Open Then MyConnection.Close() End If MyConnection.Dispose() sqlCmd.Dispose() End TryEnd FunctionCode for getDataTableFromSqlCMD:Public Shared Function getDataTableFromSqlCmd(ByVal sqlCmd As SqlCommand) As DataTable Dim dt As New DataTable Dim MyAdapter As New SqlDataAdapter(sqlCmd) Try sqlCmd.CommandTimeout = m_iSQLTimeOut MyAdapter.Fill(dt) getDataTableFromSqlCmd = dt Catch ex As Exception Throw New ApplicationException(GET DATA TABLE ERROR) Finally sqlCmd.Dispose() MyAdapter.Dispose() dt.Dispose() End TryEnd FunctionAs far as I can tell the resources in this code are being properly deallocated. Am I missing something? | Security check using an SQL call | sql;vb.net;authorization | It needs more Using statements. For example:Public Shared Function CheckSecurity(strUserID$, strOperation$, strAppID$) As Boolean Try Using da As New SqlDataAdapter(dbo.CheckSecurity, ConnString) Dim sc = da.SelectCommand, p = sc.Parameters, dt = New DataTable sc.CommandType = CommandType.StoredProcedure sc.CommandTimeout = m_iSQLTimeOut p.Add(@UserID, SqlDbType.VarChar, 15).Value = strUserID p.Add(@AppID, SqlDbType.VarChar, 50).Value = strAppID p.Add(@Operation, SqlDbType.VarChar, 50).Value = strOperation Return da.Fill(dt) > 0 ' .Fill returns the number of rows successfully added End Using ' da is disposed here even if Exception occurs Catch ex As Exception Throw New ApplicationException(SECURITY ACCESS ERROR) End Try Return FalseEnd Functionor Public Shared Function CheckSecurity(strUserID$, strOperation$, strAppID$) As Boolean Try Using con = New SqlConnection(ConnString), cmd = New SqlCommand(dbo.CheckSecurity, con) cmd.CommandType = CommandType.StoredProcedure cmd.CommandTimeout = m_iSQLTimeOut cmd.Parameters.Add(@UserID, SqlDbType.VarChar, 15).Value = strUserID cmd.Parameters.Add(@AppID, SqlDbType.VarChar, 50).Value = strAppID cmd.Parameters.Add(@Operation, SqlDbType.VarChar, 50).Value = strOperation con.Open() Using reader = cmd.ExecuteReader Return reader.HasRows End Using End Using ' con and cmd are closed and disposed here even if Exception occurs Catch ex As Exception Throw New ApplicationException(SECURITY ACCESS ERROR) End Try Return FalseEnd FunctionSome other examples https://stackoverflow.com/questions/24023575/how-to-pass-parameters-to-sqldataadapter, https://stackoverflow.com/questions/14566980/c-sharp-data-adapter-parameters |
_unix.184429 | I've successfully set up an sftp with authentication on Active Directory. All users in a particular AD group are managed by SSH's sftp subsystem and chrooted into a common home directory, let's say /upload. This works fine except that everytime a user logs in, a file named .k5login is created and remains there. I could delete the file, but whenever a user logs in, the file is created again.I've used pbis-open to connect the workstation to the domain, but I think my issue is not related to this particular package.From what I saw, this file is required by the kerberos authentication framework, but how can I avoid this? Can I modify the creation path of this file, let's say in /tmp? | Avoid creation of .k5login file in a SFTP Chroot configuration | ssh;sftp;active directory | null |
_unix.279107 | I tried to persist the environment variables for ORACLE in RedHat using/etc/environmentIt cleared my PATH variable, no command was recognized afterwards.Why does it happen, since just executing the same commands in the shell just works fine! Variables, which i added to the environmentORACLE_HOME=/usr/lib/oracle/12.1/client64PATH=$ORACLE_HOME/bin:$PATHLD_LIBRARY_PATH=$ORACLE_HOME/lib | Why does environment variables persistance breaks the PATH var | environment variables | /etc/environment is a configuration file for pam_env, not a file read by a shell. The syntax is somewhat similar, but it is not the same. In particular, you can't refer to existing variables: you've set your search path to contain $ORACLE_HOME/bin and $PATH, i.e. directories with a dollar sign in their name.To set variables for all users, you can edit /etc/security/pam_env.conf, which has a different, richer syntax, but still not as rich as what you can do in a shell.ORACLE_HOME DEFAULT=/usr/lib/oracle/12.1/client64PATH OVERRIDE=/usr/local/bin:/usr/bin:/bin:${ORACLE_HOME}/binLD_LIBRARY_PATH DEFAULT=$ORACLE_HOME/libNote that you can refer to other variables, but you can't refer to a variable's previous value.If you want a more flexible approach, add the variable definitions to /etc/profile instead. There you can use all shell constructs. The downside is that this is only read in login sessions, not e.g. by cron. You can easily benefit from them by adding . /etc/profile; at the beginning of your cron jobs however.export ORACLE_HOME=/usr/lib/oracle/12.1/client64PATH=$ORACLE_HOME/bin:$PATHexport LD_LIBRARY_PATH=$ORACLE_HOME/lib |
_unix.105005 | How can I make a shared library which is in /usr/lib/some-path linkable with the g++ -l argument when compiling?As far as I know, to do what I want, I need to chmod 0755 the library .so file, create some kind of a link file and I need to update the library cache. I tried using ldconfig command and it worked, but not for the subdirectories of /usr/lib. I also tried ln -s /usr/lib/some-path/libmy.so /link/file/output/dir which created a link file, but g++ still couldn't find the library with the -lmy. I tied running ldconfig after ln but that did not help. | How to make a library linkable with g++ -l argument | libraries;g++ | null |
_webmaster.34094 | Is there a way to separate out browser usage by location in Google Analytics? Like for example, seeing that all traffic from Nevada came from what browsers? Or, selecting a single browser and seeing where all of the traffic came from that used that browser? | View browser usage by location in Google Analytics | google analytics | From the default reporting page for the property you would like to review:Go to the Audience tab in the left menu bar and select Demographics then LocationSelect Technology then Browser from the Secondary Dimension menu (just above the data table)Switch between geographic divisions (Country/Territory, City, Continent, Sub Continent Region), click through linked regions in the data table, and/or use the search box to drill down to the locations you'd like to review |
_scicomp.25702 | Consider the 1D poisson equation$$\frac{d^2 u}{dx^2} = -\rho$$with Dirichlet boundary conditions $u(0) = u(l) = g$. Using a finite difference scheme, with a 5-point grid $u_1,u_2,u_3,u_4,u_5$ (excluding boundary points $u_0$ and $u_l$), we get the set of linear equations$$\left( \begin{array}{ccc}2 & -1 & & & \\-1 & 2 & -1 & & \\ & -1 & 2 & -1 & \\ & & -1 & 2 & -1 \\ & & & -1 & 2 \\\end{array} \right)\left( \begin{array}{c} u_1 \\ u_2 \\ u_3 \\ u_4 \\ u_5\end{array} \right) = \left( \begin{array}{c} \rho_1+g \\ \rho_2 \\ \rho_3 \\ \rho_4 \\ \rho_5+g\end{array} \right)$$My question is: What would the matrix look like if I made $u_3$ a boundary point too?Would it look like$$\left( \begin{array}{ccc}2 & -1 & & & \\-1 & 2 & 0 & & \\ & 0 & 1 & 0 & \\ & & 0 & 2 & -1 \\ & & & -1 & 2 \\\end{array} \right)\left( \begin{array}{c} u_1 \\ u_2 \\ u_3 \\ u_4 \\ u_5\end{array} \right) = \left( \begin{array}{c} \rho_1+g \\ \rho_2+g \\ g \\ \rho_4+g \\ \rho_5+g\end{array} \right)$$I ask because I have a 3d system with small but irregular internal boundary regions, and it would be currently more convenient for my purposes to leave them in the matrix (even if it means extra computational cost). | Explicitly including boundary points in a set of finite-difference equations | finite difference;poisson | If you include the boundary condition directly in the matrix, you will only get the g value at the points where the boundary is prescribed. If we use 5 nodes with the following BCS:$$u_1=g_1$$ and $$u_5=g_5$$Then the matrix resulting from the finite difference will be:$$\left( \begin{array}{ccc}1 & 0 & & & \\-1 & 2 & -1 & & \\ & -1 & 2 & -1 & \\ & & -1 & 2 & -1 \\ & & & 0 & 1 \\\end{array} \right)\left( \begin{array}{c} u_1 \\ u_2 \\ u_3 \\ u_4 \\ u_5\end{array} \right) = \left( \begin{array}{c} g_1 \\ \rho_2 \\ \rho_3 \\ \rho_4 \\ g_5\end{array} \right)$$That is, the value of $$u_1$$ and $$u_5$$ follow the Dirichlet BCs and within the domain, the Poisson equation applies.If you have Neumann boundary conditions or Robin Boundary condition, than line 1 and 5 will have to change to respect the application of these boundary conditions.If the third point is a boundary point and following my example, then the resulting matrix should be :$$\left( \begin{array}{ccc}1 & 0 & & & \\-1 & 2 & -1 & & \\ & 0 & 1 & 0 & \\ & & -1 & 2 & -1 \\ & & & 0 & 1 \\\end{array} \right)\left( \begin{array}{c} u_1 \\ u_2 \\ u_3 \\ u_4 \\ u_5\end{array} \right) = \left( \begin{array}{c} g_1 \\ \rho_2 \\ g_3 \\ \rho_4 \\ g_5\end{array} \right)$$But this is impossible in our case, since this would imply prescribing 3 conditions on a problem which requires 2.In 2D, however, you will get lines with strictly diagonal term that appear within the matrix due to Dirichlet BCs. |
_unix.305024 | I recently moved my Debian Gnome 3 installation to a new computer with a GTX 1070. I had previously installed old Nvidia drivers which didn't support the 1070, so when I booted up I was faced with a blinking prompt. To remedy this, I went into the command prompt with CTRL-ALT-F2, did sudo apt-get purge nvidia* and installed the Nvidia 367.27 Drivers. When I rebooted after installing the drivers successfully, Debian displayed Loading, please wait..., indefinitely. When I rebooted again, it (Gnome, I presume) displayed this Oh no! Something has gone wrong. message. Now, when I boot into Debian, I always get one of those two messages.Does anyone have a clue what has gone wrong? Is there any way to fix this, or is it time for me to reinstall? | Debian installation not booting after Nvidia drivers installation | debian;nvidia | null |
_softwareengineering.107687 | I've been messing around with functional programming languages for a few years, and I keep encountering this phrase. For example, it is a chapter of The Little Schemer, which certainly predates the blog by this name. (No, the chapter doesn't help answer my question.)I understand what lambda means, the idea of an anonymous function is both simple and powerful, but I fail to understand what the ultimate means in this context.Places that I've seen this phrase:The title of chapter 8 of The Little SchemerA blog: http://lambda-the-ultimate.org/A series of Lambda the ultimate X papers: http://library.readscheme.org/page1.htmlI feel like I'm missing a reference here, can anyone help? | What is the origin and meaning of the phrase Lambda the ultimate? | functional programming;terminology;history;lambda | Yes, it's simply a recurring phrase in the title of several papers, starting from a couple in the 70s, in which Sussman and Steele demonstrate the use of lambda calculus for programming, by means of a minimalist Lisp dialect named Scheme they devised for the purpose. You can find the papers themselves here; they're interesting and surprisingly relevant.I'm not sure if this is ever explicitly stated, but it's clear (from context, having read the papers, and knowing the general background and research interests of the authors) that the phrase is simply a catchy slogan for their contention that lambda abstractions, as a computational primitive, are not only universal in the formal sense (of being able to encode any program in some fashion, however awkward), but universal in a practical sense that any and every construct present in other languages, even those that are baked-in from the ground up, can be reimplemented in a lambda-based language in a way that is both effective and natural to use.The repeated phrase leads to the obvious generalized form for all X, lambda is the ultimate X, which is the sense I've generally taken Lambda the Ultimate to mean as the blog name, noting that LtU is concerned with programming language design and theory. Ironically, LtU would probably also be one of the best places to find someone who could tell you about something for which lambda is not the ultimate implementation. :]Note also that Sussman is one of the authors of SICP, a very influential textbook that also uses the Scheme language and spends a fair amount of time introducing lambda abstractions as a concept. |
_softwareengineering.117378 | We have outsourced the html and css design to an external company. We want to make sure the quality of code is good. What benchmarks can we set to achieve this. | How do I validate the html/css and JS code outsourced to an external company. | javascript;css | null |
_codereview.30498 | I'd like feedback on my callbacks/promises alternative, please.The yld repositoryvar yld;yld = (function () {'use strict';var slice, clearer, defer, prepare, yld;slice = Array.prototype.slice;clearer = { yld: { value: undefined }, throw: { value: undefined }};Object.freeze(clearer);defer = typeof process === 'object' && typeof process.nextTick === 'function' ? process.nextTick : function nextTick(closure) { setTimeout(closure);};prepare = function* (parent) { var proto, generator, fnGenerator, response; proto = { yld: function (fn) { var parent; parent = this; return function () { var generator, proto, fnGenerator; generator = prepare(parent); proto = generator.next().value; generator.next(generator); fnGenerator = fn.apply(proto, arguments); generator.next(fnGenerator); return Object.create(proto, clearer); }; }, next: function (value) { defer(function () { generator.next(value); }); }, nextCb: function () { var value; value = slice.call(arguments); defer(function () { generator.next(value); }); }, throw: function(error) { defer(function() { fnGenerator.throw(error); }); } }; if (parent !== undefined) { proto.parent = Object.create(parent, clearer); } generator = yield proto; fnGenerator = yield null; while (true) { response = yield defer(function () { fnGenerator.next(response); }); }};yld = function (fn) { return function () { var generator, proto, fnGenerator; generator = prepare(); proto = generator.next().value; generator.next(generator); fnGenerator = fn.apply(proto, arguments); generator.next(fnGenerator); return Object.create(proto, clearer); };};return yld;}());if (typeof module === 'object' && module.exports !== undefined) { module.exports = yld;} | My yld NPM - callbacks/promises alternative | javascript;node.js;callback;promise | null |
_codereview.94277 | The prompt that made me put this function together was sourced from CodingBat.I was curious about cleaner, more correct methods of doing putting this together such as finding a cleaner way to tell if there is or is not a duplicate in the array. I am also trying to be as efficient as possible. I believe this is an \$O(n^2)\$ function. Let me know what I should change.The code works just fine. I just feel like there is quite a lot I can streamline and I would like to be pointed in the right direction. public int maxSpan(int[] nums) { int highestSpan = 0; int span; boolean duplicate = false; if (nums.length == 0) return highestSpan; for (int i = 0; i < nums.length; i++) { for (int j = 0; j < nums.length; j++){ if ((nums[i] == nums[j])&& j != i){ //if duplicate duplicate = true; //get the absolute value of j - i span = j - i + 1; //Add 1 because it needs to count itself //if it is larger than the highestSpan then record it if (span > highestSpan) highestSpan = span; } } } if (duplicate) return highestSpan; else return 1;} | Finding the maximum inclusive distance between two duplicate numbers in an array | java | Getting rid of duplicate as Janos proposed and then QPaysTaxes wrote is a good step, but this useless variable introduced quite some useless code we should also get rid of. The following code builds up on QPaysTaxes' answer; I'm commenting on changed things and presenting my variant:public int maxSpan(int[] nums) { int highestSpan = 0;This is not the place where span should be defined. You don't need it here.The condition nums.length == 0 can go. for (int i = 0; i < nums.length; i++) { for (int j = i; j < nums.length; j++) {Changed the lower bound from i+1 to i to cover span equal to 1. Below removed the i != j test and used max to make the code a bit shorter. if (nums[i] == nums[j]) { int span = j - i + 1; // Add 1 to count itself highestSpan = Math.max(highestSpan, span); } } }No need for a conditional here. return highestSpan;}I guess, I saved some 6 lines without making it any more complicated. Now can also span be inlined to save 1 more line (but that's not the objective).--Now it works exactly according to the explanation by QPaysTaxes in comment without any special tests:An empty array doesn't have any spans, so clearly it has to return 0. An array of unique elements is rather more confusing, but since the prompt states that a single (i.e. unduplicated) element has a span of 1, then an array of unique (i.e. unduplicated [i.e. single]) elements has a maximum span of the span of every unique numberAn O(n) solution could look like this (untested):public int maxSpan(int[] nums) { int highestSpan = nums.length == 0 ? 0 : 1; Map<Integer, Integer> firstOccurrenceMap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { Integer firstOccurrence = firstOccurrenceMap.get(nums[i]); if (firstOccurrence == null) { firstOccurrenceMap.put(nums[i], i); } else { highestSpan = Math.max(highestSpan, i - firstOccurrence + 1); } } return highestSpan;}As the first occurrence of a number gets a special treatment, the empty array has to be handled specially, too (see the declaration of highestSpan). |
_unix.96698 | Today I bought an ibook G4 from a garage sale. The people who sold it to me didn't know the password for the 2 accounts on it. Apparently it was the guys late father's laptop. Any suggestions on how to get into the laptop and set a new admin account and password? | Mac OS X Darwin: how to reset admin password? | osx;root;startup | You must boot the Mac into single user mode and change an admin user's password from the command line. How to do it depends on the Mac OS version installed on the iBook.Here are the instructions for 10.4 (Tiger) which is probably what's installed on such an old Mac:Power on your Mac.At the chime hold down Command S on your keyboard to boot into single-user mode.Type sh /etc/rc and press Return.Type passwd username Return, replacing username with the short name of the account whose password you want to change. You can get a list of account short names with ls /Users Return.Enter the new password and press Return.Type reboot Return.Once the Mac boots you should be able to log into the account whose password you changed. |
_unix.12206 | I am new to Linux, installed Gnome, and unable to login, as only root is set, and disabled, I think after reading on the Internet.Now how do i get back to the command line, at least so I can deal with that and fix my issues from there? I am unable to bypass the Gnome login screen. | Debian (Gnome): unable to login | linux;debian;gnome;login | null |
_codereview.11503 | I only recently started coding so I know my code is not very good, but i would really appreciate any help on improving my code.my database table looks like thisgame_id |title |developer |publisher |genre |release_date |platform rating |image_location |descriptionthe first pagethis page is pretty straightforward your typical search that links to the search page and passes the keywords entered through GET<div id=\top_search\> <form name=\input\ action=\search.php\ method=\get\ id=\search_form\> <input type=\text\ id=\keywords\ name=\keywords\ size=\128\ class=\searchbox\ value=\$defaultText\> <select id=\category\ name=\category\ class=\searchbox\> ;createCategoryList();echo ' </select> <input type=submit value=Search class=button /> </form> </div>the second page is the search pagethis is where things got complicated for me.Here is what i did i created a buch of links on the left side, each link submits back to the same page but passes 4 variables with them which i use on the third page to create the query.As you can see its not very pretty.<?phpsession_start();include(includes/html_codes.php);include (includes/search_func.php);if (isset($_GET['keywords'])){$keywords = mysql_real_escape_string(htmlentities(trim($_GET['keywords']))); }if (isset($_GET['order'])){$order = mysql_real_escape_string(htmlentities(trim($_GET['order']))); }else{ $order = '';}if (isset($_GET['platform'])){$platform = mysql_real_escape_string(htmlentities(trim($_GET['platform']))); }else{ $platform = '';}if (isset($_GET['genre'])){$genre = mysql_real_escape_string(htmlentities(trim($_GET['genre']))); }else{ $genre = '';}$errors = array();if(empty($keywords)){ $errors[] = 'Please enter a search term';}else if(strlen($keywords)<3){ $errors[] = 'Your search term must be at least 3 characters long';}else if(search_results($keywords) == false){ $errors[] = 'Your search for'.$keywords.' returned no results';}if(empty($errors)){ $results = search_results($keywords); $results_num = count($results);}else{ foreach($errors as $error){ echo $error, '<br />'; }}?> <!DOCTYPE html ><html lang=en><head><title>Search</title><link rel=stylesheet href=css/main.css><link rel=stylesheet href=css/search.css></head><body><?php topBanner(); ?> <div id=wrapper><?php headerAndSearchCode(); echo $_SERVER['QUERY_STRING'];echo $keywords;?> <div id=main_section class=header> <?php echo ' <div id=filter_nav> <ul id=nav_form> <li><h3 id=h3>Genre: </h3> <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre=Fighting&order='.$order.'>Fighting</a></li> <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre=Role-Playing&order='.$order.'>Role-Playing</a></li> <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre=Action&order='.$order.'>Action</a></li> </ul> <ul id=nav_form> <li><h3 id=h3>Platform: </h3> <li><a href=search.php?keywords='.$keywords.'&platform=Playstation 3&genre='.$genre.'&order='.$order.'>PS3</a></li> <li><a href=search.php?keywords='.$keywords.'&platform=xbox 360&genre='.$genre.'&order='.$order.'>Xbox 360</a></li> <li><a href=search.php?keywords='.$keywords.'&platform=Gamecube&genre='.$genre.'&order='.$order.'>Gamecube</a></li> </ul> </div> '; echo ' <ul id=sorting_form> <li><h3 id=h3>SORT BY: </h3> <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre='.$genre.'&order=title>Title</a></li> <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre='.$genre.'&order=release_date>Date</a></li> <li><a href=search.php?keywords='.$keywords.'&platform='.$platform.'&genre='.$genre.'&order=rating>Rating</a></li> </ul> '; echo '<div id=results>'; foreach($results as $result ){ echo ' <div id=game_result> <a href= game_page.php?game_id='.$result['game_id'].'><img src= '.$result['image_location'].' id=image /></a> <div id=main_title> <a href= game_page.php?game_id='.$result['game_id'].'><h2 id=game_title>'.$result['title'].' </h2></a> <h3 id=platform>for '.$result['platform'].'</h3> </div> <p id=game_description>'.$result['description'].'</p> <div id=right_side> <h4 id=rating>'.$result['rating'].'</h4> </div> <hr id=hr/> </div> ';} echo '</div>';;?> </div></div>`page three is where i query the database and get results. Not as bad as page 2function search_results($keywords){$returned_results = array();$where = ;$keywords = preg_split('/[\s]+/', $keywords);$total_keywords = count($keywords);foreach($keywords as $key=>$keyword){ $where .= title LIKE '%$keyword%'; if($key != ($total_keywords - 1)){ $where .= AND ; } }if (isset($_GET['platform']) && !empty($_GET['platform'])){ $platform = mysql_real_escape_string(htmlentities(trim($_GET['platform']))); $where .= AND platform='$platform'; }if (isset($_GET['genre']) && !empty($_GET['genre'])){ $genre = mysql_real_escape_string(htmlentities(trim($_GET['genre']))); $where .= AND genre='$genre';}if (isset($_GET['order']) && !empty($_GET['order'])){ $order = mysql_real_escape_string(htmlentities(trim($_GET['order']))); if($where == ORDER BY $order ASC){ $where .= ORDER BY $order DESC; }else{ $where .= ORDER BY $order ASC; }}$results =SELECT * FROM games WHERE $where ;echo $results;$results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0;if($results_num === 0){ return false;}else{ while($row = mysql_fetch_assoc($results)){ $returned_results[] = array( 'game_id' => $row['game_id'], 'title' => $row['title'], 'platform' => $row['platform'], 'rating' => $row['rating'], 'image_location' => $row['image_location'], 'description' => $row['description'], ); } return $returned_results;} }?>Things i need help with being able to remove a chosen filter categoryeasier way to pass variables to the query stringbetter way to structure a filter for mysqlany feedback that will help me improve my codethanks | need help improving mysql and php filter code | php;mysql;search | here's a quick run down on your script from my perspective. Hopefully it will help you out and make your code a bit more efficient and a little prettier! :)Whilst admirable that you are attempting to stop SQL injection attacks with mysql_real_escape_string() it is really not the best method to protect yourself. Consider instead using prepared statements with PDO, believe me learning this will save you a lot of time!You also repeat alot of code, for example this line pops up a lot.$keywords = mysql_real_escape_string(htmlentities(trim($_GET[$x])));Why not put it into a function?function prepVar($var) { return mysql_real_escape_string(htmlentities(trim($var)));}and then just use$platform = prepVar($_GET['platform']);Another few pointers on isset and empty. You've explicitly asked for a variable to be set and not empty. (check this article out: http://www.htmlcenter.com/blog/empty-and-isset-in-php/)isset will return TRUE if the variable has a type i.e. String, Object etc. i.e. the variable already exists in the scope.empty will return TRUE if the variable === 0 || === false || === nullAs (in this case) empty will return true if the variable is not set (as the var would === null). You only need to use empty.$platform = $_GET['platform'];$platform = !empty($platform) ? prepVar($platform) : '';The same principles can be applied to your third page with the added complication of adding the $where variable to each of the operations.if (!empty($platform)) { $platform = prepVar($platform); $where .= platform = '{$platform}';}I don't understand this bit of code:if (isset($_GET['order']) && !empty($_GET['order'])){ $order = mysql_real_escape_string(htmlentities(trim($_GET['order']))); if($where == ORDER BY $order ASC){ $where .= ORDER BY $order DESC; }else{ $where .= ORDER BY $order ASC; }}Are you sure you want to be checking $where for a value, if it contains that value append a second ORDER BY statement to it? That doesn't make much sense :(Removing a filter categoryI would save the search state to $_SESSION each time it is run through your function. You can then recall the previous search state, modify it and then run that through your query again allowing you to remove / change / add as much or as little as you want.Easier ways to pass to your query stringFirstly you are asking for the same information within your function as you are within the procedural code on your second page. if (isset($_GET['platform']) && !empty($_GET['platform'])){ ...As you already have variables that have been mildly sanitised with mysql_real_escape_string() why not pass them to the function as variables as well. Or declare them global variables within the function? In essence the easier way is to make sure you are not duplication your code, setting a variable once and using that variable throughout your script will yield greater stability of your application in the long run.Better way to structure a filter for mySQLI dont see a problem with the way you are structuring it, personally I prefer to use functions to decorate SQL queries. In honesty it is each to there own! |
_codereview.74850 | Previous question:https://codereview.stackexchange.com/questions/74677/text-based-tetris-game-follow-up-finalSummary of improvements:Implementation of a Drawable classSeparate functionality, input moves to Game classImplementation of Cloneable class by CRTPRemoved global variables Added Block classImproving the game loop timer by implementing <chrono>How can I improve this code further?Tetris.cpp#include <iostream>#include <vector>#include <algorithm>#include <random>#include <memory>#include <chrono>#include utility.husing Matrix = std::vector<std::vector<int>>;class Shape{public: virtual ~Shape() = default; virtual Shape *clone() const = 0; virtual int getDrived(std::size_t i, std::size_t j) const = 0;};template <typename Derived>struct Clonable : public Shape{ virtual Shape *clone() const { return new Derived(static_cast<const Derived&>(*this)); }};class O : public Clonable<O>{public: O() = default; virtual ~O() = default; virtual int getDrived(std::size_t i, std::size_t j) const { return shape[i][j]; }private: Matrix shape { { { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 0, 0, 0, 0 } } };};class L : public Clonable<L>{public: L() = default; virtual ~L() = default; virtual int getDrived(std::size_t i, std::size_t j) const { return shape[i][j]; }private: Matrix shape { { { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 } } };};class N : public Clonable<N>{public: N() = default; virtual ~N() = default; virtual int getDrived(std::size_t i, std::size_t j) const { return shape[i][j]; }private: Matrix shape { { { 0, 1, 0, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 } } };};class M : public Clonable<M>{public: M() = default; virtual ~M() = default; virtual int getDrived(std::size_t i, std::size_t j) const { return shape[i][j]; }private: Matrix shape { { { 0, 0, 1, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 }, { 0, 0, 0, 0 } } };};class T : public Clonable<T>{public: T() = default; virtual ~T() = default; virtual int getDrived(std::size_t i, std::size_t j) const { return shape[i][j]; }private: Matrix shape { { { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } } };};class I : public Clonable<I>{public: I() = default; virtual ~I() = default; virtual int getDrived(std::size_t i, std::size_t j) const { return shape[i][j]; }private: Matrix shape { { { 0, 1, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 } } };};class S : public Clonable<S>{public: S() = default; virtual ~S() = default; virtual int getDrived(std::size_t i, std::size_t j) const { return shape[i][j]; }private: Matrix shape { { { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 } } };};class NonCopyable{public: NonCopyable() = default; virtual ~NonCopyable() = default;private: NonCopyable(const NonCopyable &) = delete; NonCopyable(const NonCopyable &&) = delete; NonCopyable& operator = (const NonCopyable&) = delete;};struct Drawable{ virtual void draw(std::ostream& stream) const = 0;};class Random : private NonCopyable{public: Random(int min, int max) : mUniformDistribution(min, max) {} int operator()() { return mUniformDistribution(mEngine); }private: std::default_random_engine mEngine{ std::random_device()() }; std::uniform_int_distribution<int> mUniformDistribution;};class Block : private NonCopyable{public: using Ptr = std::unique_ptr<Shape>; Block();protected: void createBlock(); void rotateBlock(); std::size_t size() const { return ilBlock.size(); } Matrix mBlock; static const std::initializer_list<size_t> ilBlock;private: // shapes Ptr t; Ptr m; Ptr n; Ptr i; Ptr o; Ptr l; Ptr s; std::vector<Ptr> shapes; const int shapeCounter = 7; Random getRandom{ 0, shapeCounter - 1 };};const std::initializer_list<size_t> Block::ilBlock ={ 0, 1, 2, 3};Block::Block() : t(std::make_unique<T>()) , m(std::make_unique<M>()) , n(std::make_unique<N>()) , i(std::make_unique<I>()) , o(std::make_unique<O>()) , l(std::make_unique<L>()) , s(std::make_unique<S>()){ mBlock.resize(ilBlock.size(), std::vector<int>(ilBlock.size(), 0)); shapes.emplace_back(std::move(t->clone())); shapes.emplace_back(std::move(m->clone())); shapes.emplace_back(std::move(n->clone())); shapes.emplace_back(std::move(i->clone())); shapes.emplace_back(std::move(o->clone())); shapes.emplace_back(std::move(l->clone())); shapes.emplace_back(std::move(s->clone())); createBlock();}void Block::createBlock(){ int blockType = getRandom(); for (auto i : ilBlock) { for (auto j : ilBlock) { mBlock[i][j] = shapes[blockType]->getDrived(i, j); } }}void Block::rotateBlock(){ for (auto i : ilBlock) { for (auto j : ilBlock) { if (i < j) { std::swap(mBlock[i][j], mBlock[j][i]); } } std::reverse(mBlock[i].begin(), mBlock[i].end()); }}class Tetris : public Block, public Drawable{public: Tetris(); void moveBlock(int, int); bool isCollide(int, int); void spawnBlock(); bool applyRotate(); bool isFull(); COORD getPosition() { return position; }private: void initField(); void makeBlocks(); void checkLine(); Matrix mStage; COORD position; virtual void draw(std::ostream& stream) const; friend std::ostream& operator<<(std::ostream& stream, const Tetris& self) { self.draw(stream); return stream; } int mScore = 0; Matrix mBoard; static const std::initializer_list<size_t> ilBoard; static const std::initializer_list<size_t> ilBoardRow;};Tetris::Tetris(){ mBoard.resize(ilBoard.size(), std::vector<int>(ilBoardRow.size(), 0)); mStage.resize(ilBoard.size(), std::vector<int>(ilBoardRow.size(), 0)); initField();}const std::initializer_list<size_t> Tetris::ilBoard ={ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};const std::initializer_list<size_t> Tetris::ilBoardRow ={ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};void Tetris::initField(){ for (auto i = ilBoard.begin(); i != ilBoard.end() - 1; ++i) { for (auto j = ilBoardRow.begin(); j != ilBoardRow.end() - 1; ++j) { if ((*j == 0) || (*j == ilBoardRow.size() - 2) || (*i == ilBoard.size() - 2)) { mBoard[*i][*j] = mStage[*i][*j] = 9; } else { mBoard[*i][*j] = mStage[*i][*j] = 0; } } } makeBlocks();}void Tetris::makeBlocks(){ position.X = ilBlock.size(); position.Y = 0; createBlock(); for (auto i : ilBlock) { for (auto j : ilBlock) { mBoard[i][j + size()] += mBlock[i][j]; } }}bool Tetris::isFull(){ for (auto i : ilBlock) { for (auto j : ilBlock) { if (mBoard[i][j + size()] > 1) { return true; } } } return false;}void Tetris::moveBlock(int x2, int y2){ for (auto i : ilBlock) { for (auto j : ilBlock) { mBoard[position.Y + i][position.X + j] -= mBlock[i][j]; } } position.X = x2; position.Y = y2; for (auto i : ilBlock) { for (auto j : ilBlock) { mBoard[position.Y + i][position.X + j] += mBlock[i][j]; } }}void Tetris::checkLine(){ std::copy(mBoard.begin(), mBoard.end(), mStage.begin()); for (auto i = ilBoard.begin() + 1; i != ilBoard.end() - 2; ++i) { bool isCompeteLine = true; for (auto j = ilBoardRow.begin() + 1; j != ilBoardRow.end() - 1; ++j) { if (mStage[*i][*j] == 0) { isCompeteLine = false; } } if (isCompeteLine) { mScore += 10; for (auto k : ilBlock) { std::copy(mStage[*i - 1 - k].begin(), mStage[*i - 1 - k].end(), mStage[*i - k].begin()); } } } std::copy(mStage.begin(), mStage.end(), mBoard.begin());}bool Tetris::isCollide(int x, int y){ for (auto i : ilBlock) { for (auto j : ilBlock) { if (mBlock[i][j] && mStage[y + i][x + j] != 0) { return true; } } } return false;}bool Tetris::applyRotate(){ Matrix temp(ilBlock.size(), std::vector<int>(ilBlock.size(), 0)); std::copy(mBlock.begin(), mBlock.end(), temp.begin()); rotateBlock(); if (isCollide(position.X, position.Y)) { std::copy(temp.begin(), temp.end(), mBlock.begin()); return true; } for (auto i : ilBlock) { for (auto j : ilBlock) { mBoard[position.Y + i][position.X + j] -= temp[i][j]; mBoard[position.Y + i][position.X + j] += mBlock[i][j]; } } return false;}void Tetris::spawnBlock(){ if (!isCollide(position.X, position.Y + 1)) { moveBlock(position.X, position.Y + 1); } else { checkLine(); makeBlocks(); }}void Tetris::draw(std::ostream& stream) const{ for (auto i : ilBoard) { for (auto j : ilBoardRow) { switch (mBoard[i][j]) { case 0: stream << ' '; break; case 9: stream << '@'; break; default: stream << '#'; break; } } stream << '\n'; } stream << Score : << mScore << \n\n\tA: left\tS: down\tD: right \t Rotation[Space];}class Game : private NonCopyable{public: int menu(); void gameLoop();private: void introScreen(); void userInput(); void display(); void gameOverScreen(); Tetris tetris;};void Game::gameOverScreen(){ std::cout << \n ##### # # # ####### ####### # # ####### ######\n # # # # ## ## # # # # # # # #\n # # # # # # # # # # # # # # #\n # #### # # # # # ##### # # # # ##### ######\n # # ####### # # # # # # # # # #\n # # # # # # # # # # # # # #\n ##### # # # # ####### ####### # ####### # #\n \n\nPress any key and enter\n; std::cin.ignore(); std::cin.get();}void Game::gameLoop(){ auto start = std::chrono::high_resolution_clock::now(); while (!tetris.isFull()) { auto end = std::chrono::high_resolution_clock::now(); double timeTakenInSeconds = (end - start).count() * (static_cast<double>(std::chrono::high_resolution_clock::period::num) / std::chrono::high_resolution_clock::period::den); if (_kbhit()) { userInput(); } if(timeTakenInSeconds > .3) { tetris.spawnBlock(); display(); start = std::chrono::high_resolution_clock::now(); } } clearScreen(); gameOverScreen();}int Game::menu(){ introScreen(); int select_num = 0; std::cin >> select_num; switch (select_num) { case 1: case 2: break; default: select_num = 0; break; } return select_num;}void Game::introScreen(){ clearScreen(); std::cout << #==============================================================================#\n ####### ####### ####### ###### ### #####\n # # # # # # # #\n # # # # # # #\n # ##### # ###### # #####\n # # # # # # #\n # # # # # # # #\n # ####### # # # ### #####\t\tmade for fun \n \n\n\n\n \t<Menu>\n \t1: Start Game\n\t2: Quit\n\n #==============================================================================#\n Choose >> ;}void Game::display(){ clearScreen(); std::cout << tetris;}void Game::userInput(){ switch (_getch()) { case 77: if (!tetris.isCollide(tetris.getPosition().X + 1, tetris.getPosition().Y)) { tetris.moveBlock(tetris.getPosition().X + 1, tetris.getPosition().Y); } break; case 75: if (!tetris.isCollide(tetris.getPosition().X - 1, tetris.getPosition().Y)) { tetris.moveBlock(tetris.getPosition().X - 1, tetris.getPosition().Y); } break; case 80: if (!tetris.isCollide(tetris.getPosition().X, tetris.getPosition().Y + 1)) { tetris.moveBlock(tetris.getPosition().X, tetris.getPosition().Y + 1); } break; case 72: tetris.applyRotate(); }}int main(){ Game game; switch (game.menu()) { case 1: game.gameLoop(); break; case 2: return 0; default: std::cerr << Choose 1~2 << std::endl; return -1; }}utility.h#if defined(__linux__) || defined(__APPLE__)#include <sys/time.h>#include <termios.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> static struct termios g_old_kbd_mode;static void cooked(void){ tcsetattr(0, TCSANOW, &g_old_kbd_mode);}static void raw(void){ static char init; struct termios new_kbd_mode; if (init) { return; } tcgetattr(0, &g_old_kbd_mode); memcpy(&new_kbd_mode, &g_old_kbd_mode, sizeof(struct termios)); new_kbd_mode.c_lflag &= ~(ICANON | ECHO); new_kbd_mode.c_cc[VTIME] = 0; new_kbd_mode.c_cc[VMIN] = 1; tcsetattr(0, TCSANOW, &new_kbd_mode); atexit(cooked); init = 1;}static int _kbhit(void){ struct timeval timeout; fd_set read_handles; int status; raw(); FD_ZERO(&read_handles); FD_SET(0, &read_handles); timeout.tv_sec = timeout.tv_usec = 0; status = select(0 + 1, &read_handles, NULL, NULL, &timeout); if (status < 0) { printf(select() failed in kbhit()\n); exit(1); } return status;}static int _getch(void){ unsigned char temp; raw(); if (read(0, &temp, 1) != 1) { return 0; } return temp;}bool gotoxy(unsigned short x = 1, unsigned short y = 1){ if ((x == 0) || (y == 0)) { return false; } std::cout << \x1B[ << y << ; << x << H; return true}void clearScreen(bool moveToStart = true){ std::cout << \x1B[2J; if (moveToStart) { gotoxy(1, 1); }}#elif _WIN32#include <conio.h>#include <Windows.h>#include <tchar.h>namespace{ HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO csbi;};void clearScreen(){ static DWORD count; static DWORD cellCount; COORD homeCoords = { 0, 0 }; if (!GetConsoleScreenBufferInfo(hStdOut, &csbi)) std::cerr << ERROR GetConsoleScreenBufferInfo - clearScreen : << GetLastError() << std::endl; cellCount = csbi.dwSize.X *csbi.dwSize.Y; FillConsoleOutputCharacter(hStdOut, (TCHAR) ' ', cellCount, homeCoords, &count); FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, cellCount, homeCoords, &count); SetConsoleCursorPosition(hStdOut, homeCoords);}#else#error OS not supported!#endif | Text-based Tetris game with CRTP - follow-up | c++;c++11;console;polymorphism;tetris | Issues preventing the code from compiling on Clang:In the Linux/Apple path from utility.h, function gotoxy(), you forgot a semicolonin the last return statement:bool gotoxy(unsigned short x = 1, unsigned short y = 1){ if ((x == 0) || (y == 0)) { return false; } std::cout << \x1B[ << y << ; << x << H; return true; // <--- Was missing the ';' ! }COORD is undefined. You are relying on the definition provided by Windows.h, which obviously doesn't exist elsewhere. Either define COORD for the Unix path yourself or better, provide your own Point2D struct that replaces the non-portable Win32 COORD type.std::make_unique is shamefully not available on Clang as of today. No easy fix herebut to define your own fallback replacement or avoid make_unique altogether. You can finda code snippet for a make_unique replacement in here.Code review:When we override a function from a base class, such as clone() and getDrived() from Shape, we can now add the override specifier to aid compiler diagnostics and optimizations. Its use can also make code clearer and intentions more explicit.The method name getDrived() of Shape doesn't make sense to me. What exactly is its purpose? It gets an element of the matrix that composes the char map of a shape. Then perhaps is should be called getCharacter()? But that would still sound weird, since we are talking about a shape. Then perhaps getPixel() or getDot() would be better,if we are talking about a 2D shape that is represented by dots/pixels.Speaking of the Shape derived classes, you have quite a few single letter type name representing the formats of the Tetris pieces. Since the names are single letter each, it might be nice to nest then into a namespace to give more context to the names. Maybe in a shapes namespace:namespace shapes{ class O { ... }; class L { ... }; class M { ... }; ...}Then code using them would look like this:auto shape = make_unique<shapes::O>();More verbose, but with a little more context about what an O means.In Tetris::draw(), it is not clear to me the meaning of the constants 0 and 9 usedin the switch statement. Zero is an empty slot, while nine seems to be the borders of the Tetris board. So those should be constants that convey this information more clearly.Similar problem in Game::userInput(). The switch statement that handles the input is relying on raw numerical constants to represent the key presses. That is crying to be replaced by an enum.Gameplay tip: Show some info about the controls in the home screen or before starting the game. The user can't guess which keys to press to move the pieces around.On the architecture of Shape and derived classes:I think you've overengineered things a bit with the whole shape hierarchy. As it is, the shape classes are just serving as holders for a matrix of chars/dots. I would either replaces the shapes by simple matrices or would make them smarter by moving the drawing and any shape-related logic to the Shape interface and subclasses. As it stands, it just adds complexity to the code. If you move more logic to the shape classes, then they would justify their existence.Another thing, you don't have to keep those template shapes as members of Block:class Block : private NonCopyable{private: // These guys are never used after a block is constructed! Ptr t; Ptr m; Ptr n; Ptr i; Ptr o; Ptr l; Ptr s; // All you need is this array of Shape pointers. std::vector<Ptr> shapes;};All you do is reference them once in the constructor and then clone each into the shapes vector. Why not place the shapes directly into the vector then and get rid of those members?The shapes are currently just data holders, so you could make that clearer by storing pointers to const shapes, enforcing immutability:using Ptr = std::unique_ptr<const Shape>; |
_codereview.121179 | Follow up question toBinary Search Tree insert while keeping track of parent for node to be addedI am implementing a red black tree for fun and am wondering how I should modify my basic BST insert. Note: this happens before the red black tree rules are applied, it just finds the correct place within the tree to add the node, places it, sets references, value and defaults the color to RED. I am mainly struggling to see if there may be a better way to tack on the parent reference for the newly added node. The implementation I have here looks ahead one step with a NULL check where a BST insert that does not need to track the parent would not need.struct node * bstInsert(struct node *n, int x) { if (n != NULL) { int isGreater = (n->val < x) ? -1 : (n->val > x); if (isGreater == -1) { if (n->left == NULL) { n->left = createAChild(n, n->left, x); } else { bstInsert(n->left, x); } } else if (isGreater == 1) { if (n->right == NULL) { n->right = createAChild(n, n->right, x); } else { bstInsert(n->right, x); } } } else{ n = createAChild(NULL, n, x); } return n;}struct node * createAChild(struct node *par, struct node *n, int x) { n = malloc( sizeof(struct node) ); n->parent = par; n->left = n->right = NULL; n->val = x; n->color = RED; return n;}Is there a cleaner solution to setting the parent reference for the node to be added? | Binary Search Tree insert while keeping track of parent for node to be added - iteration 2 | c;recursion;tree;reference | You should check the result given by malloc, because otherwise your program may crash. Maybe not on your system right now, but basically, memory allocation can fail, and if it does, your program will crash afterwards by dereferencing a null pointer.Additionally, your createAChild function should not take a node pointer. What happens if I pass in an existing object? You just overwrite it. That's a cause for memory leaks. Treat createAChild as a constructor: either give it a cleanly allocated node struct, or let it allocate its own struct. |
_unix.55365 | I am running a VPS with FreeBSD 8.3-RELEASE-p3This is my first time using FBSD as a server,and as a newbie I locked myself out of su by taking my user out of wheel group.I have disabled the ability to login with 'root' from SSH in order to increase the security level of my server.I know that someVPS providers provide remote console control service that allows you to see what's going on the screen while booting and everything, but mine doesn't allow that.Will installing VNC for command-line use only, keep me unworried of making mistakes liketaking myself out of 'wheel' and not being able to 'su'? | Installing and using VNC for command-line purposes on FreeBSD | freebsd;vnc | If you are not root, you will not be able to install VNC, so this will not help.I think there are only two options Tell your Provider to log into the system from the console and readd the user to wheel.Find and exploit to enhance your privileges. :) |
_unix.298199 | I've noticed you can't really count on seq(1) being available on anything but GNU systems. What's a simple reimplementation of seq(1) I can bring with me written in POSIX (not bash) shell?EDIT: Note that I intend to use it on at least various BSD's, Solaris, and Mac OS X. | Portable POSIX shell alternative to GNU seq(1)? | posix;portability;seq | According to the open group POSIX awk supports BEGIN, therefore it can be done in awk:awk -v MYEND=6 'BEGIN { for(i=1;i<=MYEND;i++) print i }'Where -v MYEND=6 would stand for the assignment as in the first argument to seq. In other words, this works too:END=6for i in `awk -v MYEND=$END 'BEGIN { for(i=1;i<=MYEND;i++) print i }'`; do echo $idoneOr even with three variables (start, increment and end):S=2I=2E=12for i in `awk -v MYS=$S -v MYI=$I -v MYE=$E 'BEGIN { for(i=MYS;i<=MYE;i+=MYI) print i }'`; do echo $idoneExtra Solaris note: On Solaris /usr/bin/awk is not POSIX compliant, you need to use either nawk or /usr/xpg4/bin/awk on Solaris.On Solaris, you probably want to set /usr/xpg4/bin early in PATH if you are running a POSIX compliant script.Reference answer:awk hangs on Solaris |
_vi.9326 | I found that to press ]] to close a matching bracket by means of <Plug>(vimtex-delim-close) a little inconvenient, as I am using a French keyboard and have to press two keys to type ]. So I tried to use other keys, such as ). And typing the following when in a tex file works::inoremap ) <C-R>=<Plug>vimtex#delim#close()<CR>But, if I put the above inside my .vimrc file, I receive the error:E15: Invalid expression: <Plug>vimtex#delim#close()<CR>twice.I don't really understand how this works, such as <C-R>. So maybe I am just doing it wrong? In any case, any help or reference would be greatly appreciated.P.S. I think this is not a vimtex-specific question, but, as it involves this good package, I shall still tag as such. | How to remap vimtex#delim#close()? | key bindings;vimrc;plugin vimtex | null |
_cs.67445 | Is the language $\{ w \in \{ a, b \}^{*} : |w|_{a} + |w|_{b} = 2^{n} \}$ context sensitive ? | Is the language $\{ w \in \{ a, b \}^{*} | |w|_{a} + |w|_{b} = 2^{n} \}$ context sensitive? | formal languages;computability;context sensitive | null |
_softwareengineering.206150 | If I have a method taking input and giving output, it's a no-brainer that tests should be written. But what about things like validation rules?For example, I add a validation rule that a certain property must be at least 5 characters long. Should I then write a UI test to check for an error message when the form field is empty? Assume that the validation library itself works fine, the only thing I do is add a one-liner to specify this rule.I'm leaning towards no, because I'd only be duplicating the validation rules, and if the rules itself are set up incorrectly, the test will probably also be incorrect. However, I'd very much like to hear people's opinion and experience on this. | Should validation rules be tested? | testing | Absolutely, including if the underlying library (business layer) works fine.The reason is that there may be a lot of things going wrong between the business layer and the UI when it comes to validation. In the first case, you can simply throw an exception. In the second case, you have to process the exception, react to it (for example by cancelling the processing or doing or not doing a redirection, displaying a localized message, etc.)Imagine the validation of an e-mail address. The business layer detected that someone.somewhere.com is not a valid e-mail address. The expected behavior is to:Stop processing,Stop redirection,Show a message to the user,Highlight the e-mail field in red.What if:The processing is not stopped?The invalid e-mail is simply replaced by a null string?The redirection is still done?The message is not shown?The message is wrong?Another error message for an other field is shown together with the expected message?The message is correct is some cultures, but not in others?The message is too long in some cultures for the area?The e-mail field is not highlighted?Another field is highlighted together with the e-mail field?The e-mail field is empty, i.e. the previous input is discarded?All previous input of the form is discarded? |
_codereview.173646 | In my Win Forms application, I want to display the notifications badge count. How can this be achieved?notifyIcon1.Icon = SystemIcons.Exclamation;notifyIcon1.BalloonTipTitle = hello;notifyIcon1.BalloonTipText = text+s;notifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;// this.Click = new EventHandler(Form1_Load);notifyIcon1.Visible = true;notifyIcon1.ShowBalloonTip(100000);This is my code but it display notify icon but i want badge count on icon | In my Win Forms application, I want to display the notifications badge count . How can this be achieve? | c#;winforms;windows | null |
_unix.35515 | I have a CSV file that contains 10 different fields (, is the deliminator). Example data:student-id,last,first,hwk1,hwk2,hwk3,exam1,hwk4,hwk5,exam2pts-avail,,,100,150,100,200,150,100,300991-78-7872,Thompson,Ken,95,143,79,185,135,95,259I need to swap field2 and field3 using sed but having a difficult time understanding how to write the regular expression. I have tried along with other variations:sed 's/\(.*[,]\)\(.*[,]\)\(.*[,]\)/\1\3\2/g' testIn my test file:abc,def,ghi,jkl1234,5678,abcd,efghIt works fine I have been looking at this for a while and can't figure it out. Anyone able to provide some direction? | Swap two columns in a CSV using SED | text processing;sed;csv | null |
_softwareengineering.235033 | I am confused with what's the different between clarify and gather. I know using interview, observe or questionnaire can to elicit the requirement we want, but how to clarify the functional requirement? | What process will you use to clarify functional requirements and to gather non-functional requirements? | requirements;software | Gathering requirements means just that: collecting them. Clarifying requirements means making sure that those requirements are clear and unambiguous. You need clear and unambiguous requirements so that there is no dispute with the customer over whether or not something that was asked for has been provided.One way to clarify requirements is to write acceptance tests. Acceptance tests are tests that, if they pass, indicate that the requirement has been fulfilled.// Acceptance Testpublic void GetRandomNumber_ShouldReturn4(){ var result = GetRandomNumber(); Assert.IsEqual(result, 4);}// Implementationpublic int GetRandomNumber(){ return 4; // Chosen by fair dice roll. Guaranteed to be random.}If you're having difficulty with things like scope creep, inaccurate time estimates and disputes over completion of requirements, one way to refine those things is to write a Software Design Specification, including the classes and interfaces it would take to fulfill the requirements. This can be combined with the Ubiquitous Language of DDD to get a clear understanding of the scope of a project (from both the developers' and customer's perspective), and what it takes to declare success on each requirement.Further ReadingClarifying Requirements |
_unix.98084 | Is it possible to change the location of .bashrc from /home/orhanc/.bashrc to some other directory? | Change the location of .bashrc | bash;bashrc | Yes. You have three main options:Symlink ~/.bashrc,mv ~/.bashrc ~/blah && ln -s ~/blah/.bashrc ~/.bashrcsource the new file from ~/.bashrc,mv ~/.bashrc ~/blah && cat > ~/.bashrc << 'EOF'. ~/blah/.bashrcEOFor launch bash with --rcfile.mv ~/.bashrc ~/blahbash --rcfile ~/blah/.bashrc |
_webmaster.82421 | I understand archive.org takes its website list to crawl from Alexa, but I don't understand how it decides the snapshot frequencies for each website. We can see some websites are crawled multiple times per day while others are crawled less than once a month. How is the frequency a website will be archive determined by the Wayback Machine? | What determines the frequency the Wayback Machine crawls one's website? | web crawlers;internet archive | null |
_cs.45582 | I'm using K-means for unsupervised learning, using data vectors with an IP address and a language. I need to represent them in an abstract way, so that I can use this algorithm. | While using K-means, how do I represent IP addresses and languages on the coordinate axis? | machine learning | If your data doesn't map in an obvious way onto vectors of continuous real numbers, don't use K-means.To use K-means clustering you need to have a well defined distance between any two points in the space. To do that you need to have a notion of distance for each axis.Typically discrete classifications like language don't have any natural mapping onto real numbers. |
_softwareengineering.130461 | On a uniprocessor, it is apparently optimal to schedule jobs that take less time first assuming non-preemptive scheduling - once a job runs, it must finish. Why? I am confused about how the ordering would change the overall latency. Since a uniprocessor can only take on a single process at a time, wouldn't the latency be the same regardless of order? | Why is it optimal to schedule shorter jobs first on a uniprocessor? | scheduling | Although this algorithm was designed to provide maximum throughput in all the scenarios, this is not correct for all situations. What if the processor has a lot of small processes? It will definitely lead to starvation. The turnaround time of small processes will be low, whereas that of large processes will be large as compared to other scheduling algorithms.Wikipedia says:Since turnaround time is based on waiting time plus processing time, longer processes are significantly affected by this. Overall waiting time is smaller than FIFO, however since no process has to wait for the termination of the longest process.If you schedule larger jobs first, lots of small processes would have to wait for the process to terminate (as this is non-preemptive). And since turnaround time is total time between submission of a process and its completion, this would definitely be low. But in SJF, very few large processes wait for some small processes, so turnaround time of only those large processes would be affected.Check out this link for a comparison of various techniques. |
_reverseengineering.8938 | So im working on an crackme and came across a couple of FPU loads and pops that confused me.Address main 0040169E pops 80 bit value of 00000000_FED63690h from the FPU stack (ST0=4275451536.0000000000) to the CPU stackbut when put on the CPU stack its value is changed to CPU StackLocked Value ASCII Comments0028FB38 |D2000000 0028FB3C |41EFDAC6 AWhy?Here is the code with some comments:main 00401696 PUSH EAX EAX=FED63690main 00401697 FILD QWORD PTR SS:[LOCAL.268] Loads the FED63690 as a 64 bit value so -> 00000000_FED63690main 0040169A LEA ESP,[LOCAL.266] ESP=0028FB20 (loads address of string on stack), ST0=4275451536.0000000000 (which euals above number)main 0040169E FSTP QWORD PTR SS:[LOCAL.260] POPS 80 bit value of ST0 onto program stack as 64 bit LOCAL.260 is address 0028FB38 Stack now looks like: CPU Stack Locked Value ASCII Comments 0028FB38 |D2000000 0028FB3C |41EFDAC6 Amain 004016A4 FLD QWORD PTR SS:[LOCAL.260] Loads value onto FPU Stack so -> ST0=4275451536.0000000000 (Same as before)main 004016AA FSTP QWORD PTR SS:[LOCAL.264] <%i> = -771751936. POPS 80 bit value of ST0 onto program stack as 64 bit LOCAL.260 is address 0028FB28 Stack now looks like: CPU Stack Locked Value ASCII Comments 0028FB28 |D2000000 0028FB2C |41EFDAC6 Amain 004016AE MOV DWORD PTR SS:[LOCAL.265],00401469 Format => %imain 004016B6 LEA EAX,[LOCAL.194] main 004016BC MOV DWORD PTR SS:[LOCAL.266],EAX s => OFFSET LOCAL.194main 004016BF CALL <JMP.&msvcrt.sprintf> Result is: s=-771751936 | Trouble understanding change in number when popped from FPU to CPU Stack | stack variables | 4275451536 is greater than 2^31 (2147483648) but less than 2 ^32 (4294967296)so it is represented as 2^31 + ( 2 ^31 * ((4275451536 - 2 ^31 ) / 2^31)ie 2^31 * 1.990912266075611114501953125 exponent is always written with bias (1023 for 64 bit precision) added to it so 1054 = 0x41e fractional part can be written as 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/64 ..... 1/2 ^n0.984375 < 0.990912266075611114501953125 < 0.9921875(1/2+...+1/64) < ------- < (1/2+....+ 1/128) 111111mantissa is approximated upto 52 bits explicitly and 1 or 0 is added implicitly a c src that shows the conversion of your specific decimal is shown below#include <stdio.h>#include <stdlib.h>#include <string.h>#define BIAS 1023int main(void) { char binform[100] = {0}; unsigned long a = 4275451536; _ultoa_s(a%2,&binform[0],4,10); a = a/2; int i = 1; while (a>2) { a = a/2; _ultoa_s(a%2,&binform[i++],4,10); } char paddedstr[100] = {0}; sprintf_s(paddedstr,100,%s0000000000000000000000,_strrev(binform)); printf(%x-%I64x\n,i+BIAS,_strtoui64(&paddedstr[1],0,2));}on execution the results are>F2H.exe41e-fdac6d2000000 |
_unix.184513 | I am a professor (Mechanical Engineering department) at a college which is making the transition from Windows to Linux. However, we are quite unsure whether all the CAE softwares that we use would be compatible with Linux.The list of 13 softwares that we currently use are listed below : Solid Edge,Uni Graphics,Hyperworks,CATIA,ANSYS,FLUENT,GAMBIT,MATLAB,AutoCAD,ABAQUS,ADAMS,NASTRAN, andSTAAD PRO.Which would be the best choice of OS for my college? Red Hat Enterprise Linux or CentOS? Of the little research that I did, I came to know that some work in RHEL, which is a paid distribution. Another query of mine is whether a software would work in CentOS if it works in RHEL? Also, what about Ubuntu 14.04 LTS? | Compatibilty of the following softwares | centos;rhel;compatibility | null |
_unix.347759 | I find myself having to play around with Solaris. I would usually redirect with 2>/dev/null which works on Solaris in general, but not with these two ways of doing recursive greps on Solaris.# no errors, but doesn't actually redirect permission denieds to /dev/null/usr/sfw/bin/ggrep -rni test / 2>/dev/null# errorsfind / -type f -exec grep test {} + 2>/dev/nullfind: bad option 2find: [-H | -L] path-list predicate-list Can someone shed some light on this? | Redirect errors to /dev/null when greping and finding on Solaris | grep;find;solaris;io redirection | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.