id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_cs.55216
|
According to wikipedia DFA accepts word $w$ by one of two definitions:A word $w$ is accepted by $M$ if $\hat\delta(q_0,w)\in F$.A word $w=w_1w_2\dots w_n$ is accepted by $M$ if $\exists r_0,\dots,r_n\in Q$ such that:$r_0=q_0$$\delta(r_i,w_{i+1})=r_{i+1} \ \forall 0\le i<n$$r_n\in F$Assuming that some word $w$ is accepted by definition 1, how can we show it is accepted by definition 2?Thank you!
|
Equivalence of DFA' definitions
|
automata;finite automata;simulation
| null |
_codereview.160190
|
I have a function that takes the root node as input and needs to return if the tree is a proper BST as per the definition below:The data value of every node in a node's left subtree is less thanthe data value of that node. The data value of every node in a node'sright subtree is greater than the data value of that node It cannot contain duplicate values.Here's my implementation boolean checkBST(Node root) { if(root==null) return false; Queue<Node> q = new LinkedList<>(); Set<Integer> s = new HashSet<>(); q.add(root); while(q.size()>0){ Node t = q.poll(); if(s.contains(t.data)) return false; s.add(t.data); if(t.left!=null) { if(t.data<=t.left.data) return false; q.offer(t.left); } if(t.right!=null){ if(t.data>=t.right.data) return false; q.offer(t.right); } } return true; }Things to discuss:I've pursued a Breadth first approach. Is there a better approach?The above procedure fails for some test inputs (I don't know what the inputs are that breaks it). Trying to find out what they areIssues with the above implementation
|
Check if a tree is a proper BST
|
java;tree;binary search
| null |
_codereview.162062
|
I read 99 Bottles of OOP, and one of the offhand comments was that doing the 99 bottles problem with composition was another route that one could take (the book used inheritance). Here is my attempt. Here are the lyrics needed: Beer SongSome difficulties I had: 1) Implementation of successor was tricky. I could not simply pass in a successor object because then BottleNumber(99) needed to hold BottleNumber(98) which needed to hold... Instead I used successor_number and generated a successor when needed. 2) Factory seemed messy - the arguments for the initialize method stacked up and up. Named arguments only made things longer. Sometimes I had to implement a default_object and other times I could use default named parameters. Should this be standardized throughout? Comments welcomeclass BeerSong def verse(number) bottle_number = BottleNumber.for(number) #{bottle_number} of beer on the wall, #{bottle_number} of beer.\n.capitalize + #{bottle_number.action}, #{bottle_number.successor} of beer on the wall.\n end def verses(starting,ending) starting.downto(ending).map do |number| verse(number) end.join(\n) end def song verses(99,0) endendclass BottleNumber attr_reader :number, :container, :pronoun, :quantity, :action, :successor_number class << self def for(number) return number if number.is_a? BottleNumber case number when 0 BottleNumber.new(number, quantity: 'no more', successor_number: 99, action: 'Go to the store and buy some more') when 1 BottleNumber.new(number, container: 'bottle', pronoun: 'it') else BottleNumber.new(number) end end end def initialize(number, container: 'bottles', pronoun: 'one', quantity: nil, action: nil, successor_number: nil) @number = number @container = container @pronoun = pronoun @quantity = quantity || default_quanity @action = action || default_action @successor_number = successor_number || default_successor_number end def to_s #{quantity} #{container} end def default_successor_number number - 1 end def default_quanity number.to_s end def default_action Take #{pronoun} down and pass it around end def successor BottleNumber.for(successor_number) endend
|
Print lyrics of 99 Bottles of Beer
|
object oriented;ruby
|
Some comments when looking through your code:SuccessorI think that's fine - how else were you going to do it? Metz does exactly the same thing doesn't she? When successor is called a new bottle number - 1 is created - unless of course the bottle number is zero, in which case you start right back at 100.Knowledge of the arguments and their order:Consider this:BottleNumber.new(number, quantity: 'no more', successor_number: 99, action: 'Go to the store and buy some more')I don't like this. Why? Because every time you need to instantiante a bottle you need to KNOW what goes in there and you also need to know the order in which the arguments go in. You could eliminate the need to know the argument order by passing in a hash. That's probably the only bit of criticism i can add.Inheritancefor this particular problem, inheritance seems like a better fit. it just seems a lot cleaner than dealing with the messiness of passing in those parameters.anyways those are just my thoughts and i hope you find them of some use.
|
_webmaster.55806
|
I'm trying to indicate multiple related products on a product page using Microdata (with Schema.org). But the child products are orphaned because they are not contained in the parent div. I tried using itemref but I must be using it incorrectly or it must be the wrong solution.Also, I cannot easily create a wrapper div or use the body element to create the parent. My ideal solution would be one that leaves the page structure as-is, and somehow links the child product divs to the parent. I thought itemref would do that, but it doesn't appear to be working.Here is example HTML.<div id=main-product itemscope itemtype=http://schema.org/Product> <div class=product-name> <h1 itemprop=name>Main Product</h1> </div></div><!-- END main-product div --><!-- START related-products div --><div class=related-products><ol class=products-list id=related-products-list> <li class=item> <div class=product itemprop=isRelatedTo itemscope itemtype=http://schema.org/Product itemref=main-product> <p class=product-name><a itemprop=url href=/some_product1.php><span itemprop=name>Some Product 1</span></a></p> </div> </li> <li class=item> <div class=product itemprop=isRelatedTo itemscope itemtype=http://schema.org/Product itemref=main-product> <p class=product-name><a itemprop=url href=/some_product2.php><span itemprop=name>Some Product 2</span></a></p> </div> </li></ol></div>The above HTML is simplified, but similar in structure to what's on my site and gives similar errors when submitted to validators.E.g. http://webmaster.yandex.com/microtest.xml gives:microdataERROR: unable to determine affiliation of these fields. There are two possible reasons: this fields are incorrectly placed or an orphan itemprop attribute is indicateditemType = orphansisrelatedtoproductitemType = http://schema.org/Producturlhref = /some_product1.phptext = Some Product 1name = Some Product 1isrelatedtoproductitemType = http://schema.org/Producturlhref = /some_product2.phptext = Some Product 2name = Some Product 2productitemType = http://schema.org/Productname = Main ProductThe Google validator does not seem to show any errors, but the child products are not related to the parent product.
|
Link child product to parent product when not contained in child element
|
html5;microdata
| null |
_datascience.15598
|
My question is really simple, how to find the filename associated with a prediction in Keras? That is, if I have a set of 100 test samples named and I get a numpy array which contains the estimated class probabilities, how do I map the filenames to the probabilities?import cv2import osimport glob def load_test(): X_test = [] y_test = [] os.chdir(testing_path) file_list = glob.glob('*.png') for test_image in file_list: img = cv2.imread(test_image,1) X_test.append(img) y_test.append(1) return X_test,y_testif __name__ == '__main__': X_test = np.array(X_test, dtype = np.uint8) X_test = X_test.reshape(X_test.shape[0],3,100,100) X_test = X_test.astype('float32') X_test /= 255
|
How to find the filename associated with a prediction in Keras?
|
python;keras
|
The order of the files that populate file_list, is the same order X_test appears in, by row. So just match the indices to correlate filename with prediction.X_test[0] ~ prediction[0] ~ file_list[0]
|
_unix.5398
|
Another question recommented I use extlinux. It displays the rather unhelpful message Boot error. Why wouldn't it work? How can I debug the problem?Disk layout: on /dev/sda rEFIt is installed. /dev/sda4 is / and there is no separate /boot partition.Method of installation:extlinux /bootextlinux.cfgDEFAULT GentooLABEL Gentoo KERNEL /boot/kernel APPEND -
|
Extlinux boot error
|
macintosh
| null |
_unix.85812
|
How can I record a radio stream in Linux like the screamer in Windows? Does anyone have any idea or suggestion?
|
How I can record stream radio in Linux?
|
audio;streaming
| null |
_unix.147568
|
I have to access a certain set of Linux machines where control is governed by VPN access, and passwords on the individual systems are effectively not kept secure or secret (security through obscurity). Don't tell me this is a bad practice, I didn't set it up, it's a corporate thing, and it's not in my court to change it.I could try to add my public key to /root/.ssh/authorized_keys on every individual machine on the said network, but I think a cleaner solution would be to simply use the default password with ssh.Is there any way to do this with ssh on OS X?
|
Is there a way to pass a Password to ssh automatically?
|
ssh;password;vpn
| null |
_webapps.49855
|
I have a google group, and the discussion is slowly catching up. We use several tags for each post. Is there a way to let users subscribe ONLY to some tags. Either directly through the google group setting, or by letting the email arrive with the tag listed, and then setting up a filter system on the mail program that only keeps unread messages with certain keywords.I could not find ways to subscribe to a single tag, nor ways to add the tags in an email (to filter later).
|
letting users subscribe to messages that have certain tags in a google group
|
google groups
| null |
_softwareengineering.240308
|
Edit:OK, so, people said it is unclear what I am asking. I am asking for feedback on this design. Here is an example user story:As a group admin on the website I want to be notified when a user in my group uploads a file to the group.Easiest solution would be that in the code handling the upload, we just directly create an email message in there and send it. However, this seems like it isn't really the appropriate level of separation of concerns, so instead we are thinking to have a separate worker process which does nothing but send notifications. So, the website in the upload code handles receiving the file, extracting some metadata from it (like filename) and writing this to the database. As soon as it is done handling the file upload it then does two things: Writes the details of the notification to be sent (such as subject, filename, etc...) to a dedicated notification table and also creates a message in a queue which the notification sending worker process monitors. The entire sequence is shown in the diagram below.My questions are: Do you see any drawbacks in this design? Is there a better design? The team wants to use Azure Worker Roles, Queues and Table storage. Is it the right call to use these components or is this design unnecessarily complex? Quality attribute requirements are that it is easy to code, easy to maintain, easy to debug at runtime, auditable (history is available of when notifications were sent, etc...), monitor-able. Any other quality attributes you think we should be designing for?Original:We are creating a cloud application (in Azure) in which there are at least 2 components. The first is the source component (for example a UI / website) in which some action happens or some condition is met that triggers a second component or worker to perform some job. These jobs have details or metadata associated with them which we plan to store in Azure Table Storage. Here is the pattern we are considering:Steps:Condition for job met.Source writes job details to table.Source puts job in queue.Asynchronously:Worker accepts job from queue.Worker Records DateTimeStarted in table.Queue marks job marked as in progress.Worker performs job.Worker updates table with details (including DateTimeCompleted).Worker reports completion to queue.Job deleted from queue.Please comment and let me know if I have this right, or if there is some better pattern. For example sake, consider the work to be sending a notification such as an email whose template fields are filled from the details mentioned in the pattern.
|
Correct pattern for Worker Processes involving Queues & Tables
|
design patterns;cloud computing;azure;cloud
| null |
_unix.122795
|
When editing an authorised_keys file in Nano, I want to wrap long lines so that I can see the end of the lines (i.e tell whose key it is). Essentially I want it to look like the output of cat authorised_keysSo, I hit Esc + L which is the meta key for enabling long line wrapping on my platform and I see the message to say long line wrapping has been enabled but the lines do not wrap as I expect. I'm using Terminal on OSX 10.8.5
|
Long line wrapping in Nano
|
ubuntu;nano
|
To see the word wrapping you are expecting, use Esc+$Note for new coders to nano: Esc+$ does not mean hold down escape while pressing $; instead it means press and release Esc and then press $ (which is of course shift-4)However, be careful if you're editing a configuration file or code or something that is sensitive to newlines and/or indents. I suggest making sure Soft line wrapping is off in those cases.
|
_unix.102542
|
I have been using the following script to organize my photos into Date' Directories:for x in *.JPG; do d=$(date -r $x +%Y-%m-%d) mkdir -p $d mv -- $x $d/doneThis script works great. My photo files follow the same naming convention 'IMG_20131125_090000.JPG' ie date and time photo taken. Is there a way to change the script above so that it categorizes into date directories still but using the date in the file name rather than use the date the file was modified?
|
Create sub-directories and organize files by date from file name
|
shell script;scripting;date
|
Answer fixed to get 2013-11-25 instead of 20131125If your script runs with a bash compatible shell, the easiest solution is to replaced=$(date -r $x +%Y-%m-%d)withd=${x:4:4}-${x:8:2}-${x:10:2}portable solution with expr:d=$(expr substr $x 5 4)-$(expr substr $x 9 2)-$(expr substr $x 11 2)If you need only 20131125 instead of 2013-11-25 as directory name, you can also Solution with sed:d=$(echo $x | sed 's/.*_\([0-9]*\)_.*/\1/')The sed commands replaces the filename with the number between the underscores (=the date).Solution with awk:d=$(echo $x | awk -F _ '{print $2}')Solution with cut:d=$(echo $x | cut -d_ -f 2')
|
_unix.345665
|
Is there any file system which allows reading from an existing network share, but also writing to the mount, but those writes are only temporary?To let you know the background: We have around 4TB data on our live system. If we want to test our staging system, the stage should be able to access the data, but not modify it. Nevertheless the stage needs write permission, but all the changes stage is causing should be written to some temporary space, which will not affect live system.I want to avoid to clone 4TB data all the time.
|
Read only file system, which allows also temporary write to other destination
|
filesystems;mount;storage
| null |
_unix.251208
|
There may be a question out there for this somewhere. But I wasn't able to find it easily. Basically I want to write a bash script on a new box. A script that I've previously used. Example:#!/bin/bash -exhi='hello world!'echo $hiI've always used (for multiline output)cat > script.sh <<EOF#!/bin/bash -exhi='hello world!'echo $hiEOFBut as you may have noticed this has issues with $hi, and other symbols. Is there a good way to do this? Tips Tricks?
|
Writing a bash script on a new box, Escaping Code
|
linux;bash;scripting
|
You should quote the End-Of-File marker, otrherwise the variable expansion (or rather, everything starting with a $, will get the current context.Compare: hi=herecat >file.sh <<EOF#!/bin/shhi=thereecho $hiEOFsh file.sh(outputs here)hi=herecat >file.sh <<\EOF#!/bin/shhi=thereecho $hiEOFsh file.shoutputs therehi=herecat >file.sh <<'EOF'#!/bin/shhi=thereecho $hiEOFsh file.shoutputs there.Alternatively, you can quote the $:hi=herecat >file.sh <<EOF#!/bin/shhi=thereecho \$hiEOFsh file.sh(outputs there)This initially surprising behavior comes in very handy when there is a need to generate slightly different scripts for various purposes.
|
_cs.60840
|
There has been significant literature in solving the (Approximate) Nearest Neighbour Problem in the spherical setting in the $\mathbb{R}^n$ using Angular and Spherical LSH and other lattice sieving techniques. A proper definition of the problem is found in the image below. (The problem definition is borrowed from Faster sieving for shortest lattice vectors using spherical locality-sensitive hashing by Laarhoven and Weger 2015. Here is the IACR page for the paper. )(Refer to Sieving for shortest vectors in lattices using angular locality-sensitive hashingby Laarhoven 2015. The link is in the comments.)I was curious if there is a way to have a similar spherical setting for the approximate NN problem for the finite field $\mathbb{Z}_2^n$. Particularly, I was wondering if there was a sphere definition relevant to $\mathbb{Z}_2^n$ that could be analogical or atleast very similar to the one in Definition 4. The one in definition 4 allows entire lattices to be embedded on the sphere i.e. $P$ is a lattice. The proposed distance measure could either be the $l_2$ norm or the hamming distance. It does not seem that it can be simply translated into finite fields.I apologize if this is a naive question or does not make sense because I am a first time undergraduate researcher who is not very familiar with this forum and the level of questions asked here.
|
Approximate Nearest Neighbour Problem in Spherical Setting
|
optimization;lattices;nearest neighbour
|
There is a reasonable distance metric on $\mathbb{Z}_2^n$ that allows one to define something that can be viewed as the analog of a sphere. In particular, use the Hamming distance. Then given any vector $c \in \mathbb{Z}_2^n$ and any positive integer $k$, the set $\{x \in \mathbb{Z}_2^n : d(x,c) \le k\}$ can be a ball centered at $c$ with radius $k$. You could even call it a Hamming ball.You can also define a version of nearest-neighbor search, using the Hamming distance on $\mathbb{Z}_2^n$ instead of the ordinary Euclidean distance on $\mathbb{R}^n$. Everything carries over. The algorithms/solutions may need to be different, though. For approaches to this problem, you could look at metric trees and locality sensitive hashing.
|
_webapps.20940
|
I've noticed an unusual activity on my Gmail account: Inconnu Vit Nam (fpt.vn:118.71.51.26) 14 nov. (il y a 1 jour)What does it mean exactly?that a successful login has been made with full access to my account; a successful login has been made to the account, but Google has blocked the access before any access were possible; only an attempt, but the credentials have not been validated. ... or something else?
|
Gmail unusual activity, does it mean a successful connection has been made?
|
security;gmail
|
From Gmail Help:Last account activity shows you information about recent activity in your mail. Recent activity includes any time that your mail was accessed using a regular web browser, a POP1 client, a mobile device, etc. We'll list the IP address that accessed your mail, the associated location, as well as the time and date.That means your mail was definitely accessed. Gmail will not list any unsuccessful attempts, therefore you should immediately change your password and follow the security checklist!
|
_reverseengineering.14261
|
A couple of days ago I bought an air conditioner.The system has a wireless module. By analyzing the ports, I could see that port 22 is open.I have obtained the file that is responsible for managing the connection with the outside and internally (the interface).The file is of type BFLT executable - version 4 ram. Here is more detailed information. (extracted from radare)type bFLT (Executable file) class bfltfile backupServer arch armfd 6 bits 32size 0x3d804 machine unknowniorw t true os Linuxblksz 0x0 minopsz 4mode -r-- maxopsz 4block 0x100 pcalign 4format bflt subsys Linuxhavecode true endian littlepic false stripped falsecanary false static truenx false linenum falsecrypto false lsyms falseva false relocs falsebintype bflt binsz 251908This file I have been able to virtualize with qemu-arm.In the BFLT files there is a section containing all the string and using IDA Pro with the bfltldr plugin to relocate the strings. For debugging I have used the architecture arm litte endian genericAnalyzing the application with IDA Pro, I was able to observe that it expects from the outside some commands with a format and some parameters.The parameters I have but the arguments do not as it is complicated to debug without having any kind of information about the name of each function.The operating system used by the application I think is GNU/Linux or a variant.My goal is to analyze the arguments and parameters that are passed via socket to try to find some vulnerability (buffer overflow, ...) and inject a shell to open a backdoor. The problem I have is that I find it costly to debug the application since in IDA Pro are the memory addresses in the functions and I would like to know if there is any change memory addresses, by the names of known functions of the GNU/Linux.
|
Reverse a BFLT file
|
ida;disassembly;arm;qemu;shellcode
|
bFLT format is used in uCLinux systems and its executables use one of two approaches to make system calls:Statically linked libc (uClibc). In this case you should see explicit syscalls (SVC instructions) in the code. Depending on the age of the system the will be using either Old ABI (with syscall number encoded as the operand of the SVC instruction) or the new ABI(EABI) with syscall number in R7. You can look up syscall numbers e.g. here.Libc in a shared library. I have never seen it myself but it seems uCLinux does support shared libraries loaded at fixed addresses. So you may see calls to apparently unmapped addresses where the libc is supposed to be loaded. In this case you may need to disassemble the libc binary as well to label the functions using syscalls and then match against the calls in the binary. In either case I would suggest you installing or building an uCLinux toolchain and compiling a few helloworld binaries with it. The nice thing about it is that the bFLT is produced from an ELF as the final step so you can compare the ELF with all symbols against the bFLT which should give you some clues how to handle your target.
|
_codereview.46107
|
Is there a better way to handle this ClassNotFoundException ?private Class<?> getClass(String value){ Class<?> columnClass = null; try { columnClass = Class.forName(StringUtils.trim(value)); } catch (ClassNotFoundException ex) { if (value.contains(double) || value.contains(Double)) { columnClass = Double.class; } else if (value.contains(int) || value.contains(Int)) { columnClass = Integer.class; } else if (value.contains(bool)) { columnClass = Boolean.class; } else if (value.contains(long) || value.contains(Long)) { columnClass = Long.class; } else { log.error(FAILED. Class object is not supported: + value, ex); } } return columnClass;}
|
Java ClassNotFoundException Handling
|
java;exception handling
|
With a limited set as this, you might as well skip the Class.forName() entirely and just keep the if statements. Exceptions are expensive, if statements not so much and there are only 4 options anyway.Furthermore you could reduce the semi-repeating a little by providing a unified version of the input to compare against (all characters in lower/uppercase).In fact, I would change it to use a simple lookup table.This results in something like this:static Map<String, Class<?>> lookup = new HashMap<>();static { lookup.put(double, Double.class); lookup.put(int, Integer.class); lookup.put(bool, Boolean.class); lookup.put(long, Long.class);}private Class<?> getClass(String value){ for(String key : lookup.keySet()){ if(value.toLowerCase().contains(key.toLowerCase())){ return lookup.get(key); } } return null;}You can remove the intermediate columnClass variable entirely since the try-catch is now gone and there is no additional logic.
|
_unix.93612
|
So there is a network: 192.168.1.0/24. Router is an OpenWrt 12.04 on a WRT160NL. We got a new network printer. But it's www server is reachable to everyone in the network (and thus everyone can print with it..). Q: How can I disable the network access for all the machines in 192.168.1.0/24 - and only let 2 IP's ex.: 192.168.1.10 and .20 to access the printer? - there isn't ANY access control on the network printer...
|
OpenWrt: prevent that an IP address could be reachable in the network, excluding a few hosts
|
openwrt
|
Sorry, you would probably need additional hardware for that.You need to put the network printer in an independent subnet, connected through a firewall. If you had VLAN support on the internal switch, you could put the network printer's port on a separate VLAN. OpenWrt supports VLANs in general, but unfortunately your hardware isn't working correctly at the moment.http://wiki.openwrt.org/toh/linksys/wrt160nl#switch.ports.for.vlansBut if your printer also supports USB, you might use that with the routers USB port. The recommended solution is p910nd. Then you could control access using firewall rules.
|
_codereview.110474
|
One year ago I published an F# solution of the same task and there is an old C# solution. But I think it's a simple task and require a simple solution.What do you think?using System;using System.Collections.Generic;namespace SalesTaxes{ class Program { static void Main(string[] args) { List<ShoppingCartItem> itemList = getItemsList(); decimal salestaxes = 0.00m; decimal totalprice = 0.00m; foreach (ShoppingCartItem item in itemList) { salestaxes += item.Taxes * item.Quantity; totalprice += item.Item.Price * item.Quantity; Console.WriteLine(string.Format({0} {1} : {2}, item.Quantity, item.Item.Name, (item.Item.Price + item.Taxes) * item.Quantity)); } totalprice += salestaxes; Console.WriteLine(Sales Taxes : + salestaxes); Console.WriteLine(Total : + totalprice); Console.ReadLine(); } private static List<ShoppingCartItem> getItemsList() { List<ShoppingCartItem> lstItems = new List<ShoppingCartItem>(); //input 1 lstItems.Add(new ShoppingCartItem { Item = new Product { Name = Book, Price = 12.49m, Type = Product.ProductType.book, IsImport = false }, Quantity = 1 }); lstItems.Add(new ShoppingCartItem { Item = new Product { Name = music CD, Price = 14.99m, Type = Product.ProductType.other, IsImport = false }, Quantity = 1 }); lstItems.Add(new ShoppingCartItem { Item = new Product { Name = chocolate bar, Price = 0.85m, Type = Product.ProductType.food, IsImport = false }, Quantity = 1 }); return lstItems; } } public class Product { public enum ProductType { food = 1, book = 2, medical = 3, other = 4 }; public string Name { get; set; } public decimal Price { get; set; } public ProductType Type { get; set; } public bool IsImport { get; set; } public bool IsExempt { get { return (int)Type < 4; } } } public class ShoppingCartItem { const decimal TaxRate = 0.1m; const decimal ImpTaxRate = 0.05m; public Product Item { get; set; } public int Quantity { get; set; } public decimal Taxes { get { return decimal.Ceiling(Item.Price * ((Item.IsExempt ? 0 : TaxRate) + (Item.IsImport ? ImpTaxRate : 0)) * 20) / 20; } } }}
|
SalesTax problem (C# version)
|
c#;finance
|
A couple of small suggestions.Var:You spend a lot of time redeclaring variable types when they are already well established by your code. For example:decimal totalprice = 0.00m;foreach (ShoppingCartItem item in itemList){...}List<ShoppingCartItem> lstItems = new List<ShoppingCartItem>();I know there can be some debate about whether var is preferred or not, but I can say I work in a shop that currently uses it heavily and it makes refactoring a dream. Just changing the Foreach to:foreach(var item in itemList)would make refactoring much easier later. This way it will figure out the type for you at compile time, meaning itemList can be an ienumerable of anything as would still be valid in that case.Console.WriteLine:There is already a string format overload for Console.Writeline. The following lines are equivalent:Console.WriteLine(string.Format({0} , x));Console.WriteLine({0},x);Collection Construction:You can use simpler syntax to construct your collection in getItemsList() making your entire signature for the function something closer to this: private static IEnumerable<ShoppingCartItem> getItemsList() { return new List<ShoppingCartItem> { new ShoppingCartItem { Item = new Product {Name = Book, Price = 12.49m, Type = Product.ProductType.book, IsImport = false}, Quantity = 1 }, new ShoppingCartItem { Item = new Product{Name = music CD,Price = 14.99m,Type = Product.ProductType.other,IsImport = false}, Quantity = 1 }, new ShoppingCartItem { Item = new Product{Name = chocolate bar,Price = 0.85m,Type = Product.ProductType.food,IsImport = false}, Quantity = 1 } }; }Return Type List:For what you use the return value for, in getItemsList, it doesn't need to be returned as a List. It could be an IList or IEnumerable without any ill effects. It's not a huge deal in your case as it's private, but around where I work we generally try to return collections under there interfaces. I know resharper will flag this as well.Naming:The enumeration ProductTypes values and the getItemsList method do not follow C# standards for naming. It really should be GetItemsList and Food/Book/Medical/Other.IsExemptWhy is it:return (int)Type < 4;instead of:return Type != ProductType.Other;They mean the same thing, but one is a bit more obvious as to it's intentions.Taxes Getter:This is more of a soft suggestion, but this getter is a bit convoluted to read. I had to dig through and add some spacing to figure out what it was doing and even then I misplaced a paren the first time and got the wrong solution. I understand what you are doing with this type of code but it's honestly something that will be more of a headache than a help later as it is not immediately obvious what it is doing unless you dig in. Maybe simplifying out the ternary statements into getters for those values, or methods if you prefer, would be a better solution as it would vastly simplify the amount of parenthesis and make the statement a bit easier on the eyes. Example:public decimal Taxes { get { return decimal.Ceiling( Item.Price *( CalculateTaxRate() + CalculateImportRate()) * 20) / 20; } } private decimal CalculateTaxRate() { return Item.IsExempt ? 0 : TaxRate; } private decimal CalculateImportRate() { return Item.IsImport ? ImpTaxRate : 0; }This seems much easier to read at a glance.WritelinesAlso worth noting that you swap between the string.format method of writing variables out to the string concatenation method in a couple of places:Console.WriteLine(string.Format({0} {1} : {2}, item.Quantity, item.Item.Name, (item.Item.Price + item.Taxes) * item.Quantity));Console.WriteLine(Sales Taxes : + salestaxes);Best to stick with a style when you start. I prefer the string format approach, using the appropriate Console.WriteLine overload, as it hedges away from doing string + string. In this case it's really not more efficient, but it's a bad to get into the habit of string + string, as in non-trivial usages of concatenation it's inefficient. When I find yourself using string + string it's usually a tip off that there is a better way to be doing it (StringBuilder, String.Format, etc). Once again, no actual gain from this in your instance, just a good habit to build upon.Overall:The solution itself looks pretty good, though I'll admit I didn't run it through too much in the way of testing. I would just suggest those small style changes. Hope that helps.
|
_cstheory.16771
|
Fix a constant $0<\alpha<1/2$. The problem is the following. Suppose there are $N$ axis-parallel rectangles on the 2D plane with weights $w_1, w_2,\ldots, w_N$ and with coordinates all in the range $[0,M]$ for some $M$. Let $W=\sum w_i$. Find a simple (i.e. non self-intersecting) curve that partitions them into two sets of rectangles such that each set has total weight at least $\alpha W$ and the total weight of all rectangles cut by the curve is as small as possible, or output that no such curve exists. This is NP-complete, and I'm interested in a good heuristic/approximation algorithms with $O(N+poly(M))$ time (or more exactly $O(N+poly(M)+polylog(W))$ time).A thorough search doesn't give me any reference in literature that studies this problem. Any insight is appreciated!
|
Balanced partitioning of a set of axis-parallel 2D rectangles
|
cg.comp geom;heuristics;convex geometry
| null |
_unix.46312
|
I've installed power saving packages (bumblebee, laptop-mode-tools, and cpufreq) to my laptop with Debian Wheezy. Thanks to that I decrease power usage from 32W to 10W. But now I faced the issue that I can't disable touchpad. I wrote simple script that inverts state of touch-pad:#!/bin/shsynclient TouchpadOff=`synclient | grep TouchpadOff | awk '{print !$3}'`When I launch this script, it inverts state of touch-pad as expected, but in 5 seconds TouchpadOff is rewritten with value 2, and touch-pad becomes active again.I suppose that it's laptop-mode-tools who modifies TouchpadOff variable. I tried to find related settings in laptop-mode-tools, but didn't find anything.Any ideas how to determine who modifies TouchpadOff variable and how to disable such a modification?
|
Power saving enables touchpad
|
linux;power management;laptop;touchpad;synclient
| null |
_unix.372538
|
What does this iptables rule mean?iptables -t raw -I OUTPUT -j CT -p udp -m udp --dport 69 --helper tftp
|
What does this iptable rule mean?
|
linux;iptables
|
This rule seems to be part of a lager set of rules.-t raw -I OUPUT: insert this rule into the beginning of the OUTPUT chain of the table raw-j CT: if the conditions are met jump to target CTnow the conditions-p udp: protocol must be udp-m udp: use the extension udp - needed to be able to filter on udp-ports--dport 69: apply to udp datagrams with destination port 69--helper tftp: for tracking of related datagrams use the expectations for tftpreference: helpers on regit.org
|
_codereview.36759
|
Disclaimer: The code already was graded - so I don't ask for a homework here -just for a code review. :)For a university course my colleagues and I had to implement a list without using any Arrays or any utilities from java collections. Only interfaces were allowed.We received a small feedback complaining that the our class Tuple is publicly visible. As I do this course just for learning I felt the need for more details and a comprehensive feedback. I add our task that you can better understand why we coded it in this way.Our TaskWe had to implement a list with two inheritance generations with the following properties. SList: SList implements java.lang.Iterable and provides a method add with two parameters: the position where it should be inserted and the element which should be added.AList: AList inherits from SList - with the necessary types set through generics it is a subtype of SList. Each AList list element is affiliated witha possible empty list. The type of the affiliated list items is set through an other type parameter. AList provides another add method with three parameters:position andelement like in SList affiliated_list which is affiliated to the added element.DList: With the necessary types set through generics it is a subtype of AList. All elements added to DList should support a dependsOn method. Moreover DList provides a method consistent which returns true if all list elements from DList do not depend on each other. This is evaluated thanks to the dependsOn method.If you speak German, you can take a look on the task directly.SListpackage Aufgabe5;import java.util.Iterator;public class SList<T> implements Iterable<T>{ // A Double Linked List with Iterator and ListElements. protected class ListIterator<T> implements Iterator<T>{ private ListElement<T> currentElement; /** * PRECONDITION * head != null */ protected ListIterator(ListElement<T> head) { this.currentElement = head; } /** * POSTCONDITIONS * return the current element */ public ListElement<T> getCurrentElement(){ return this.currentElement; } /** * POSTCONDITIONS * return the next current element */ public boolean hasNext() { return this.currentElement != null; } /** * PRECONDITION * currentElement != null * POSTCONDITIONS * return all elements consecutively in the given order */ public T next(){ ListElement<T> next = this.currentElement.getNext(); ListElement<T> returnElement = this.currentElement; this.currentElement = next; return returnElement.getValue(); } /** * PRECONDITION * currentElement != null * POSTCONDITION: The element is removed from the linked list. */ public void remove() { ListElement<T> nextElement = this.currentElement.getNext(); ListElement<T> previousElement = this.currentElement.getPrevious(); previousElement.setNext(nextElement); nextElement.setPrevious(previousElement); this.currentElement = nextElement; } /** * PRECONDITION * builder != null * POSTCONDITIONS * return elements as a String */ public String toString(){ ListIterator<T> iterator = new ListIterator<T>(this.currentElement); StringBuilder builder = new StringBuilder(); builder.append([); while(iterator.hasNext()){ builder.append(iterator.next()); builder.append(, ); } builder.append(]); return builder.toString(); } } protected class ListElement<T>{ private T value; private ListElement<T> previous; private ListElement<T> next; private ListElement(){ this(null, null, null); } /** * PRECONDITION * value != null, previous != null, next != null */ protected ListElement(T value, ListElement<T> previous, ListElement<T> next){ this.value = value; this.previous = previous; this.next = next; } /** * POSTCONDITIONS * return next element in the list */ protected ListElement<T> getNext(){ return this.next; } /** * PRECONDITION * next != null */ public void setNext(ListElement<T> elem){ this.next = elem; } /** * POSTCONDITIONS * return previous element */ public ListElement<T> getPrevious(){ return this.previous; } /** * PRECONDITION * previous != null */ public void setPrevious(ListElement<T> elem){ this.previous = elem; } /** * POSTCONDITIONS * return value */ public T getValue(){ return this.value; } /** * POSTCONDITIONS * return the value as a String */ public String toString(){ return this.value.toString(); } } private ListElement<T> head; private ListElement<T> tail; private int listSize; public SList(){ this.listSize = 0; this.head = null; this.tail = null; } public void add(int position, T value){ if (Math.abs(position) > (this.listSize + 1)){ throw new IndexOutOfBoundsException(The provided position is out of bounds: +position); } // hier noch ein paar Exceptions her zum Schutz! if (shouldBeAppend(position)) { append(value, position); } else if (shouldBeLeftAppended(position)) { leftAppend(value, position); }else if (shouldBeInsertedLeft(position)){ leftInsert(value, position); }else if (shouldBeInsertedRight(position)){ rightInsert(value, position); } listSize ++; } private void append(T value, int position){ // first entry in new list if (listSize == 0 && head == null && tail == null){ ListElement<T> element = new ListElement<>(value, null, null); this.head = element; this.tail = element; }else{ ListElement<T> element = new ListElement<>(value, this.tail, null); tail.setNext(element); this.tail = element; } } /** * PRECONDITION * head != null, tail != null, value != null */ private void leftAppend(T value, int position){ ListElement<T> element = new ListElement<>(value, null, this.head); this.head.setPrevious(element); this.head = element; } /** * PRECONDITION * foundElement != null, value != null * POSTCONDITION * An additional element is added to the list. */ private void insert(T value, ListElement<T> foundElement){ ListElement<T> nextElement = foundElement.getNext(); ListElement<T> element = new ListElement<>(value, foundElement, nextElement); foundElement.setNext(element); nextElement.setPrevious(element); } /** * PRECONDITION * head != null, value != null, position > 0 * POSTCONDITION * An additional element is added to the list. */ private void leftInsert(T value, int position){ ListElement<T> foundElement = head; for (int i=1; i < position; i++){ foundElement = foundElement.getNext(); } insert(value, foundElement); } /** * PRECONDITION * tail != null, value != null, position < 0 * POSTCONDITION * An additional element is added to the list. */ private void rightInsert(T value, int position){ ListElement<T> foundElement = tail; for (int i=-1; i > position; i--){ foundElement = foundElement.getPrevious(); } insert(value, foundElement); } private boolean shouldBeAppend(int position){ return (listSize == 0) || (position == -1) || (listSize == position); } private boolean shouldBeLeftAppended(int position){ return (listSize != 0) && (position == 0); } private boolean shouldBeInsertedLeft(int position){ return (position != 0) && (position > 0) && (position != listSize); } private boolean shouldBeInsertedRight(int position){ return (position < 0) && (position != -1) && (Math.abs(position) != listSize); } public int size(){ return this.listSize; } public Iterator<T> iterator(){ ListIterator<T> iterator = new ListIterator<>(this.head); return iterator; } /** * POSTCONDITIONS * return the iterator as a String */ public String toString(){ return this.iterator().toString(); }}AListpackage Aufgabe5;import java.util.Iterator;public class AList<K, V> extends SList<Tuple<K, V>>{ public AList() { super(); } /** * POSTCONDITION * inserts an element with 3 parameters */ public void add(int position, K key, SList<V> elements){ Tuple<K, V> tuple = new Tuple<>(key, elements); super.add(position, tuple); } /** * POSTCONDITION * return another iterator in Iterator */ public Iterator<Tuple<K, V>> iterator(){ return super.iterator(); }}DListimport java.util.Iterator;public class DList<K extends Dependent<? super K>,V > extends AList<K, V> { /** * CLIENT HISTORY CONSTRAINT: list was filled with elements. * POSTCONDITIONS * return true if all elements don't depend on one another (false) */ public boolean consistent() { Iterator<Tuple<K,V>> it= super.iterator(); boolean pos_found = false; boolean independent = true; while (it.hasNext() ) { Tuple<K,V> elem = it.next(); Iterator<Tuple<K,V>> it2 = super.iterator(); pos_found = false; while(it2.hasNext()) { Tuple<K,V> elem2 = it2.next(); if(pos_found) { if(elem.getXCoordinate().dependsOn(elem2.getXCoordinate())) { independent = false; } } if(elem2.equals(elem)) { pos_found = true; } } } return independent; } }Tuplepackage Aufgabe5;import java.util.Iterator;class Tuple<X, Y> implements Iterable<Y>{ private final X xCoordinate; private final SList<Y> yCoordinate; /** * PRECONDITION * xCoordinate != null, yCoordinate != null, */ public Tuple(X xCoordinate, Y yCoordinate){ this.xCoordinate = xCoordinate; this.yCoordinate = new SList<>(); } /** * PRECONDITION * xCoordinate != null, yCoordinate != null, */ public Tuple(X xCoordinate, SList<Y> list){ this.xCoordinate = xCoordinate; this.yCoordinate = list; } /** * POSTCONDITIONS * return xCoordinate */ public X getXCoordinate() { return this.xCoordinate; } public Iterator<Y> iterator(){ return yCoordinate.iterator(); } /** * PRECONDITION * builder != null * POSTCONDITIONS * return key and value as a String */ public String toString(){ StringBuilder builder = new StringBuilder(); builder.append((); builder.append(this.xCoordinate); builder.append( ,); // (key, builder.append(this.yCoordinate); builder.append()); // value) return builder.toString(); }}Interface Dependent necessary for dependsOnpublic interface Dependent <T> { // Compares two items on a certain property // Such a property can be e.g. if elements are integers // or if the elements are characters. // PRECONDITION: x != null public boolean dependsOn(T x);}
|
Implementation of a double linked list with generics and inheritance
|
java;linked list;generics
|
This is great code, and I trust that you can implement the required data structure correctly. Therefore, I won't review it with respect to the assignment.Most things I found are nitpicks (e.g. about proper formatting). There are a couple of suggestions you can consider. And then there is even one little bug.SListA package declaration should create a globally unique name space, e.g. at.ac.tuwien.nutzerkennung.oop13.aufgabe5. All parts should be lowercase.Inconsistent spacing irks me: head) { vs Element(){. Pick one style and enforce it consistently (e.g. by using automated formatters). The Java Coding Conventions seem to suggest a single space between closing paren and opening curly brace.In a similar vein, always keep an empty line before a method declaration. A documentation comment belongs to the following declaration.It is almost never necessary for good readability to have the first line of a method empty.PRECONDITION head != null doesn't help much as a comment. Enforce this precondition, e.g. via assert head != null. But it's good that you have carefully thought about such conditions.Having a comment describe the functionality of a class/method/field is a good idea. However, such a comment usually precedes the declaration, and should use a documentation comment (/**). This criticism applies to the comment // A Double Linked List with Iterator and ListElements..You consequently mention this when referring to instance fields: this.currentElement. I personally like this a lot (coming from languages like Perl), but it isn't exactly common. Such usage is of course OK if it is part of your groups coding convention.The way you have designed your classes, ListElement is actually Iterable as well. At least you use it as such. Encoding this relationship by formally implementing that interface would clean your code up in some parts:SList#iterator() would becomepublic Iterator<T> iterator(){ return this.head.iterator();}and ListIterator#toString() would becomepublic String toString(){ StringBuilder builder = new StringBuilder(); builder.append([); for (T item : this.currentElement) { builder.append(item); builder.append(, ); // FIXME remove trailing comma } builder.append(]); return builder.toString();}If we don't do that, there is an easy way to remove the trailing comma in ListIterator#toString():public String toString(){ ListIterator<T> iterator = new ListIterator<T>(this.currentElement); StringBuilder builder = new StringBuilder(); builder.append([); while(iterator.hasNext()){ builder.append(iterator.next()); if (iterator.hasNext()) { builder.append(, ); } } builder.append(]); return builder.toString();}Notice also how I used empty lines to separate the three distinct tasks initialization enclosing the items in brackets returning.As far as I can see, new ListElement() == new ListElement(null, null, null) has no useful interpretation, and isn't used anywhere. Remove that useless constructor.shouldBeAppend should be shouldBeAppended ;-)It is dubious that all those shouldBeXAppended methods make sense on their own; it would not impact the code negatively if you would put the conditions directly into the SList#add conditional. Having them in their own methods only makes the code more self-documenting, and a bit easier to test (also, it hides cyclomatic complexity). I personally would not have put them into separate methods, so that it is easier to get an overview of the possible paths.if ((listSize == 0) || (position == -1) || (listSize == position)) { append(value, position);}else if ((listSize != 0) && (position == 0)) { leftAppend(value, position);}else if ((position != 0) && (position > 0) && (position != listSize)){ leftInsert(value, position);}else if ((position < 0) && (position != -1) && (Math.abs(position) != listSize)){ rightInsert(value, position);}Can we be sure from this mess that all paths are actually covered, and that we are allowed to omit the else?Some of the tests are unneccessary: if the first branch is not taken, we already know that (listSize != 0) && (position != -1) && (listSize != position). We can remove those tests from the other branches. The test (position != 0) && (position > 0) looks a bit silly, we can simplify that as well. In the final branch, we already know that (position < 0) because the two other cases were handled earlier. The test Math.abs(position) != listSize simplifies to -position != lisSize because of that.// assert Math.abs(position) <= (this.listSize + 1)if ((listSize == 0) || (position == -1) || (listSize == position)) { append(value, position);}else if (position == 0) { leftAppend(value, position);}else if (position > 0) { leftInsert(value, position);}else if (-position != listSize) { rightInsert(value, position);}So, what input doesn't get handled? position == -listSize. Oops!A note on style: Settle for one style to format if/else. In Java it is common to cuddle them onto one line, but in that case put a space in between: } else if (...) {. I prefer to put the else on a new line, because it allows me to put a comment line before each condition.if (listSize == 0 && head == null && tail == null) the class is small enough to keep all invariants in mind, but listSize == 0 and head == null && tail == null imply each other. In general, an assertion to make sure that these two are in sync would be better than to take another branch as if nothing happened.In this special case, you could remove those two large branches as they share most code, and write instead:private void append(T value, int position){ ListElement<T> element = new ListElement<T>(value, this.tail, null); // handle case of empty list: insert at beginning too if (tail == null) { assert listSize == 0; assert head == null; this.head = element; } // append at the end of an existing list else { assert tail.getNext() == null; tail.setNext(element); } this.tail = element;}Is there any specific reason you use both this.tail and a bare tail here?AListI don't quite see why this class needs its own iterator() implementation, considering that it just calls the parent class' method.DListYou have switched to another brace style, putting each brace on its own line for control flow constructs. Settle for a single style, etc.There is no way for independent to become true again once it is set to false. It might be better to remove that variable and return immediately once the value can be determined.pos_found should be named posFound, because this is the naming convention is Java. Actually, booleans should usually have an is prefix. As the variable is only used inside the loop (and reset there to its original value each time), it should be declared inside the loop.Conditionals of the form if (cond1) { if (cond2) { ... } } should be written as if (cond1 && cond2) to avoid unnecessary indentation.When looping over the elements in an Iterable object, it is often better to use a for (Tuple<K, V> elem : this) { ... } loop rather than manually accessing the iterator methods with a while.It is usually better to use a 4-space indent instead of 8-space indent (or even tabs). Most editors can be configured to use a certain indentation style.This class looks like it was written by a C programmer.TupleUsing X and Y for type parameters is confusing. Use something that makes sense in the problem domain, like K, V.What is all this talk about coordinates, considering that yCoordinate isn't even a number, but a list? Such terminology generally needs a comment explaining what it means.return xCoordinate most useless comment ever.Don't put multiple statements onto the same line. You gain nothing, and loose readability.
|
_unix.349691
|
We have a sudoers file in /etc/sudoers.d/ops (on 10 servers). Sometimes we need to add multiple users and Cmnd_Alias to that file. How can we automate this with an ansible playbook?Our sudoers file:User_Alias OPS_USERS = user1,user2,user3Cmnd_Alias OPS_CMD = /sbin/ifconfig, /usr/sbin/dmidecodeOPS_USERS ALL = NOPASSWD:OPS_CMD
|
How to modify sudoers file with ansible?
|
ubuntu;sudo;ansible
|
Personally I would go with a template module (link).I would prepare a template somehow similar to this:User_Alias OPS_USERS = {{ users|join(', ') }}Cmnd_Alias OPS_CMD = {{ commands|join(', ') }}OPS_USERS ALL = NOPASSWD:OPS_CMDAnd in variables I would put something like this:users: - user1 - user2 - user3commands: - /sbin/ifconfig - /usr/sbin/dmidecodeEdit:Maybe a little bit of explanation would be needed.In template I used a filter that joins strings with given separator (', '). You can find more about filters here. Of course strings to concatenate are taken from the lists 'users' or 'command' defined in variables section of your play book.
|
_webapps.102368
|
I am being bombarded with spam from the same address '0x5bfaf04b'.I tried to unsubscribe but that is fake and/or non working so I attempted their support page at the same 0x5bfaf04b. It cam back as a bonus address. I have been receiving 6-10 on average daily. All with different headers and the bottom signature is Gmail.com.This is very frustrating how these scammers have found a way to bypass all security in place and send this kind of garbage. Over and over in disguise as something else.How can this be stopped.
|
How can I stop the spam?
|
email;gmail filters;security
| null |
_cs.70497
|
let T be tree with 10 vertices.what is the sum of degree of all vertices in tree
|
the sum of degree of all vertices in tree with 10 vertices
|
graphs
| null |
_webmaster.10986
|
I have a single app product I want to sell. There are tons of e-commerce website, but these seem to be targeted to companies that sell more than one product.Is there some solution to make an attractive website that emphasises the purchase of a single product?
|
How to sell a single product rather than opening an entire ecommerce website
|
ecommerce
| null |
_webapps.95125
|
PayPal doesn't allow me to pay unless I use its currency conversion. If I select Bill me in the currency listed on the seller's invoice, it gives me an error - You cannot use this credit card for this transaction. Please use another funding source.But if I select Use PayPal's conversion process to complete my transaction using my card's currency, then it shows me no errors and I can proceed to pay.The problem is that the seller's currency is already the same as my credit card's, so if I allow PayPal to use its currency conversion, I'll be hit with a double currency conversion. But if I don't allow it, PayPal won't let me finish the transaction!How do I persuade PayPal to let me NOT use its currency conversion?
|
PayPal gives an error unless I use its currency conversion
|
paypal
| null |
_computerscience.2337
|
The GL Transmission Format comes along with a JSON styled main file which basicly describes the scene and binary files which contain the buffers.I'm currently writing a WebGL library and I need to work alot with the vertex and index buffers. So, my question now is:Would it be possible to store plain text array buffers in the gltf (e.g., as JSON) instead of generating binary blobs always when the buffers are adjusted?
|
Is it possible to store the plain buffer data in gltf files?
|
webgl;data structure;vertex buffer object;gltf
|
It's not possible to store the plain text array buffers in gltf, however, here is the code I use to generate buffers in JavaScript:let vtx = [ 0.0857, 0.0759, 0.0367, 0.9726, 0.9678, 0.0318, 0.9754, 0.9327];let idx = [ 0, 2, 2, 4, 4, 0, 0, 1, 1, 4];let buf = new ArrayBuffer(52);let dat = new DataView(buf, 0, 52);for (var i = 0; i < 20; i += 2) { dat.setUint16(i, idx[i / 2], true);}for (var v = 20; v < 52; v += 4) { dat.setFloat32(v, vtx[(v - 20) / 4], true);}let b64 = btoa(String.fromCharCode(...new Uint8Array(buf)));window.console.log(data:application/octet-stream;base64, + b64);Where buf contains the binary data in a JavaScript ArrayBuffer object and b64 finally a base64 encoded string:data:application/octet-stream;base64,AAACAAIABAAEAAAAAAABAAEABAB7g689dnGbPb1SFj1Q/Hg/vsF3P7hAAj3Qs3k/bcVuPw==
|
_webapps.82621
|
I have a sheet with following values on column A: [ A ][1] Dead line[2] 15 days remaining***[3] Dead[4] 131 days remaining*[5] 80 days remaining**I would like to use conditional formatting on column A so:when only 1 asterisk appears: green cell backgroundwhen only 2 asterisks appear: yellow cell backgroundwhen only 3 asterisks appear: orange cell backgroundwhen column is Dead: red cell backgroundBut when I set to A:A the rule text contains with value * to paint with green background, the whole column is painted with green background, regardless of other rules.I see that the * is interpreted as an wildcard to any string, but I would like to threat each * as one asterisk character only.Someone can help me?PS:The final sheet must use this format of data on column A, with those awful asterisks (no way to change);A1 is a header;It is only a sample. Original sheet has so many lines...
|
Google Sheets: Asterisk character (no wildcard) on conditional formatting
|
conditional formatting;google spreadsheets
|
You can achieve your desired results by putting a tilde, ~ in front of the asterisk as an escape character, if you put the conditional formatting rules in the order listed below.First, create the one for orange when three asterisks occur using text contains and then specifying ~*~*~*. Select custom to pick an orange background. Then create the one for two asterisks using text contains and ~*~* picking yellow for the color. Then for the next rule create one for green with text contains and ~*. Then you can create the one with a red background using text is exactly specifying Dead and picking red for the background. You should then see the following:
|
_unix.52383
|
I would like to automatically run a script after grub-install (using Grub2) if it's possible?Some context. The script will simply run grub-install /dev/sda1, grub-install /dev/sdb1, grub-install /dev/sdc1 as I want all three EFI boot partitions in sync.
|
Is there a way to automatically run a script after grub-install?
|
grub2
| null |
_unix.252615
|
When I use time and date at the end of a crontab line like backup`date+%F_%T`.sql or like backup`date%d%m%y`.sql, my crontab command doesn't work. But when I remove it, it works perfectly.Why doesn't it work when I use time and date like date%d%m%y?
|
Why doesn't `date +%F_%T` work in crontab?
|
cron
|
First of all you need to escape every % and you should also use a little different syntax with date. So e.g. this one will work just fine:`date +\%d\%m\%y`.sql
|
_webapps.74834
|
When I create an appointment at 9:00 in NYC (US Eastern timezone), my guest in London (GMT) has to attend it at 14:00 his time.However, the US and Britain switch to daylight saving time at different moments (2015-03-08 vs 2015-03-29).This means that my guest has to attend the meeting at 13:00 his time for the next 3 weeks. Google handles this seamlessly, maybe even too seamlessly: my guest is not notified that his meeting has shifted by an hour.This is not very good (he may have other appointments not affected by the DST lunacy). Ideally, the user should be notified whenever an appointment's local time changes.What can be done about it?
|
Appointments across different daylight saving time areas are silently modified
|
google calendar
| null |
_webapps.31704
|
In Google Calendar, from the main calendar view, is there a way to have appointments open in a new browser tab when clicked, instead of opening in the same tab (the default behavior)?
|
In Google Calendar, is there a way to open appointments in a new browser tab instead of in the same tab?
|
google calendar
| null |
_cs.2417
|
Wikipedia defines side-channel attacks as:any attack based on information gained from the physical implementation of a cryptosystemUsually in side channel attacks the implementations leak information (e.g., timing attack: the implementation leaks the time it takes to complete a task, etc.)Are tampering-attacks also considered as side-channel attacks?On one hand, tampering-attacks are (usually) attacks on the implementation itself.On the other hand, the attack might be such that information only enters the device, and no information comes out of the device, so there is no side-channel that leaks the information.(example: If we heat some access-control device, until it grants us the access. Or if we perform SQL injection that causes the device to grant the access (but leaks no secret other than that))
|
Are tamper attacks considered side-channel?
|
terminology;cryptography
| null |
_unix.272214
|
I'm trying to write a short script that finds empty lines and then prints the nth line after the empty lines.Forfoo1foo2foo3bar1bar2bar3spam1spam2spam3eggs1eggs2eggs3printing every 2nd line after a blank line would result in:foo2bar2spam2eggs2I tried using sed sed -n -e /^$/ {N; N; x; N; p; x; d} but I cannot get the hold space to be cleared and the result is not what I want.
|
How to print nth line after match / empty lines
|
sed;awk;scripting
| null |
_unix.171834
|
I have copied some files to an SFTP-only server.I want to verify that all the files arrived intact. Since the server is SFTP-only, I cannot run e.g., an MD5sum on the remote host.I have the server mounted via GVFS/SFTP on my local machine.There are many gigabytes of data I wish to verify. However, doing a byte-by-byte diff would be infeasible. Instead, I wish to simply compare file sizes.Since the SSH protocol is encrypted, and therefore resistant to tampering/errors (and I have no enemies powerful enough to tamper with an SSH connection, especially for files as trifling as these,) I can safely assume that every byte that DID make it across made it across intact.However, a truncated file is still a possibility.How can I compare file sizes (in bytes) for a large amount of files?
|
How to compare file sizes in two directories?
|
files;file transfer;verification
| null |
_cs.50072
|
I have found a algorithm to check whether a Hamiltonian Cycle Exists in the graph or not, but not able to compute/analyse it's time complexity.The algorithm is as follows :Label all the vertices with distinct prime numbers.Label all edges with weight equal to 1.Now remove one vertex at a time, while removing a vertex v, if there is edge between u and v & v and w, then add a edge between u and w, with weight = weight(u->v)*weight(v->w)*label(v)If at the end you end up with only one vertex with self edges and if there is a self edge that is equal to the product of all the primes of the removed vertices then there is Hamiltonian Cycle.I have proved the algorithm is correct but unable to find it's time complexity. I think there can be much more optimization in this algorithm also, as we don't need to add those edges to the graph that whose weight divides the weight of some other already present edge.If someone can give some optimization to this algorithm it may turn out to be polynomial, thus proving P = NP.
|
Time Complexity and Optimization for the Algorithm?
|
time complexity;np complete;optimization;p vs np
| null |
_softwareengineering.119430
|
Assume the following situation similar to that of Stack Overflow: I have a system with a front-end that can perform various manipulations on the data (by sending messages to REST back-end):PostingEditing and deletingAdding labels and tagsNow in the first version we created it well modularized but the need as of now for 'evolving' the system similar to Stack Overflow. My question is how best to separate the commonality and how to incorporate the variability with respect to the following:Commonality:The above 'functionalities' and sending/receiving the data from the serverLook and feel (also a variability as explained below)HTTP verbs associated with the above actionsVariability:The RESTful URLs where the requests are sentThe text/style of the UI (the commonality is analogous to Stack Overflow - the functionality of upvotes, posting a question remains the same, but the words, the icons, the look and feel is still different across sites)I think this is entirely a client-side code organization/refactoring issue. I'm heavily using jQuery, javascript and backbone for front-end development. My question is how best should I isolate the same to be able to create multiple such aspects to the tool we are currently working on?
|
How can I refactor client side functionality to create a product line-like generic design?
|
javascript;design;rest;refactoring
| null |
_softwareengineering.140424
|
The result of the following process should be a html form. This form's structure varies from one to user. For example there might be a different number of rows or there may be the need for rowspan and colspan.When the user chooses to see this table an ajax call is made to the server where the structure of the table is decided from the database. Then I have to create the html code for the table structure which will be inserted in the DOM via JavaScript.The following problem comes to my mind: Where should I build the HTML code which will be inserted in the DOM? On the server side or should I send some parameters in the ajax call method and process the structure there? Therefore the main question involves good practice when it comes to decide between Server side processing or client side processing.Thank you!
|
Is it better to build HTML Code string on the server or on the client side?
|
programming practices
|
Server-sidePros: More controllable, easier to debug, less dependent on client's browser Cons: More server load, higher network traffic and latencyClient-sideCons: Depends on decent JS/DOM implementation in the browser.Pros: Performance, performance, performance. Less server load (thus faster server response), much less network traffic, and thanks to previous two much less latency.For example LinkedIn's Engineering Team article Blazing fast node.js: 10 performance tips from LinkedIn Mobile as one of the points talks about that issue.
|
_cstheory.22174
|
If $\mathsf{NP}$ contains a class of superpolynomial time problems, i.e.for some function $t \in n^{\omega(1)}$, $\mathsf{DTIME}(t) \subseteq \mathsf{NP}$,then if follows from the deterministic time hierarchy theorem that $\mathsf{P} \subsetneq \mathsf{NP}$. But are there any other interesting consequences nontrivial (i.e. not a consequence of $\mathsf{P} \subsetneq \mathsf{NP}$)if nondeterminism can speed up deterministic computations?
|
Consequences of nondeterminism speeding up deterministic computation
|
cc.complexity theory;time complexity;nondeterminism
| null |
_unix.289166
|
We are running ubuntu 14.04, which still does not have openjdk8 yet. And I doubt they are going to fix this very soon. We need jdk8 very badly. Is this openjdk-r ppa safe enough?
|
Is the openjdk-r ppa trustworthy enough to install on server?
|
ubuntu;java
|
Installing openjdk-8 from this Launchpad PPA is safe.To install OpenJDK 8 execute the following commands : sudo add-apt-repository ppa:openjdk-r/ppasudo apt updatesudo apt install openjdk-8-jdk
|
_datascience.11069
|
I am taking a class in information retrieval. We learned that the index of a search engine has (possibly among other things):A vocabulary mapping terms to their statistics (frequency, type, ...) andA posting list mapping terms to the documents were they are stored (with or without positions, fields, ...)These are separate data structures. I understand why those information is needed and what for. But I don't understand why we want to keep them separate. Why can't we have one data structure that maps terms to statistics and documents?I am currently thinking it might be because the vocabulary would be much smaller and we could read it from memory. So we could use the statistics to remove certain query terms, which are likely not useful or to try to find misspellings in the query without having to touch the large posting list.Is this correct or is there another reason to keep vocabulary and posting list separate?
|
Why keep vocabulary and posting list separate in a search engine
|
information retrieval;search;indexing
| null |
_cs.65495
|
I will start of with an informal example and give a more formal problem definition later.Say I have a finite set of positive real values: $\{2.3, \pi, 4.382, 0.3\}$. Using normal addition and multiplication, we can construct expressions like $(\pi + 2.3) * 0.3 + 4.382$ and $(0.3 + \pi) * (2.3 + 4.382)$. We put the following constraints on the expressions:Each value in the set must be used exactly once in the expression.We can only use addition, multiplication and brackets in our expression.The goal now is to get as close to a target value, say $9.5$. For example, the expression $2.3 * \pi * 4.382 * 0.3 = 9.49886...$ gets close. How can we find the expression whose evaluation is closest to $9.5$? Or more formally:Given a finite set $V$ of - not necessarily unique - elements, two binary operands $f(x, y)$ and $g(x, y)$ that operate on the elements in $V$ and a target value $t$, find the expression $E$ containing each element of $V$ exactly once, such that the evaluation of $E$ is as close to $t$ as possible. $E$ must consist only of the values in $V$, the given operands and brackets.I understand that for small sets, an exhaustive check that checks all possible expressions is feasible. Using heuristics, quickly finding an approximate answer (with small distance to the target) is probably possible for larger sets too. My questions are; does a more efficient method exist to find exact answers for large sets? Do efficient methods exist specifically for certain operands? What fields of mathematics and computer science touch on this subject?
|
Find expression with minimal distance to target
|
complexity theory;optimization
|
This is a very difficult problem. For an already hard special case, you can look at the subset sum problem. So in general, one direction to look at is NP-hard optimization problems (and ways of coping with hardness).
|
_scicomp.12886
|
Background:I am currently running a large amount parameter variation experiments.They are being run in Python 2.6+, using numpy.These experiments are going to take about 2 weeks to run.Roughly I am varying 3 parameters (independent variables) over a range of values.I am fixing 6 further independent variables (for now)I am reporting on 4 dependent variables.One of the parameters I am varying is being distributed across several processes (and computers).For each of these parameters, I generate a separate csv files with each row containing the values of all the variables (including independent, fixed and dependent).Across all the variation expect to generate about 80,000 rows of dataMost of the time I am only looking at the value of one of the dependent variables, however I keep the others around, as they can explain what is going on when something unexpected happens.In a earlier version of this experiment, varying across only 2 parameters (each though only 2 values)I was copying pasting this csv file into a spreadsheet program and doing a bunch of copy pasting to make a table of just the dependent variable I was interested in.The doing some awkward things in MS-Excel to let me sort by formulas.This was painful enough for the 6 experiment results sets I had.By the time this run is finished I am going to have 2 orders of magnitude more results.Question:I was thinking once done, I could dump all the results from the csv files into a database, and the query out the parts that are interesting.Then take those results and put them into a spreadsheet for analysis.Making graphs, finding scored relative to the control results etcAm I thinking along the right lines? (Is this what people do?)My database foo is fairly rusty these days, even when it was good I was using MS-Access.I was intending on using MS-Access for this as well.
|
Should I use a database to handle large amounts of results?
|
software;data visualization;data analysis
|
I would suggest that a full database may be overkill for your purposes, though it would certainly work.Even $5 \cdot 10^5$ rows should be no more than around 25mb of data.I would strongly recommend doing the analysis/plotting/etc with the same tool that you will use for querying your data. It is my experience that when changing what to analyse only takes changing 1 line of code and waiting 2 seconds, it is much easier to get the most out your data. Copy pasting is also HIGHLY error prone. I have seen several people at the point of desperation because their data did not make sense, only to realise they made a mistake when copying data in their excel sheet.If your are at all familiar with python, I would suggest using pandas or (if you have more data than you can fit in memory) pytables, which will give you all the advantages of a database (including speed). Pandas has a lot of utility functions for plotting and analysing data, and you would have the full scientific python stack as well. Take a look at this ipython notebook for an example of pandas use.I believe similar tools exist for R, as well as commercial software such as Matlab or Stata. HDF5 is a good generic way of storing the data initially, and has good library support in many languages.
|
_softwareengineering.290465
|
Should unit tests be written by the developer who wrote the code or someone else ? And how effective is writing units tests as a method of learning a new system ?
|
Who should write Unit Tests?
|
unit testing;development process;tdd
| null |
_reverseengineering.12178
|
In my vtable i found a method that simply returns ecx.Now im confused as to what this tries to accomplish ? Is this a known useful sequence ?
|
Virtual Method that returns ?
|
ida;c++
|
The C++ compiler of Visual Studio uses ecx as the default register for this pointer, a virtual method which returns ecx then actually returns this or *this. For example, you can test the following code:class A{public: virtual A getmyself() { return *this; } virtual A* getmyselfpointer() { return this; }}The generated assembly code for getmyself (the same for getmyselfpointer) isgetmyself: mov eax, ecx retnThis detail is not true for clang or gcc since they do not use ecx as default register for this.
|
_webmaster.95351
|
I have a small static website which allows customers to purchase a PDF containing some data based from an input from them. The PDF's are a page or two and follow a standard template, and various values change based upon the what the customers are searching for, and I expect them to be unique per customer (i.e 99% chance of having a unique PDF, although majority of the content within the PDF may be similar).Previously I haven't made the PDF's searchable, however I've wanted to start including them and have written some code that dynamically gets all the available PDF's and generates a page where they are listed with a hyperlink to open them using this PHP code embedded in a HTML page :-$directory = ../logs/reports/;$files = glob($directory . *.pdf);foreach($files as $phpfile){ $filename = basename($file); echo '<a href=/includes/getreport.php?file='.urlencode($filename).'>'.basename($file).'</a><br>';}My sitemap is reflecting the new page with weekly change frequency<url> <loc>https://www.myurl.com/reportlist.html</loc> <changefreq>Weekly</changefreq></url> I forgot to update my robots.txt initially for an allow rule as I had a disallow on /includes/ where the PHP file that retrieves the report is located, so I updated it and it now looks like the belowUser-agent: *Disallow: /font/Disallow: /includes/Disallow: /js/Disallow: /wdsl/Allow: /includes/getreport.phpMy Search Console is now showing the following under Index Statusso the links to the PDF's are being crawled, but apparently links are blocked by robots.txt from being crawled. If I check the robots.txt Tester of a URL I get the following I've tried putting the allow statement in the robots.txt at the top originally, and then at the below as per the current setup, and it appears to have been seen by Google after the changes. If run Fetch as Bingbot I get the followingwhich suggest that robots.txt can access the page and retrieve the PDF, and although it looks like there is no visible text, I'm not overally worried as according to https://webmasters.googleblog.com/2011/09/pdfs-in-google-search-results.html these PDF's may be searchable by OCR, and I can cut and paste text from them via a PDF reader.Lastly if I check my search results via site:mysite.com I see a number of links with A description for this result is not available because of this site's robots.txt so it seems to think they aren't searchable.So my question is two-fold, firstly why are these appearing as blocked in Search Console, not sure if waiting longer is the answer as the Index Status seems to be changing and the number of indexed pages is dropping, but the blocked by robots seems to remain the same. Secondly will indexing this sort of content be problematic?
|
Google not indexing site, robots being blocked
|
google search console;robots.txt;pdf
|
It appears you're using query strings on a PHP page to generate the file links. Try adding a wildcard to the end of your ALLOW, as this will form part of the URI.Also, have you checked the URL parameters section to see how Google is treating these variables? You can also explicitly set behaviour, make sure Google understands how to use the query strings when it's indexing.
|
_computergraphics.5258
|
I need a 3D triangular sphere mesh with uniformly sampled vertices, say $V$, with a predefined adjacency. Is there a specific way to achieve that?
|
3D sphere mesh with a predefined number of vertices and a given adjacency matrix of vertices
|
3d;computational geometry;mesh
| null |
_webapps.39822
|
I have a table where each row contains data like this:Team name | First member | Second member | Third member | Team descriptionWould it be possible to transform/break this data so that each row contains only one member? Like this:Team name | First member | Team descriptionTeam name | Second member | Team descriptionTeam name | Third member | Team description
|
Split content of one row into multiple rows?
|
google spreadsheets
| null |
_unix.384622
|
Following statement always returns 1 when I am expecting it to return 0: echo ACI123456777-001-20170701.pdf | grep -e ^ACI([0-9]{9})-([0-9]{3})-([0-9]{8}).pdf$
|
grep pattern matching
|
linux;shell script;grep
|
You observed an exit of code 1, like this:$ echo ACI123456777-001-20170701.pdf | grep -e ^ACI([0-9]{9})-([0-9]{3})-([0-9]{8}).pdf$; echo code=$?code=1To have it work as you expect, you need the -E` option:$ echo ACI123456777-001-20170701.pdf | grep -Ee ^ACI([0-9]{9})-([0-9]{3})-([0-9]{8}).pdf$; echo code=$?ACI123456777-001-20170701.pdfcode=0-E turns on extended regex features.If you really want to use basic regex, which is the default, then you need to add several escapes:$ echo ACI123456777-001-20170701.pdf | grep -e ^ACI\([0-9]\{9\}\)-\([0-9]\{3\}\)-\([0-9]\{8\}\).pdf$; echo code=$?ACI123456777-001-20170701.pdfcode=0The meaning of -eThe grep option -e precedes a regex pattern:$ echo ACI123456777-001-20170701.pdf | grep -e '^ACI'ACI123456777-001-20170701.pdfIf there is only one pattern, then grep doesn't need -e and you can omit it:$ echo ACI123456777-001-20170701.pdf | grep '^ACI'ACI123456777-001-20170701.pdfIf there are two or more patterns, however, -e is needed:$ echo ACI123456777-001-20170701.pdf | grep -e '^ACI' -e 'pdf'ACI123456777-001-20170701.pdf
|
_codereview.105484
|
I completed the following task:You need to create the foundations of an e-commerce engine for a B2C (business-to-consumer) retailer. You need to have a class for a customer called User, a class for items in inventory called Item, and a shopping cart class calledCart. Items go in Carts, and Users can have multiple Carts. Also, multiple items can go into Carts, including more than one of any single item.I am a new Pythoner, and don't have good knowledge of OOP. I feel the code is not good. I welcome recommendations to improve the code.Here's my code:class Item(object): def __init__(self,itemname,itemprice): self.__itemname = itemname self.__itemprice = itemprice def GetItemName(self): return self.__itemname def GetItemPrice(self): return self.__itemprice def ChangeItemPrice(self,newprcie): self.__itemprice = newprcieclass Cart(dict): #cart dict format: {itemname:[price,number]} def ShowCart(self): return self class User(object): def __init__(self, name): self.name = name self.__cartlist = {} self.__cartlist[0] = Cart() def AddCart(self): self.__cartlist[len(self.__cartlist)] = Cart() def GetCart(self, cartindex = 0): return self.__cartlist[cartindex] def BuyItem(self, item, itemnum, cartindex = 0): try: self.__cartlist[cartindex][item.GetItemName()][1] += itemnum except: self.__cartlist[cartindex].update({item.GetItemName():[item.GetItemPrice(),itemnum]}) def BuyCancle(self, itemname, itemnum, cartindex = 0): passif __name__ == '__main__': item1 = Item('apple', 7.8) item2 = Item('pear', 5) user1 = User('John') user1.BuyItem(item1, 5) print(user1 cart0 have: %s % user1.GetCart(0).ShowCart()) user1.BuyItem(item2, 6) print(user1 cart0 have: %s % user1.GetCart(0).ShowCart()) user1.AddCart() user1.BuyItem(item1, 5, 1) print(user1 cart1 have: %s % user1.GetCart(1).ShowCart())
|
Python OOP shopping cart
|
python;beginner;object oriented;e commerce
| null |
_unix.177988
|
I've installed Open Panel, which seems to ship with Pure FTP server. I added a linux user ftpuser, and now I can log in with it. I'd like to specify a directory to which this user starts with when it logs in.How can I achieve this?
|
(Pure FTP) FTP User login directory
|
ftp
|
You can use a program like usermod with its -d option if you have that installed: usermod -d /new/ftpuserhome ftpuserif you don't have that, you can also edit the /etc/passwd file as root and change the 6th field (the one before the last field (: is the field separator).
|
_unix.165324
|
I tried this substitution with GNU sed on OS X (4.2.2 installed through Homebrew). But it doesn't work.printf Hello\x92 World | gsed -r s/[\x92]/'/gThe expected output is:Hello' WorldThe actual output is:Hello<unknown character symbol> WorldI also tried:printf \x92 | gsed -r 's/[\x92]/P/g'But I continue to get an unprintable character that is the byte '\x92'.What am I doing wrong here?
|
Why doesn't this sed substitution for a non-ASCII byte work?
|
sed;character encoding
| null |
_unix.49261
|
On the one hand I have a lot of tar files created with gnu format, and on the other hand I have a tool that only supports pax (aka posix) format. I am looking for an easy way to convert the existing tar files to pax format - without extracting them to the file system and re-create the archives.GNU tar supports both formats. However, I haven't found an easy way to the conversion.How can I convert the existing gnu tar files to pax?[I asked the same question on superuser.com, and a commenter recommended to migrate the question to unix.stackexchange.com.]
|
How to convert tar file from gnu format to pax format
|
tar;conversion
|
You can do this using bsdtar:ire@localhost: bsdtar -cvf pax.tar --format=pax @gnu.tarire@localhost:file gnu.targnu.tar: POSIX tar archive (GNU)ire@localhost:file pax.tarpax.tar: POSIX tar archive@archive is the magic option. From the manpage:@archive (c and r mode only) The specified archive is opened and the entries in it will be appended to the current archive. As a sim- ple example, tar -c -f - newfile @original.tar writes a new archive to standard output containing a file newfile and all of the entries from original.tar. In contrast, tar -c -f - newfile original.tar creates a new archive with only two entries. Similarly, tar -czf - --format pax @- reads an archive from standard input (whose format will be deter- mined automatically) and converts it into a gzip-compressed pax- format archive on stdout. In this way, tar can be used to con- vert archives from one format to another.
|
_softwareengineering.323872
|
I have modeled a problem as a graph that consists of many trees. Some of the nodes in the graph may belong to more than one tree. I am trying to describe a subset of paths in the graph with as few nodes as possible in order to store them efficiently. All paths start from a root and end at a leaf node.Below are a few examples:Suppose the subset of paths chosen all start from the root node R. Then, I can describe all these paths with all paths that start from R. This uniquely determines the paths that were selected. So I just need to store R and a flag that specifies that this node is a root.A similar scenario, but for the case where all the paths end at a specific leaf node L. They can be described with all paths that end at L. So I just need to store L and a flag that specifies that this node is a leaf.A similar scenario, but for the case where all the paths pass through a specific intermediate node I. They can be described with all paths that pass through I. So I just need to store I and a flag that specifies that this node is an intermediate node.The problem could get more complicated if the paths need to be described with more than just a root/leaf/intermediate node. For example, I may need to specify many roots, leaves, and intermediate nodes. However, I want the description to contain as few nodes as possible.Is there any known algorithm/heuristic that I can apply to my problem?Thanks a lot.
|
How to describe a set of paths in a graph with as few nodes as possible?
|
graph;trees
| null |
_unix.64753
|
After upgrading to Fedora 18, I am seeing the following critical messages on /var/log/messages whenever I log on to the computer:CRITICAL: gsm_manager_set_phase: assertion \`GSM_IS_MANAGER<br>Gtk-CRITICAL: gtk_main_quit: assertion `main_loops != NULL' failedBased on my limited knowledge, critical messages and above can affect the usage of my computer if I don't deal with these urgently. Not that they are affecting the current usage of my computer, but I would like to find out more about them (seems to deal with mobile technology and GIMP toolkit?) and how to turn them off if I do not need these services.
|
Critical messages from gsm and gtk
|
fedora;logs;gtk;gsm
| null |
_unix.172017
|
This is my scriptif [[ ! $url == *.txt ]]thenexitfiI have also tried:if [[ ! $url == *.txt ]]thenexitfiand:if [[ $url !== *.txt ]]thenexitfiBut even though $url does contain *.txt it still exits?
|
If variable does not contain not working
|
bash;test
| null |
_unix.26138
|
I have a unix script which creates a temporary log file, say tempfl.log.When this file is created it has permission rw-r--r--.There is a linechmod 0440 /etc/sudoers tempfl.log 2>&1But when the script is done the permission changes to r--r--r-- but it should be rw-r--r--. If I change the line to chmod 0644 /etc/sudoers tempfl.logthe permissions are right for tempfl.log but it throws errors sayingsudo: /usr/local/etc/sudoers is mode 0644, should be 0440I do not understand what sudoers is doing and what is wrong.
|
understanding sudoers
|
shell
|
Your script is changing the permission of 2 files, /etc/sudoers and tempfl.log. Split the command in two lines and you should be fine.
|
_softwareengineering.289070
|
I'm writing AI for the game and encountered this article that helped me out. I'm not sure how the probability function is computed. Does it rely on some advanced math I'm not understanding or for each move program generates randomly lots of possible set ups and then computes chance by counting times ship is encountered on the given field?
|
How probability function is computed for the game Battleships?
|
artificial intelligence
|
You enumerate every possible legal position that the largest (surviving) ship can be in. Call that N. Then for each cell, you count up how many of those positions include that cell. Call that c. Then your probability is c/N . You can deliberately targeting the largest ship as the probability map is more concentrated for that one, and therefore most likely to give a successful hint, although the authors continue to do the same for other ship sizes.Whether this is a good measure is debatable - it assumes all remaining positions are equally likely, which in turn assumes your opponent scatters his ships at random. I suspect humans will tend to follow patterns they believe makes life difficult for the opponent, eg. not having touching ships (so that hitting one won't lead you into hitting another while in TARGET mode).
|
_datascience.19731
|
I am using artificial neural networks to classify normal/attack network traffic. While having a large data set to train my model, i want to avoid over-fitting and reduce training time. So how can i generate a representative sample based on my data (which contains both malicious and benign records) ? Is there a machine learning algorithm for this purpose ? Tools like weka, orange or python ?
|
how can I generate a representative sample from a large data set?
|
dataset;sampling
| null |
_vi.3869
|
I have a file that contains words that I want to save, along with other junk that I do not need. I just want to delete everything except the words that contain a certain pattern. Take email addresses for example:foo foo foo foo foo [email protected] foo [email protected] some magic and save everything from @ to the previous and next [email protected] [email protected] would be useful in so many applications (especially email addresses).
|
Delete all of a file except for certain words that contain certain letters
|
command line;search;regular expression
|
Easy way - grepThe easiest technique is to use :%!grep -o {pat}. The -o/--only-matching make grep only display the matches.:%!grep -o 'foo\w*bar'Note: that grep's regex's are a different variant from PCRE and Vim's.Pure Vim method with plugin - still easyFor a pure native vim solution I suggest you look at ExtractMatches or Yankitute plugins.(Ab)Using :s for fun and profitYou want to roll your extract matches command with :s with a sub-replace-expression (\=) and a list.let lst = []:%s/pattern/\=add(lst, submatch(0))[-1]/g:%d:pu=lst:1dThe basic idea is to add each match to the list, lst, using a sub-replace-expression for the :s command. We can use some in-place array trickery to make sure the text doesn't change by always returning the last element of the array (what we just added).This :s trick is often done in the form::let lst = []:%s//\=add(lst, submatch(0))[-1]/g:call setreg('', join(lst, \n), 'l')This will capture the current matches (uses last used pattern) into the default register. If you have Vim 7.4 then the :s can be simplified further: :%s//\=add(lst, submatch(0))/gnMore information:h :range!:h :s:h sub-replace-expression:h List:h add():h submatch():h :d:h :pu:h @=
|
_codereview.4814
|
I am trying to create a function similar to Excel's EOMONTH function in C#. I have written the following, however, I am not entirely sure if the it achieves the equivalent functionality. Is my equivalent of Excel's Eomonth function correct and are my tests sufficient?public static DateTime EOMonth(this DateTime dateTime, int months = 0){ DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1); return firstDayOfTheMonth.AddMonths(1 + months).AddDays(-1);}Tests[Test]public void EOMonth_For5jan2011WithNoAddedMonths_ReturnsLastDayOfJan() { var expectedDate = DateTime.Parse(31-Jan-2011); var currentDate = DateTime.Parse(5-Jan-2011); var result = currentDate.EOMonth(); Assert.That(result, Is.EqualTo(expectedDate));}[Test]public void EOMonth_For5jan2011With_1_AddedMonths_ReturnsLastDayOfFeb2011(){ var expectedDate = DateTime.Parse(28-Feb-2011); var currentDate = DateTime.Parse(5-Jan-2011); var result = currentDate.EOMonth(1); Assert.That(result, Is.EqualTo(expectedDate));}[Test]public void EOMonth_For5jan2011WithNegative_1_AddedMonths_ReturnsLastDayOfFeb(){ var expectedDate = DateTime.Parse(31-Dec-2010); var currentDate = DateTime.Parse(5-Jan-2011); var result = currentDate.EOMonth(-1); Assert.That(result, Is.EqualTo(expectedDate));} [Test] public void EOMonth_For28Feb2007_12_AddedMonths_ReturnsLastDayOfFeb2008() { var expectedDate = DateTime.Parse(29-Feb-2008); var currentDate = DateTime.Parse(28-Feb-2007); var result = currentDate.EOMonth(12); Assert.That(result, Is.EqualTo(expectedDate)); }
|
Is my equivalent of Excel's EOMONTH function correct?
|
c#;unit testing;datetime
| null |
_codereview.163438
|
Problem statementConsider an n-element sequence of integers, A = {a0, a0, ..., an-1}. We want to perform \$n\$ operations on \$A\$, where each operation is defined by the following sequence of steps:Remove any integer, ai, from \$A\$ and set it aside. Calculate scorek = runningSum mod ai, where 1 ≤ k ≤ n and runningSum is the sum of all the numbers removed from A during the previous k - 1 operations.Update runningSum such that runningSum = runningSum + ai, where ai is the integer that was removed from A during step 1 above.Introduction of AlgorithmThe max score is the first medium level algorithm on Hackerrank Rookie 3 contest in May 5, 2017. The success rate is 14.10%, and I only scored 3.5 out of 35 points in the contest. In the contest, I did some work on recursive algorithm, but failed to implement the correct memoization, and did not know that bit mask is the solution to solve timeout issue. After the contest I was busy to learn and teach myself. I thought that if I am a good tester, very patient to go over a few simple test cases first, I must have solved the problem. So I like to try the idea on the algorithm after the contest. Two unit test cases are chosen, one is the array {\$1, 2\$}, and the other is {\$1,2,1\$}. Test case {1, 2, 1}C# code only passed first 5 test cases, timeout last 5 test cases. Source code can be looked up from the link. The solution is implemented with the correct memoization matching the recursive tree, but timeout since too many string concatenation. Suppose that the array has three numbers, int[] numbers = new int[]{1, 2, 1}.Calculated variable as Dictionary has the following:[0 1, 0][0 2, 0][0, 1][1 2, 0][1, 0][2, 1][,1]The key is encoded using the function: public static string EncodeKey(HashSet<int> numbers) { int[] sorted = numbers.ToArray(); Array.Sort(sorted); return string.Join( , sorted); }Debug the code, and check how many times the dictionary is looked up. 3 times.key = 0 1, 0 2, 1 2.Draw a recursion tree for this simple test case. Here is the graph:Apply bit mask technique In order to solve time out issue, I had to use bit mask instead of using encoded key by using the above function EncodeKey with the argument HashSet numbers, apply bit mask techniques learned through top coder article called A Bit of Fun: Fun with Bits. The code is much easy to follow after I did draw recursive tree on the test case, and bit mask set operation is also easily to look up through the top coder article. Here is C# code with those two test cases. C# code passes all test cases on Hackerrank. Please help me to be a good tester, a smart problem solver to work on basics first. #if DEBUGusing Microsoft.VisualStudio.TestTools.UnitTesting;#endifusing System;using System.Collections.Generic;using System.Linq; using System.Text;using System.Threading.Tasks;namespace MaxScore_usingBitArray{ class MaxScore_usingBitMask { /// <summary> /// source code reference is here: /// https://www.hackerrank.com/contests/rookierank-3/challenges/max-score/forum/comments/299005 /// /// </summary> /// <param name=args></param> static void Main(string[] args) { ProcessInput(); //RunTestcase(); } public static void ProcessInput() { int n = Convert.ToInt32(Console.ReadLine()); var data = Console.ReadLine().Split(' '); long[] numbers = Array.ConvertAll(data, Int64.Parse); long maxScore = GetMaximumScore(numbers); Console.WriteLine(maxScore); } /// <summary> /// How to calculate score? /// Please read the problem statement. /// For test case int[]{1,2}, if first number array 1 is selected first, score 0 % 1 = 0. /// Sum will be 1, and then number 2 will be scored as 1 % 2 = 1. Total score is 0 + 1 = 1. /// There are 2 options to enumerate 2 numbers, maximum score is to choose maximum one of /// those two options. /// </summary> /// <param name=array></param> /// <returns></returns> public static long GetMaximumScore(long[] array) { return getMaxScore(array, 0, array.Sum()); } public static Dictionary<int, long> memo = new Dictionary<int, long>(); /// <summary> /// Bit mask technique to solve timeout issue - 3 seconds time limit. /// use the following article on topcoder for reference: /// https://www.topcoder.com/community/data-science/data-science-tutorials/a-bit-of-fun-fun-with-bits/ /// The following function uses an integer to represent a set, with a 1 bit representing /// a member that is present and a 0 bit one that is absent. /// The following set operations are used in the function: /// Set Union A | B /// Clear bit /// A &= ~(1 << bit) /// Test bit (A & 1 << bit) != 0 /// </summary> /// <param name=numbers></param> /// <param name=bitmask></param> /// <param name=sum></param> /// <returns></returns> private static long getMaxScore(long[] numbers, int bitmask, long sum) { if (memo.ContainsKey(bitmask)) { return memo[bitmask]; } var maximumScore = 0L; for (var i = 0; i < numbers.Length; i++) { var bitToCheck = 1 << i; // set ith bit if ((bitmask & bitToCheck) != 0) // test bit { continue; } bitmask |= bitToCheck; // set union var current = numbers[i]; var score = ((sum - current) % current) + getMaxScore(numbers, bitmask, sum - current); bitmask &= ~bitToCheck; // backtracking, clear the bit - ith bit maximumScore = Math.Max(score, maximumScore); } memo[bitmask] = maximumScore; return maximumScore; } }#if DEBUG [TestClass] public class Test { [TestMethod] public void Test1() { var array = new long[] { 1, 2}; MaxScore_usingBitMask.memo.Clear(); long maxScore = MaxScore_usingBitMask.GetMaximumScore(array); System.Diagnostics.Debug.Assert(maxScore == 1); } [TestMethod] public void Test2() { var array = new long[] { 1, 2, 1 }; MaxScore_usingBitMask.memo.Clear(); long maxScore = MaxScore_usingBitMask.GetMaximumScore(array); System.Diagnostics.Debug.Assert(maxScore == 1); } }#endif}
|
Hackerrank: Max Score
|
c#;algorithm;programming challenge;bitwise;dynamic programming
| null |
_cs.10096
|
I currently have a system that has {f(a) = b, f(f(x)) = x} (part of an exam question - look at page 5 - exercise 1).To start off with proving non-confluency, I am thinking along these lines:f(f(x)) and f(a) can be unified by using {a -> f(x)}. Then we can rewrite:f(f(x)) = x [eq.1]f(f(x)) = b [eq.2]The above two cannot be reduced any further, and do not have any common ancestor or successor. Therefore the system is not confluent.To make this confluent, we can add a third equation to the system:x = bThis way, the equation will both be confluent and terminate. Another alternative would be:f(x) = bIs there anything I have missed? Or is this pretty much the gist of it?
|
Proving non-confluency and adding an equation to make it confluent and terminating
|
logic;proof techniques;semantics;term rewriting
|
I do not think $f(f(x))$ and $f(a)$ can be unified. You can not map constant $a$ to the term $f(x)$.My example would be $f(f(a)) = f(b)$ while otherwise $f(f(a)) = a$.It seems the equation $x=b$ maps all terms to $b$. That is too much. I would add $f(b) = a$. This leaves two classes of terms, those equivalent to $a = f(b) = f(f(a)) = \dots$ and those equivalent to $b = f(a) = f(f(b)) = \dots$Here, $a=a$ and $b=b$ and never the twain shall meet ...
|
_webapps.39414
|
I've clicked to join the beta for Facebook Graph Search, but I still cannot access the feature.When will it be rolled out to the public? Is there any way to circumvent the beta wall and gain access now?
|
When will Facebook Graph Search be available for me?
|
facebook;social graph;facebook graph search
|
From the press release:The roll out is going to be slow so we can see how people use Graph Search and make improvements.andHow are you rolling this out? Graph Search is in a limited preview, or beta. That means Graph Search will only be available to a very small number of people who use Facebook in US English.How can I get Facebook Graph Search? You can sign up for the waitlist at www.facebook.com/graphsearchAs the button you clicked says, you've joined a waiting list for the beta. Facebook will be very slow and cautious rolling this out, the world is watching.
|
_unix.174157
|
I'm having a little trouble getting parted 3.2 to accept a partitioning scheme that was valid in parted 2.3 (tested on Debian with jessie vs. wheezy).parted 3.2 will not accept a partition that goes all the way to the end of a volume (marker 1024MiB on a volume with size 1024MiB), instead it errors out with:Error: The location 1024MiB is outside of the device /dev/loop0.Here is a little script to reproduce (also happens when using GPT):#!/bin/bash -xtruncate disk.raw --size=1024Mdevice_path=$(losetup -f --show disk.raw)parted --script --align none $device_path -- mklabel msdosparted --script --align none $device_path -- unit mib print freeparted --script --align none $device_path -- mkpart primary 0MiB 1024MiBlosetup -d $device_pathrm disk.rawOutput with parted 2.3+ truncate disk.raw --size=1024M++ losetup -f --show disk.raw+ device_path=/dev/loop0+ parted --script --align none /dev/loop0 -- mklabel msdos+ parted --script --align none /dev/loop0 -- unit mib print freeModel: (file)Disk /dev/loop0: 1024MiBSector size (logical/physical): 512B/512BPartition Table: msdosNumber Start End Size Type File system Flags 0.02MiB 1024MiB 1024MiB Free Space+ parted --script --align none /dev/loop0 -- mkpart primary 0MiB 1024MiB+ losetup -d /dev/loop0+ rm disk.rawOutput with parted 3.2+ truncate disk.raw --size=1024M++ losetup -f --show disk.raw+ device_path=/dev/loop0+ parted --script --align none /dev/loop0 -- mklabel msdos+ parted --script --align none /dev/loop0 -- unit mib print freeModel: Loopback device (loopback)Disk /dev/loop0: 1024MiBSector size (logical/physical): 512B/512BPartition Table: msdosDisk Flags: Number Start End Size Type File system Flags 0.03MiB 1024MiB 1024MiB Free Space+ parted --script --align none /dev/loop0 -- mkpart primary 0MiB 1024MiBError: The location 1024MiB is outside of the device /dev/loop0.+ losetup -d /dev/loop0+ rm disk.rawAs you can see 3.2 differs slightly in where the partition starts, but that shouldn't make a difference since mkpart only accepts [start] [end] and not [start] [size].There are of course workarounds for this, like making the last partition smaller or making the volume larger, but I would like to get to the bottom of this and understand why this happens.
|
parted 3.2 says 1024MiB is outside of the device (of size 1024MiB)
|
debian;parted
| null |
_cs.70880
|
I am currently writing a program where a lot of adding 0 to numbers and multiplying by 1 and 0 occurs and it got me to wondering if the CPU 'shortcuts' (drops), these operations. I'm a CS student and this hasn't been brought up ever.Can a CPU do this? What are the trade-offs in designing a CPU that detects +1, *1 and *0 and executes them faster?
|
Can CPU's 'shortcut' adding 0, multiplying by 1, and multiplying by 0?
|
arithmetic;cpu
|
Yes, there are processors which detect some kind of do-nothing operations, handle them specially so that they take less time than what they would take if they were handled navely. In some cases, there are even recommended instructions to use for NOP (NOP are sometimes useful to align the code with a memory boundary, having NOP of various lengths available help the relieve the decoding part), the wikipedia page for NOP has a list which gives the normal meaning for some of them.But what you think as a do-nothing operation may not be one if you take into account things like resetting flags or the side effects of memory accesses -- and a processor should behave correctly in such matter;I'd not rely on this as an optimization; more as an encoding trick or as a way to reduce the op-code pressure; they are working when the operands are statically known to have no effect and in such cases, the code writer -- human or compiler -- should avoid the operation if possible;detecting dynamically that the value has no effect is probably more costly than what would be gained by doing so. That said, some relatively simple processors have operations which take a time which depend on the arguments (for arithmetic operations, don't think I've seen this for something else than integer multiplication and division, or for floating point operations)
|
_softwareengineering.233987
|
Im doing a thought experiment about making a product on top of Linux. Im wondering: If you make a custom window manager (akin to KDE, for example) on top of X and you release it, do you have to release it under the GPL (Linux) or MIT (X.org)? Or can you keep it closed source?
|
Is it legal to distribute a closed source X Window Manager?
|
open source;linux
|
X-Windows is licensed under the MIT License, which is a permissive license. Its only requirement appears to be that you include a copy of the MIT license, and do not restrict others from using the X-Windows software in any way they see fit. The MIT License doesn't require you to make your own software open-source, nor does it prevent you from closing the X-Windows source in the context of your Window manager.
|
_softwareengineering.271249
|
What is the best practice for handling exceptions thrown from event handlers/listeners in a event loop? For example:class EventLoop{ public: void start(); //create a thread which calls run(); void run() { while(true) { listener.waitEvent(); //blocks until an event occured try { listener.processEvent(); //calls given handler } catch(const Exception& excp) { //The exception is thrown from another class //What shall I do? } } } //other code..}//Sample event loop usage:EventLoop el;SampleListener sampleListener;el.setListener(sampleListener);el.start();//other work..In this example, when processEvent() throws an exception, the event loop thread should be able to continue to run. Also, the error should be handled. One possible solution may be add an errorOccured() method to listener. In catch block the method could be invoked.But it increases complexity of the program seriously.Your suggestions?Thanks..
|
How shall I handle event loop exceptions?
|
c++;multithreading;exceptions
| null |
_webapps.17238
|
Is it possible to insert a datepicker in every cell of a column in Google Spreadsheet so that anyone can click (with a single click) on that cell and get a datepicker calendar to select a date?
|
Adding a datepicker in Google Spreadsheet
|
google spreadsheets
|
Right-click the selection you want to have the date picker show up for (i.e. single cell, entire row, entire column) and then open data validation. Set Criteria: Date is a valid date and click Save. Now just double-click the cell!
|
_codereview.93814
|
The code bellow was refactored for performance improvements for another user on this site.Functionality, high level:Sheet1 - CodeName aIndex: used as the main reference to the structure of the data being processed in 2 other sheets: mapping column headers for incoming data in sheet2, to column headers to be processed for the final result on Sheet3Sheet2 - CodeName bImport: this where external (raw) data is imported before processing. Importing of data is not part of this processSheet3 - CodeName cFinal: out of a set of about 50 incoming columns, Sheet1 will define a subset of 20 to 30 columns to be processed for the final resultThe code is fully functional, without issues, and decent performance (50,000 rows and 44 columns processed in 4 to 5 seconds); it contains more comments than usual for learning purposes, explaining some basic steps, or things that may not be obvious or clear to an inexperienced person.Notes:This is not a request that requires understanding of the functionality, or finding inefficiencies (unless there are obvious parts that can be optimized).It's about self improvement relative to coding practices: I am open to any criticism no matter how harsh, for any mistakes I may have made - I'll easily swallow my pride, as long as I can improve any bad habits I may have picked up along the way.When I posted the question intended to make it as relevant to this site as possible: Does this code make my ass look fat?I realize that members of this community are volunteers (like me), and provide feedback out of passion about the subject, so I tried to analyse the question objectively, as a reviewer:The code is way too long to make me feel it's worth the effort, and this is the reason I didn't bring its functionality into the mix: there is less effort required for analyzing it at a high level (coding style), and not intricacies of functionalityThere is nothing I can do to make it shorter: I was curious about its structure: did I modularize it enough, or maybe too muchI wouldn't want to get involved in a long review by attempting to understand its logic and reasons of doing what it does, but just quick feedback about anything obviously bad from a readability and maintainability perspective.That said, I will provide relevant details about functionality for each part as a contexts for the algorithmThe first Sub controls the start and end of the entire process (after an imported file): turns off all events and calculations in Excel that can slow down execution, starts a timer, starts the main process, captures the total duration, and turns all Excel features back on:.Option ExplicitPublic Sub projectionTemplateFormat() Dim t1 As Double, t2 As Double fastWB True 'turn off all Excel features related to GUI and calculation updates t1 = Timer 'start performance timer mainProcess t2 = Timer 'process is completed fastWB False 'turn Excel features back on 'MsgBox Duration: & t2 - t1 & seconds 'optional measurement outputEnd SubThe next Sub is where the main processing is done, and makes calls to smaller helper functions:Sets up all references needed during processing: the 3 workbooks, and a set of local variablesDetermines the columns and size of imported data (Sheet2)Determines if there is any previous data on the result sheet (Sheet3) for cleanupIt doesn't remove the headers: these are the column to be migrated from the imported dataOverwrites the headers in Imported Sheet with a standard set of headers defined on Sheet1The headers on Sheet1 can be adjusted by the user (added, removed, renamed) relative to the expected headers in the imported dataThey are also aligned with the headers on Sheet3 (the final result)Re-formats the imported data with specific text, number, and date formatsIf there is at least 1 row of imported data on Sheet2, it starts the main processThe following steps are the most CPU intensive task:Start looping over each column on Sheet3 (columns of the final result)Find the first column to be migrated (based on the header name from Sheet3)If found, set a reference to the entire column with data (50,000 rows or more)Set a reference on Sheet3, to an area of the same size as the column of imported dataCopy the data from Sheet2 to Sheet3Move on the the next column on Sheet3 an repeat the process until all predefined columns on Sheet3 are populatedOverwrite some imported values on Sheet3 with hard-coded data from Sheet1Reformat the dates on 2 specific columns on Sheet3 to YYYY requirementReformat other specific columns on Sheet3Convert all data on Sheet3 to UPPER CASEApply cell and font formatting to all data on Sheet3Zoom all sheets to 85%Private Sub mainProcess() Const SPACE_DELIM As String = Dim wsIndex As Worksheet Dim wsImport As Worksheet 'Raw data Dim wsFinal As Worksheet 'Processed data Dim importHeaderRng As Range Dim importColRng As Range Dim importHeaderFound As Variant Dim importLastRow As Long Dim finalHeaderRng As Range Dim finalColRng As Range Dim finalHeaderRow As Variant Dim finalHeaderFound As Variant Dim indexHeaderCol As Range Dim header As Variant 'Each item in the FOR loop Dim msg As String Set wsIndex = aIndex 'This is the Code Name; top-left pane: aIndex (Index) Set wsImport = bImport 'Direct reference to Code Name: bImport.Range(A1) Set wsFinal = cFinal 'Reference using Sheets collection: ThisWorkbook.Worksheets(Final) With wsImport.UsedRange Set importHeaderRng = .Rows(1) 'Import - Headers importLastRow = getMaxCell(wsImport.UsedRange).Row 'Import - Total Rows End With With wsFinal.UsedRange finalHeaderRow = .Rows(1) 'Final - Headers (as Array) Set finalHeaderRng = .Rows(1) 'Final - Headers (as Range) End With With wsIndex.UsedRange 'Transpose col 3 from Index (without the header), as column names in Import Set indexHeaderCol = .Columns(3).Offset(1, 0).Resize(.Rows.Count - 1, 1) wsImport.Range(wsImport.Cells(1, 1), wsImport.Cells(1, .Rows.Count - 1)).Value2 = Application.Transpose(indexHeaderCol) End With applyColumnFormats bImport 'Apply date and number format to Import sheet If Len(bImport.Cells(2, 1).Value2) > 0 Then 'if Import sheet is not empty (excluding header row) With Application For Each header In finalHeaderRow 'Loop through all headers in Final If Len(Trim(header)) > 0 Then 'If the Final header is not empty importHeaderFound = .Match(header, importHeaderRng, 0) 'Find header in Import sheet If IsError(importHeaderFound) Then msg = msg & vbLf & header & SPACE_DELIM & wsImport.Name 'Import doesn't have current header Else finalHeaderFound = .Match(header, finalHeaderRng, 0) 'Find header in Final sheet With wsImport Set importColRng = .UsedRange.Columns(importHeaderFound).Offset(1, 0).Resize(.UsedRange.Rows.Count - 1, 1) End With With wsFinal Set finalColRng = .Range(.Cells(2, finalHeaderFound), .Cells(importLastRow, finalHeaderFound)) finalColRng.Value2 = vbNullString 'Delete previous values (entire column) End With finalColRng.Value2 = importColRng.Value2 'Copy Import data in Final columns End If End If Next End With setStaticData importLastRow extractYears applyColumnFormats cFinal 'Apply date and number format to Import sheet allUpper wsFinal 'wsFinal.UsedRange.AutoFilter applyFormat wsFinal.Range(wsFinal.Cells(1, 1), wsFinal.Cells(importLastRow, wsFinal.UsedRange.Columns.Count)) Dim ws As Worksheet For Each ws In Worksheets ws.Activate ActiveWindow.Zoom = 85 ws.Cells(2, 2).Activate ActiveWindow.FreezePanes = True ws.Cells(1, 1).Activate Next Else MsgBox Missing raw data (Sheet 2 - 'Import'), vbInformation, Missing Raw Data End IfEnd SubNext method is a straight overwrite operation of static data from Sheet1 onto Sheet3Private Sub setStaticData(ByVal lastRow As Long) With cFinal .Range(D2:D & lastRow).Value = aIndex.Range(H2).Value .Range(F2:F & lastRow).Value = aIndex.Range(H9).Value .Range(AC2:AC & lastRow).Value = aIndex.Range(H3).Value .Range(X2:X & lastRow).Value = aIndex.Range(H4).Value .Range(Y2:Y & lastRow).Value = aIndex.Range(H5).Value .Range(AE2:AE & lastRow).Value = aIndex.Range(H6).Value .Range(AF2:AF & lastRow).Value = aIndex.Range(H7).Value .Range(AD2:AD & lastRow).Value = aIndex.Range(H8).Value End WithEnd SubAnother method of applying a specific text, number, date format to a set of columns (the same set of columns on either Sheet2 (Import), or Sheet3 (final result)Private Sub applyColumnFormats(ByRef ws As Worksheet) With ws.UsedRange .Cells.NumberFormat = @ 'all cells will be General .Columns(colNum(G)).NumberFormat = MM/DD/YYYY .Columns(colNum(I)).NumberFormat = MM/DD/YYYY '.Columns(colNum(A)).NumberFormat = @ '.Columns(colNum(B)).NumberFormat = @ '.Columns(colNum(C)).NumberFormat = @ .Columns(colNum(R)).NumberFormat = MM/DD/YYYY .Columns(colNum(Q)).NumberFormat = MM/DD/YYYY .Columns(colNum(T)).NumberFormat = MM/DD/YYYY .Columns(colNum(W)).NumberFormat = @ 'YYYY .Columns(colNum(V)).NumberFormat = @ 'YYYY .Columns(colNum(AC)).NumberFormat = MM/DD/YYYY .Columns(colNum(N)).NumberFormat = _($* #,##0.00_);_($* (#,##0.00);_($* -??_);_(@_) .Columns(colNum(AM)).NumberFormat = _($* #,##0.00_);_($* (#,##0.00);_($* -??_);_(@_) .Columns(colNum(AN)).NumberFormat = _($* #,##0.00_);_($* (#,##0.00);_($* -??_);_(@_) .Columns(colNum(AO)).NumberFormat = _($* #,##0.00_);_($* (#,##0.00);_($* -??_);_(@_) End WithEnd SubHelper method: Cell, border, and font formatting to all data on Sheet3Private Sub applyFormat(ByRef rng As Range) With rng .ClearFormats With .Font .Name = Georgia .Color = RGB(0, 0, 225) End With .Interior.Color = RGB(216, 228, 188) With .Rows(1) .Font.Bold = True .Interior.ColorIndex = xlAutomatic End With With .Borders .LineStyle = xlDot 'xlContinuous .ColorIndex = xlAutomatic .Weight = xlThin End With End With refit rngEnd SubHelper method: Converts all data to upper caseThe main aspect about all helper methods acting on large ranges of data is that they perform:Only one interaction with the worksheet to copy all data to memoryProcesses each individual value by looping over the memory arrays (unavoidable nested loops for 2 dimensional arrays)Then in another single interaction with the sheet places all data transformed back in the same areaThis is, by far, the most overlooked performance improvement. It requires minimum coding effort, but might be perceived as a somewhat difficult concept to grasp for novice VBA enthusiasts (including myself) who just want to get the job done, without complicating thingsPrivate Sub allUpper(ByRef sh As Worksheet) Dim arr As Variant, i As Long, j As Long If WorksheetFunction.CountA(sh.UsedRange) > 0 Then arr = sh.UsedRange For i = 2 To UBound(arr, 1) 'each row For j = 1 To UBound(arr, 2) 'each col arr(i, j) = UCase(RTrim(Replace(arr(i, j), Chr(10), vbNullString))) Next Next sh.UsedRange = arr End IfEnd SubHelper method: converts dates on certain columns to a YYYY format. In retrospect, I should have made it generic to accept a column name, range, letter, or number, as a parameter instead of hard-codding 2 columns. The point I was trying to make here was to combine multiple columns within one loop for improved performance, instead of several loops performing the same operation, on different columnsPrivate Sub extractYears() Dim arr As Variant, i As Long, j As Long, ur As Range, colW As Long, colV As Long Set ur = cFinal.UsedRange '3rd sheet If WorksheetFunction.CountA(ur) > 0 Then colW = colNum(W) colV = colNum(V) arr = ur For i = 2 To getMaxCell(ur).Row 'each row If Len(arr(i, colW)) > 0 Then arr(i, colW) = Format(arr(i, colW), yyyy) If Len(arr(i, colV)) > 0 Then arr(i, colV) = Format(arr(i, colV), yyyy) Next ur = arr End IfEnd SubPrivate Sub refit(ByRef rng As Range) With rng .WrapText = False .HorizontalAlignment = xlGeneral .VerticalAlignment = xlCenter .Columns.EntireColumn.AutoFit .Rows.EntireRow.AutoFit End WithEnd SubHelper method: next, are 2 generic functions that return:The column letter from the column numberThe column number from the column letterNot ideal naming convention as it's not descriptive enough (not intuitive or self-documented). My reason (not excuse): long names don't fit well in the small area provided - doesn't make it OKPublic Function colLtr(ByVal fromColNum As Long) As String 'get column leter from column number 'maximum number of columns in Excel 2007, last column: XFD (16384) Const MAX_COLUMNS As Integer = 16384 If fromColNum > 0 And fromColNum <= MAX_COLUMNS Then Dim indx As Long, cond As Long For indx = Int(Log(CDbl(25 * (CDbl(fromColNum) + 1))) / Log(26)) - 1 To 0 Step -1 cond = (26 ^ (indx + 1) - 1) / 25 - 1 If fromColNum > cond Then colLtr = colLtr & Chr(((fromColNum - cond - 1) \ 26 ^ indx) Mod 26 + 65) End If Next indx Else colLtr = 0 End IfEnd FunctionPublic Function colNum(ByVal fromColLtr As String) As Long 'A to XFD (upper or lower case); if the parameter is invalid it returns 0 'maximum number of columns in Excel 2007, last column: XFD (16384) Const MAX_LEN As Byte = 4 Const LTR_OFFSET As Byte = 64 Const TOTAL_LETTERS As Byte = 26 Const MAX_COLUMNS As Integer = 16384 Dim paramLen As Long Dim tmpNum As Integer paramLen = Len(fromColLtr) tmpNum = 0 If paramLen > 0 And paramLen < MAX_LEN Then Dim i As Integer Dim tmpChar As String Dim numArr() As Integer fromColLtr = UCase(fromColLtr) ReDim Preserve numArr(paramLen) For i = 1 To paramLen tmpChar = Asc(Mid(fromColLtr, i, 1)) If tmpChar < 65 Or tmpChar > 90 Then Exit Function 'make sure it's a letter. upper case: 65 to 90, lower case: 97 to 122 numArr(i) = tmpChar - LTR_OFFSET 'change lettr to number indicating place in alphabet (from 1 to 26) Next Dim highPower As Integer highPower = UBound(numArr()) - 1 'the most significant digits occur to the left For i = 1 To highPower + 1 tmpNum = tmpNum + (numArr(i) * (TOTAL_LETTERS ^ highPower)) 'convert the number array using powers of 26 highPower = highPower - 1 Next End If If tmpNum < 0 Or tmpNum > MAX_COLUMNS Then tmpNum = 0 colNum = tmpNumEnd FunctionFor the next method I applied an extra performance improvement to the usual known method of determining the last cell with data:Normal methods perform an inverse search of the first data value staring at the last row\column of an Excel sheet (which now has over 1 million rows and and 16 thousand columnsThis method expects only on the UsedRange - the notoriously inaccurate range that remembers cell formatting, unused formulas, hidden objects, etc. However, this inaccurate range is much smaller the the entire sheet, but large enough to include all data, so it performs the inverse search over only a few excess rows and columnsBy my definition, the last used cell can also be empty, a long as it represents the longest row and column with dataPublic Function getMaxCell(ByRef rng As Range) As Range 'search the entire range (usually UsedRange) 'last row: find first cell with data, scanning rows, from bottom-right, leftwards 'last col: find first cell with data, scanning cols, from bottom-right, upwards With rng Set getMaxCell = rng.Cells _ ( _ .Find( _ What:=*, _ SearchDirection:=xlPrevious, _ LookIn:=xlFormulas, _ After:=rng.Cells(1, 1), _ SearchOrder:=xlByRows).Row, _ .Find( _ What:=*, _ SearchDirection:=xlPrevious, _ LookIn:=xlFormulas, _ After:=rng.Cells(1, 1), _ SearchOrder:=xlByColumns).Column _ ) End WithEnd FunctionHelper method: another set of versatile general functions for turning off Excel features that might hinder VBA performance, main ones:xlCalculationAutomatic - extremely convenient for manual interactions with sheets, huge potential of performance issues when performing VBA updates to large ranges as it triggers exponential calculations to all dependent formulas on the sheet(s)EnableEvents - can trigger nested events (infinite recursion) which Excel terminates eventually). Also may cause inexplicable or unexpected VBA behavior when not turned back onScreenUpdating - well knownDisplayPageBreaks: I've seen an earlier comment referring to this. To me this is insidious, perceived harmless, when in fact it can cause extra work behind the scenes, especially when re-sizing rows and columns. I never print anything, so I never care about page breaks, but Excel cares about them at every move: re-size 1 column\row - it recalculates page size for all used area; it should be used and only when printingPublic Sub fastWB(Optional ByVal opt As Boolean = True) With Application .Calculation = IIf(opt, xlCalculationManual, xlCalculationAutomatic) If .DisplayAlerts <> Not opt Then .DisplayAlerts = Not opt If .DisplayStatusBar <> Not opt Then .DisplayStatusBar = Not opt If .EnableAnimations <> Not opt Then .EnableAnimations = Not opt If .EnableEvents <> Not opt Then .EnableEvents = Not opt If .ScreenUpdating <> Not opt Then .ScreenUpdating = Not opt End With fastWS , optEnd SubPublic Sub fastWS(Optional ByVal ws As Worksheet, Optional ByVal opt As Boolean = True) If ws Is Nothing Then For Each ws In Application.ActiveWorkbook.Sheets setWS ws, opt Next Else setWS ws, opt End IfEnd SubPrivate Sub setWS(ByVal ws As Worksheet, ByVal opt As Boolean) With ws .DisplayPageBreaks = False .EnableCalculation = Not opt .EnableFormatConditionsCalculation = Not opt .EnablePivotTable = Not opt End WithEnd SubPublic Sub xlResetSettings() 'default Excel settings With Application .Calculation = xlCalculationAutomatic .DisplayAlerts = True .DisplayStatusBar = True .EnableAnimations = False .EnableEvents = True .ScreenUpdating = True Dim sh As Worksheet For Each sh In Application.ActiveWorkbook.Sheets With sh .DisplayPageBreaks = False .EnableCalculation = True .EnableFormatConditionsCalculation = True .EnablePivotTable = True End With Next End WithEnd SubAny suggestions to improve readability for ease of maintenance, restructuring functions, naming conventions, etc, will be much appreciated
|
Intense worksheet manipulations: what price did I pay for performance optimization?
|
performance;algorithm;vba;excel
|
This isn't going to be a full-blown, fine-combed review. Just a few points.Use PascalCase for procedure/member identifiers. Being consistent about this helps readability because it makes it easy to tell members from locals and parameters at a glance, without even reading them.In general your indenting is fine, except here:fastWB True 'turn off all Excel features related to GUI and calculation updates t1 = Timer 'start performance timer mainProcess t2 = Timer 'process is completedfastWB False 'turn Excel features back onYes, it's a logical block, a bit like On Error Resume Next {instruction} On Error GoTo 0 would be. But it's not a syntactic code block. A different usage of vertical whitespace makes a better job at regrouping the statements I find:fastWB True 'turn off all Excel features related to GUI and calculation updatest1 = Timer 'start performance timermainProcesst2 = Timer 'process is completedfastWB False 'turn Excel features back onThe comments are annoying more than anything else. Consider using more descriptive identifiers instead:ToggleExcelPerformancestartTime = TimerRunMainProcessendTime = TimerToggleExcelPerformance FalseNote that the difference between startTime and endTime will be skewed if you run this code a few seconds before midnight on your system, because of how Timer works. Shameless plug, but with a little bit of abuse there are much more precise and reliable ways to time method execution (I co-own the rubberduck project), especially if you don't need the duration to be in your production code.This declaration came as a surprise:Dim ws As WorksheetFor Each ws In WorksheetsWhy? Because it's the only declaration in the MainProcess method, that's declared close to usage (as it should). Either stick it to the top of the procedure with the other ones (eh, don't do that), or move the other declarations closer to their first usage (much preferred).Pretty much the entire procedure's body is wrapped in this If..Else block:If Len(bImport.Cells(2, 1).Value2) > 0 Then 'wall of codeElse MsgBox Missing raw data (Sheet 2 - 'Import'), vbInformation, Missing Raw DataEnd IfI suggest you revert the condition to reduce nesting:If Len(bImport.Cells(2, 1).Value2) = 0 Then MsgBox Missing raw data (Sheet 2 - 'Import'), vbInformation, Missing Raw Data Exit SubEnd If'wall of codeThis is what I like to call an abuse of the With statement:With Application 'wall of codeEnd WithI like that you're making explicitly qualified references to the Application object like this, ...but not like this - a With block should look like this:With someInstance foobar = .Foo(42) .DoSomething .Bar smurfEnd WithIf you're merely wrapping a whole method with a With block just to avoid having to type Application the 3-4 times you're referring to the Application object, ...sorry to say, but you're just being lazy - and you've uselessly increased nesting for that reason, too.IMO this is another abusive/lazy usage of With:With wsImport Set importColRng = .UsedRange.Columns(importHeaderFound).Offset(1, 0).Resize(.UsedRange.Rows.Count - 1, 1)End WithVersus:Set importColRng = wsImport.UsedRange.Columns(importHeaderFound) _ .Offset(1, 0) _ .Resize(wsImport.UsedRange.Rows.Count - 1, 1)This is awkward:With rng Set getMaxCell = rng.Cells _ ( _ .Find( _ What:=*, _ SearchDirection:=xlPrevious, _ LookIn:=xlFormulas, _ After:=rng.Cells(1, 1), _ SearchOrder:=xlByRows).Row, _ .Find( _ What:=*, _ SearchDirection:=xlPrevious, _ LookIn:=xlFormulas, _ After:=rng.Cells(1, 1), _ SearchOrder:=xlByColumns).Column _ )End WithYou open up a With block, but the first statement in it ignores it: Set getMaxCell = rng.Cells _Should be Set getMaxCell = .Cells _And then After:=rng.Cells(1, 1) is also referring to rng. What do you need that With block for, really?Now, I really don't like that .Cells call: that 15-liner single instruction is doing way too many things. An instruction should only have as few as possible reasons to fail. If either Find fails, you'll have a runtime error 91, and no clue if it's the row or the column find that's blowing up.Function GetMaxCell(ByRef rng As Range) As Range On Error GoTo CleanFail Const NONEMPTY As String = * Dim foundRow As Long foundRow = rng.Find(What:=NONEMPTY, _ SearchDirection:=xlPrevious, _ LookIn:=xlFormulas, _ After:=rng.Cells(1, 1), _ SearchOrder:=xlByRows) _ .Row Dim foundColumn As Long foundColumn = rng.Find(What:=NONEMPTY, _ SearchDirection:=xlPrevious, _ LookIn:=xlFormulas, _ After:=rng.Cells(1, 1), _ SearchOrder:=xlByColumns) _ .Column Set GetMaxCell = rng.Cells(foundRow, foundColumn)CleanExit: Exit FunctionCleanFail: Set GetMaxCell = Nothing Resume CleanExit 'break here Resume 'set next statement hereEnd FunctionThat will return Nothing to the caller (for it to handle of course) instead of blowing up if the function is given an empty range, or any other edge case that wasn't accounted for. And as a bonus, all you need to do to find the problem is to place a breakpoint just before the error-handling subroutine finishes.There's certainly a lot more to say about this code, ...but this answer is already long enough as it is ;-)
|
_hardwarecs.59
|
I'm looking for a weatherproof (or waterproof only) IP Camera capable of covering long distances like 500 meters or more for 24/7 surveillance in industrial areas. I've searched among popular brands but none of them had this specification. most camera lens sized I found are:3.6mm 15 meters6mm 20 meters8mm 26 meters12mm 40 meters16mm 60 metersThe only Important specifications for the IP camera is having a good video quality and at least 500 meters of straight coverage, so it doesn't matter whether it uses mechanical zoom or digital but it definitely must be a PTZ (Pan, Tilt, Zoom) camera. Thanks! UPDATE: the camera's video quality need to be HD and 10 pixels per inch.
|
Weatherproof IP camera for long distances
|
ip camera;waterproof
|
The AvertX 30X HD provides pretty much everything you're looking for, but it only covers ~105m. This brand tends to not specify optical or digital zoom on their website which makes things difficult.The 3S N5012 has a lot of very appealing features. Specifically, 94mm max focal length paired with 12x digital zoom can provide long view distances. This could reach close to 500m, but digital zoom severely affects video quality, so that's your call.I'll update this as I find more options.
|
_softwareengineering.89266
|
I'm often asked at some point during the interview process to compare myself to my peers. For example, one of my first after-graduation jobs asked me to compare myself to my classmates. A job I recently interviewed for asked me to compare myself to my coworkers.I always play this down quite a bit. I'm always worried that, I'm miles above everyone around me, sounds too arrogant. When push comes to shove though it is the truth.I graduated at the top of my class. I had a 3.99, the highest GPA of anyone else that year. My fellow students bitched and moaned about things like having to use the console to write javac xxx.java and build programs instead of just hitting the build button in VS. Most of them were utterly inept and I'd hate to see what happened to them in the real world. Others were miles above these people. There were like 3-5 of us that actually gave a damn, pursued our own education as if it mattered, and had whatever genes are necessary to think like a programmer or mathematician (the one guy I'd say was smarter than me was actually a math major--he graduated one year ahead of me or he would have taken my title). Even among these few big hitters I was one of, if not the best (some was due to more experience though).For about 90% of the other students though I see this not as me being so good, but them being really that f'n bad. I was often dumbfounded not just by their ignorance, but by their unwillingness to do what it took to loose it. My peers in college were lazy, bemoaning, irresponsible, sacks of stupidity that would rather run around puking from so much booze than put out the least amount of effort in learning anything. Then they blamed their ineptitude on the professors.As I entered the workforce I found that this trend continued. When I'm on the internet, talking to a worldwide populace of brilliant people I'm rather mediocre. I'm smart, excited, etc...I'm still very good but I'm much more able to see myself as a smaller fish in a larger ocean. Locally though, in personal real life experience....what I find easy others find hard even among what I'd call some of the best developers I've worked with. I know more about design, general development, and the specific language I use more than anyone else I know. Part of this is, I know full well, the kind of places I've learned in and where I've worked (who doesn't have the money to pay me what I'm worth). Still though, if I were to fairly compare myself to my coworkers, and in years past my co-students...don't I come off as more than a little arrogant?Others see me this way too though. It actually took me a while to recognize that there's actually something significantly special about the way I approach my programming (I really care), work ethic, and additionally my lucky roll in the gene game. I have seen it get to my head from time to time, and I try to avoid it, but in all honesty I'm just better than most.One thing that seems to differentiate me more than anything really is the fact that I continue to pursue greater knowledge at home, off hours. I'm one of the best because I want to be and it shows significantly. I've found that this is actually fairly rare in the real world, though many Internet people have me beat here as well.Knowing that there's certainly many more people like this out there, in fact I know of many people on SE that are much smarter than I am, how do you approach this question? Do you answer honestly? I'm a fucking God that has do dumb down everything thing they do for the little people! The only way I can drag the rest along is by saying everything 20 times in 5 different ways. Or do you downplay yourself to make sure you don't come off as someone so damn arrogant they can't work with others?Edit: Yes, I make grammatical mistakes and additionally many more. I also suck at welding even though I tried very hard to get it. I also have a very hard time keeping my house plants alive. Some people are simply better at it. I'm simply better at programming.
|
Comparing one's self to others during interviews
|
interview
|
You might say something like this (something I tried recently and worked relatively well).I see myself as a potential leader amongst my fellow co-workers. I am striving for this by offering advice on various programming tasks and leading the design and development of the projects I work on. An example of this is when I helped Bob the other day resolve a particulary complex problem. I offered him a number of methods he could use to resolve a problem he had been stuck with for a few days. Another example is during the recent team meeting of Project Give 'em shit I offered and lead the discussion in design by suggesting we use the Repository pattern for our database interaction. When the team were unsure of the benefits of this or how it works I provided a detailed informal training session into the benefits and uses of this design pattern and where it helps resolve requirement.Throughout the day, Tim will often come and ask my advice on how to fix a problem he is experiencing, or Jane who was asked to look into the latest microsft web design methodologies and didn't know where to start. I helped her by suggesting she look at the MVC architecture and ASP .NET web forms as starting points.I am constantly trying to improve my skills so that I can help progress my own development, push my boundaries and be able to relay that back to the team in healthy technical discussions and through the work I contribute.End.Being the smartest, best programmer, or knowing the best about cutting edge technology is sometimes not the primary trait a company is looking for. You need to find out what they cherish most, and while continuing on what you are doing learning wise etc aim to become to the attention of your superiors on those areas. They might be looking for communication, teamwork or customer interaction which is something I value just as highly in an employee.And try not to do so to the detriment of your relationship with your colleagues. The workplace can just be like the grown up version of the school class room. Just as brutal if you find yourself on the outside.
|
_codereview.85048
|
I have written some code which makes a button morph into a container. I have written it using prototypes. I am fairly new to jQuery/JS so was looking for advice on whether this was a bad/good way to write the script?A previous version of my implementation was reviewed here.I was just thinking, would it have been more appropriate to have just had the constructer function Morphing and then an object containing all the other methods and things, rather than loads of different prototypes?Here is the jQuery:function Morphing( button, container, content, span, top) { this.button = button; this.container = container; this.content = content; this.overlay = $('div.overlay'); this.span = span; this.top = top; var self = this; this.positions = { endPosition: { top: Morphing.top, left: '50%', width: 600, height: 400, marginLeft: -300 }, startPosition: { top: self.container.css('top'), left: self.container.css('left'), width: self.container.css('width'), height: self.container.css('height'), marginLeft: self.container.css('margin-left') } };}Morphing.prototype.startMorph = function() { var self = this; this.button.on('click', function() { $(this).fadeOut(200); console.log('Button clicked, button faded out'); setTimeout(self.containerMove.bind(self), 200); });};// Perhaps the rest of the code under should just be in a normal object?Morphing.prototype.containerMove = function() { var self = this; this.overlay.fadeIn(); this.container.addClass('active'); console.log('Overlay shown, container given active class'); this.container.animate(this.positions.endPosition, 400, function() { self.content.fadeIn(); self.span.fadeIn(); console.log('Container animated to center, content and span shown'); self.close(); });};Morphing.prototype.close = function() { var self = this; this.span.one('click', function() { self.content.fadeOut(); self.span.fadeOut(); self.overlay.fadeOut(); console.log('Span clicked. Content, span, overlay all hidden'); setTimeout(self.animateBack.bind(self), 275); });};Morphing.prototype.animateBack = function() { var self = this; this.container.animate(this.positions.startPosition, 400, function() { self.button.fadeIn(300); self.container.removeClass('active'); console.log('Container animated back to start. Button shown and container removed active class'); });};And the index.html: <body> <button class=morphButton>Terms & Conditions</button> <div class=morphContainer> <span class=close>X</span> <h1 class=content>Terms & Conditions </h1> <p class=content> Pea horseradish azuki bean lettuce avocado asparagus okra. Kohlrabi radish okra azuki bean corn fava bean mustard tigernut juccama green bean celtuce collard greens avocado quandong fennel gumbo black-eyed pea. Grape silver beet watercress potato tigernut corn groundnut. Chickweed okra pea winter purslane coriander yarrow sweet pepper radish garlic brussels sprout groundnut summer purslane earthnut pea tomato spring onion azuki bean gourd. </p> </div> <button class=newButton>New</button> <div class=newContainer> <span class=newClose>X</span> <h1 class=newContent>New Stuff</h1> <p class=newContent>Pea horseradish azuki bean lettuce avocado asparagus okra. Kohlrabi radish okra azuki bean corn fava bean mustard tigernut juccama green bean celtuce collard greens avocado quandong fennel gumbo black-eyed pea. Grape silver beet watercress potato tigernut corn groundnut. Chickweed okra pea winter purslane coriander yarrow sweet pepper radish garlic brussels sprout groundnut summer purslane earthnut pea tomato spring onion azuki bean gourd.</p> </div> <div class=overlay></div><script>$(document).ready(function() { var morph = new Morphing( $('button.morphButton'), $('div.morphContainer'), $('h1.content, p.content'), $('span.close'), 100 ); var morphTwo = new Morphing( $('button.newButton'), $('div.newContainer'), $('h1.newContent, p.newContent'), $('span.newClose'), 200 ); morph.startMorph(); morphTwo.startMorph();});</script> </body>jsfiddle: https://jsfiddle.net/Specksavers/9a2projy/2/The console.log() statements will be removed in the final version
|
jQuery morphing button concept
|
javascript;jquery
| null |
_unix.8980
|
I'd like to mirror my existing root (and only) partition on an SSD to another disk. It should be a sort of RAID-1, just asymmetric*. I know there's the option mdadm --write-behind, which should do it.But I have no idea if it is possible with preserving the context of the existing partition. I imagine it likecreate the slave partitionsetup the RAID telling it that the slave partition is not initializedlet it initialize it by cloning the master partitionbut I'm probably too optimistic, aren't I?* All reads should access the first disk and writes should be considered finished when the first disk is written.
|
How to raid-mirror existing root partition?
|
software raid
|
You can create an mdraid RAID-1 array starting with an existing partition. First, you need to make room for the mdadm superblock, which means you need to shrink your filesystem a little.At the moment, the normal superblock format is 0.9. Its location is between 128kB and 60kB from the end of the partition, it is 4kB long, and it starts on an address that is a multible of 64kB. So shrink your filesystem by 128kB, or more precisely to ((device_size mod 64kB) - 1) * 64kB.If you want more than 2TB per stripe, you need the 1.0 superblock format, which isn't supported out-of-the-box by all distributions yet. The 1.0 superblock is at the end of the device, which I understand to mean that you only need to shrink your filesystem by 8kB.Now that you've shrunk the filesystem, you can create the array. First create a degraded array with just the existing data. Make sure the filesystem isn't mounted at this point. For your use case the write-intent bitmap must be on a separate partition. Use -e 1.0 to use the newer version-1 superblock format.mdadm --create /dev/md0 -e 0.9 -l 1 -n 2 \ --write-behind=256 --bitmap=/path/to/bitmap /dev/sda1 missingNow you can mount the filesystem in /dev/md0. Add the second disk at your leasure. The data will be copied to the new drive in the background.mdadm --add /dev/md0 --write-mostly /dev/sdb1I've created a mirrored array like this, but without write-behind mode. I don't think write-behind mode would invalidate the procedure.
|
_unix.59917
|
I am making an embedded Linux distribution and my board is a Raspberry Pi. My kernel version is 3.2.27 without initramfs and my root file system as follows:/lib /* contains kernel modules *//bin /sbin /usr/bin /usr/sbin /* contains busybox utils binaries *//usr/lib /* contains cross-compiler tool chain libs */linuxrc /* generated by busybox, kept in / *//dev /* I have created console and ttyAM0 manually but added mode devices by udev *//etc/init.d/rcS /* required by busybox init */after kernel booted I am getting a console (I don't know whether it is busybox console or not). I have few problems belowNo process information available (no files/folder created under /proc).When I am using ps -e it shows nothing.Why this unexpected behavior happens?
|
No /proc in a Busybox-based embedded Linux distribution
|
linux;startup;proc;busybox
|
After initialising and mounting the root file system, Linux starts /sbin/init which carries on with the user space initialisations including mounting /procMost likely your rcS or whatever configuration init reads doesn't do that, and you need to tell it to.If you've got a shell prompt, you can mount /proc manually with:mount -t proc p /procNote that the /proc directory must exist before you can mount something there. You should include it in your root image.
|
_softwareengineering.72844
|
Is it appropriate to release incomplete open-source firmware, or in other words, to release only GPL software but not proprietary software source code?How are non-open-source programs, in compiled firmware for a router/embedded device, allowed with the open-source, Linux-based operating system and other GPL software?For example:If a company releases compiled firmware and source code for a router but only releases the source code for GPL software within the firmware, is it okay, according to the GPL, that the firmware source code would be uncompilable because it is incomplete and is missing the proprietary part of the software?
|
Is it appropriate to only release the GPL-licensed part of the code as open source?
|
licensing;gpl
| null |
_cs.41544
|
$$L = \{x^iy^jz^k \mid i \le2j\text{ or }j \le 3k\}$$To Prove: If given language is regular or not.I know that it is not a regular language but I am not able to come up with the string which I can use in the pumping lemma to prove that it is not regular.We can also divide $L$ into two parts:$$\begin{align*}L_1 &= \{x^iy^jz^k \mid i \le 2j\}\\L_2 &= \{x^iy^jz^k \mid j \le 3k\}\,,\end{align*}$$so I just need the strings to be used in the pumping lemma for $L_1$ and $L_2$.
|
Prove if given language is regular or not
|
formal languages;regular languages
|
It's not regular. Hint: Let $p$ be the integer of the pumping lemma and pump the string $x^{6p}y^{3p}z^{2p}$.
|
_softwareengineering.67813
|
How many of you actually work out the exercises when learning from a book (any programming related book), I'm currently working my way through a C++ book and find that some of the exercises I feel I can complete rather easily I skip. Do most people do this? Or do they read the whole book and come back to exercises that looked difficult?
|
Do you do the exercises when reading a book?
|
learning;books
|
I find it to be helpful to actually type in the solutions to the exercises and run them. Sometimes you'll get the answer on the first try, and sometimes it's a little bit trickier than it first looked. You'll never know what you're missing until you have working code.One huge benefit to typing in the exercises yourself if that you get practice debugging. If it's a new language and a new environment, you'll inevitably make mistakes. Getting the solutions to even the simplest problems to work is good practice.
|
_scicomp.17477
|
Can someone give some references to understand what's the differences between a component-wise and a characteristic-wise ENO scheme?If I'm right, the characteristic variables come from the diagonalization of flux matrix but I don't see how it comes to play when doing ENO and what's the advantage of it.
|
ENO/WENO component-wise vs characteristic-wise
|
fluid dynamics;reference request
|
In both components-wise and characteristic variable methods, the basic ENO formulation remains the same. In this answer, Only finite volume formulation is considered. however, FD is similar in philosophy and can can be studied from the references. note: $i$ is the cell under consideration. $j$ is the generic index for cells.Implementation Details [1]1. Component-wise ENOThis is the most straightforward procedure.The procedure is similar as that for a scalar 1d equation. We have a vector of conserved variables $\bar u_{n \times 1} = [u_1, u_2, ... ,u_n]^T$ and the flux vector $f_{n \times 1} = f(\bar u)$. We carry out ENO reconstruction for each component of $\bar u$ (lets call it simply $u$) separately. This is not a true decoupling. This gives us left and right values for $u$ ($u_l $ and $u_r$) at $x_{i+\frac{1}{2}}$. Doing this for all components gives us $\bar u_l$ and $\bar u_r$ at $x_{i+\frac{1}{2}}$. Then flux $f$ at $x_{i+\frac{1}{2}}$ is found out by solving the Riemann problem at $x_{i+\frac{1}{2}}$. Either exact or approximate Riemann solver can be used for this. Some of the hyperbolic systems, including Euler's equations, have exact Riemann solutions. A low order solution is more sensitive towards choice of Riemann solver. Hence we can use more cost effective approximate solvers at high orders (however, we don't use component method for high orders!). Once the fluxes are formed, we can advance in time using appropriate time integrator. Similar approach is taken for WENO.2. Characteristic-wise ENOa. Linear system with constant coefficient matrix $f'$:Consider the same system of equations.Considering it to be a (strictly) hyperbolic system, the Jacobian $f'$ (or coefficient matrix $A$ as in some cases), has $n$ distinct eigenvalues ($\lambda_j(\bar u); j=1,...,n$) and corresponding right ($r_j(\bar u); j=1,...,n$) and left eigenvectors ($l_j(\bar u); j=1,...,n$). let $R = [r_1, r_2, ... , r_n]$ and $\Lambda = diag(\lambda_1, \lambda_2,...,\lambda_n)$ be constant everywhere. Then we can diagonalize the Jacobian matrix using $R, R^{-1}$ and $\Lambda$.i.e. we get, $\bar v_t + \Lambda \bar v_x = 0$where, $\bar v$ is the characteristic variable vector. Now each component of $\bar v$ is truely decoupled and this is nothing but $n$ separate hyperbolic equations. We can then do the ENO procedure on each one to get $v$ at a particular $x_{i+\frac{1}{2}}$. After all the components are treated in this fashion, we get $\bar v$ at $i+\frac{1}{2}$. After this, we can recover $\bar u$ from $\bar v$ by using $\bar u_{i+\frac{1}{2}} = R \bar v_{i+\frac{1}{2}}$. b. Non linear system or variable coefficient matrix $f'$:The main problem with this type is that, $R, R^{-1}$ and $\Lambda$ change with u. So we need to freeze them in space at $x_{j+\frac{1}{2}}$. This is done by taking arithmatic or Roe or $somefancy$ average or $\bar u_j$ and $\bar u_{j+1}$ at $j+\frac{1}{2}$. Then $R_{j+\frac{1}{2}} = R(\bar u_{j+\frac{1}{2}}) ; \forall j$We can get characteric variable $v_{j+\frac{1}{2}}$ from $u_{j+\frac{1}{2}}$ using this $R$. In other words, the transformation into the characteristic variable is local. Then perform scalar ENO reconstruction on all $v$ and obtain values at $i+\frac{1}{2}$. The rest of the procedure remains the same as discussed earlier,Transform back to $u$ at $i+\frac{1}{2}$.Solve Riemann problem $\rightarrow$ Find flux.Time integration.Why and when to use component method:Straightforward and Really simple to use. We need to perform less number of operations. Works well for many problems especially if order of accuracy is small (2 or maybe 3 in some cases). Suitable for simple test cases.Characteristic method:More robust.As Kyle Mandli very rightly pointed out in his comment, since we are truly decomposing the variables, the upwind fluxes will be more accurate. We are taking into consideration the wave direction and speed. For more demanding test problems and higher accuracies, we should use the characteristic decomposition. Also for highly nonlinear equations, one should use the characteristic decomposition for obtaining a robust solver.As an example, you can study the FD implementation of WENO to equations of ideal magnetohydrodynamics [2] (because, it is a very good example to demonstrate the use of the characteristic method. Also you will get to see the FD implementation, which is not discussed here).Along with this, the text on Computational Gasdynamics by Culbert Laney discusses about ENO implementation. References[1] Shu, C. W. (1997). Essentially Non-Oscillatory and Weighted Essentially Non-Oscillatory Schemes for Hyperbolic Conservation Laws. ICASE Report, (97 - 65)Very detailed explanation. In fact I have repeated here most of what is given in this report. Here is the link for the report. [2] Jiang, G.-S., & Wu, C. (1999). A High-Order WENO Finite Difference Scheme for the Equations of Ideal Magnetohydrodynamics. Journal of Computational Physics, 150(2), 561594.[3] PyWENO can be used for obtaining the coefficients easily.
|
_softwareengineering.310919
|
Say that you have an web application which prints pages in a document. Suppose that after validating the page range, the application does the following:If a billing option is turned on, it first checks with the server to confirm the print.After confirming the print (or doing nothing if the billing option is not turned on), it then prints the pages.In order to support billing being both on and off, the code looks something like this:function printPages (...) { if (billing) { confirmPrintWithServer(..., function () { printPagesInternal(...); }); } else { printPagesInternal(...); }}If the call to check the printing was synchronous, this wouldn't really be a problem. Then it would look like this:function printPages (...) { if (billing) { if (!confirmPrintWithServer(...)) return; } // continue with rest of printPages}What went in a printPagesInternal in the first case would simply be the rest of printPages in the synchronous case.Is there any better way to name these two things than appending Internal or something similar to the end of the one that the caller of the code does not see? If we had more layers of checks, would we do InternalInternal? Is the more layers of checks situation just not going to happen, so adding Internal is actually the right solution?
|
How to name functions which continue a process after an asynchronous step
|
naming;asynchronous programming
| null |
_unix.251840
|
I want to turn a computer that I have lying around into a file server. The problem is that I cannot find my public IP. I have used services such as myip or even google, but they all point to the IP of the server of my ISP in another city. Does anyone know: How I can find my public IP and How I can access my computer from outside my LAN?
|
Finding Servers Public IP and Allowing Remote Access
|
ip;file server
| null |
_cstheory.16127
|
I have a question about a answer of a question which is proposed in this stack exchange.The Past QuestionOne of the most basic result in circuit complexity is the constnat depth cirdcuit lower bound computing PARITY function using the switching lemma. Another popular function MAJORITY has also lower bound $exp (\Omega (n^{1/(d-1)}))$ and matching upper bound $exp (O (n^{2/(d-1)}))$.My question is about upper bound of Threshold function which is a natural generalization of majority function. The formal definition of the threshold function is the following one. DEFINITION:$THR(x_{1},...,x_{n})= \begin{cases} 1 & a_{1}x_{1}+\cdots +a_{n}x_{n} \geq t \\ 0 & otherwise \end{cases}$We assume that each weight $a_{i} \in \mathbb{Z}$ is at most $2^{O(n)}$QUESTION1:The depth $d$ circuit with unbounded fanin AND OR NOT gates to compute the above function has size $2^{n^{\epsilon}}$ ?Where $\epsilon $ can depend on $d$ like $2^{n^{1/100d}}$ .AnswerKristoffer Arnsfelt Hansen said that:1.$General$ $weight$ $threshold$ $gates$ can be computed by polynomial size depth 2 circuits built from $majority$ $gates$. An efficient construction of this is e.g. given by Amano and Maruoka. Then you can just compute each of these by constant depth circuits built from AND and OR gates.My Question$majority$ $gates$ is a monotone gate which is computes a monotone function. A monotone functin does not decreace its function value by increasing the number of 1s in the input 0-1 bit string. However, $General$ $weight$ $threshold$ $gates$ is NOT a monotone function. For example, we can check the function which output 1 if and only if $2x_{1} -5x_{2} + 3x_{3} \geq 3.5$ is not a monotone function because increasing the value of $x_{2}$ brokes the monotone property. My question is :For a givern arbitrary threshold function $THR:\{0,1\}^{n}\rightarrow \{0,1\}$ with arbitrary real number weights and with no monotonicity, can we construct a constant depth circuit with $poly(n)$ threshold gates such that for any gate, any weight of the gate is integer number and is at most $poly(\Delta) $, where $\Delta$ is fan-in of the gate?
|
Monotonicity and Threshold function
|
cc.complexity theory;circuit complexity
| null |
_unix.174292
|
Could anyone describe to me what sloppy mount is? There's two mount points on my server but I have no idea how to erase the sloppy one. I hope some one could explain to me the potential faults or what's happening under the hood. Appreciate your help:)ILTLVLSSC418:/etc # mountnfsserver:/export/sapmnt/T10 on /sapmnt/T10 type nfs (rw,soft,retrans=2,addr=10.96.88.7)nfsserver:/export/saptrans/trans1 on /usr/sap/trans type nfs (rw,soft,retrans=2,addr=10.96.88.7)nfsserver:/export/sapmnt/T10 on /sapmnt/T10 type nfs(rw,nfsvers=3,soft,retrans=2,sloppy,addr=10.96.88.7)nfsserver:/export/saptrans/trans1 on /usr/sap/trans type nfs4 (rw,soft,retrans=2,sloppy,addr=10.96.88.7,clientaddr=10.26.91.11)The mount command result is shown above. Plus I could not execute umount, as it would fail and remount back.
|
Linux sloppy mount
|
linux;mount;nfs;automounting
| null |
_opensource.867
|
After a patent expires people are free to use it.Does this means, that the technology described in the claims are then Open Source?
|
Is technology in expired patents open source?
|
patents
| null |
_codereview.3104
|
I've just released a jQuery plugin that conditionally displays elements based on form values. I would appreciate any suggestions on how to improve both the code and its usefulness.Here's the demo pageWould this be useful to you?What other functionality should I include?Any refactoring or structure changes that I should make?I am worried about exposing 4 different functions. Is this too many?The GoalThe plugin helps in situations where an element should hide or show based on values in other elements. In particular, it excels when there are multiple conditions that need to be satisfied in order to hide or show. Additional concepts to keep in mindUse as jQuery pluginEasy to chain rules togetherUnderstandable by reading a line of codeCan build/add custom conditionsExample of business rules to solveLet's say we have the following rules for elements:Display a set of checkboxes if Zip is between 19000 and 20000Income is lower than 15000Display another set of checkboxes if City is 'Philadelphia'Income is lower than 40000Display city select box if Zip is between 19100 and 19400Ideal look$('.elements_to_display') .reactIf( '#some_form_element', SatisfiesFirstCondition) .reactIf( '#some_other_form_element', SatisfiesAnotherCondition) .reactIf( '#some_other_form_element', SatisfiesAnotherCondition);Page JSvar IS = $.extend({}, $.fn.reactor.helpers);$('.cities') .reactIf('#zip', IS.Between(19100, 19400)) .reactIf('#zip', IS.NotBlank);$('.philly_middle_to_low_income') .reactIf('#income_2011', IS.LessThan(40000)) .reactIf('#cities_select', IS.EqualTo('philadelphia'));$('.low_income_select_zips') .reactIf('#income_2011', IS.LessThan(15000)) .reactIf('#zip', IS.BetweenSameLength(19000, 20000)) .reactIf('#zip', IS.NotBlank);$('.reactor').trigger('change.reactor');Plugin react.js(function($){ $.fn.reactTo = function(selector) { var $elements = $(selector), $reactor_element = $(this), _proxy_event = function() { $reactor_element.trigger('change.reactor'); }; $elements.filter('select').bind('change.reactor', _proxy_event); $elements.filter('input').bind('keyup.reactor', _proxy_event); return this; }; $.fn.reactIf = function(sel, exp_func) { var $sel = $(sel); var _func = function() { return exp_func.apply($sel); }; this.each(function() { if (!$(this).hasClass('reactor')) { $(this).reactor(); } var conditions_arry = $(this).data('conditions.reactor'); if (!$.isArray(conditions_arry)) { conditions_arry = []}; conditions_arry.push(_func); $(this).data('conditions.reactor', conditions_arry); }); $(this).reactTo(sel); return this; }; $.fn.react = function() { this.each(function() { $(this).trigger('change.reactor') }); return this; }; $.fn.reactor = function(options) { var settings = $.extend({}, $.fn.reactor.defaults, options); this.each(function() { // var opts = $.meta ? $.extend({}, settings, $this.data()) : settings; var $element = $(this); if (!$element.hasClass('reactor')) { $element.data('conditions.reactor', []).addClass('reactor'); } var is_reactionary = function() { var conditionalArray = $(this).data('conditions.reactor'); var r = true; $.each(conditionalArray, function() { r = (r && this.call()); }); return r; } var reaction = function(evt) { evt.stopPropagation(); if (is_reactionary.apply(this)) { settings.compliant.apply($element); } else { settings.uncompliant.apply($element); } } $element.bind('change.reactor', reaction); }); return this; }; $.fn.reactor.defaults = { compliant: function() { $(this).show(); }, uncompliant: function() { $(this).hide(); } }; $.fn.reactor.helpers = { NotBlank: function() { return( $(this).val().toString() != ) }, Blank: function() { return( $(this).val().toString() == ) }, EqualTo: function(matchStr) { var _func = function() { var v = $(this).val(); if (v) { return( v.toString() == matchStr ); } else { return false; } } return _func; }, LessThan: function(number) { var _func = function() { var v = $(this).val(); return(!(v && parseInt(v) > number)); } return _func; }, MoreThan: function(number) { var _func = function() { var v = $(this).val(); return(!(v && parseInt(v) < number)); } return _func; }, Between: function(min, max) { var _func = function() { var v = $(this).val(); return(!(v && (parseInt(v) > max || parseInt(v) < min))); } return _func; }, BetweenSameLength: function(min, max) { var len = min.toString().length; var _func = function() { var v = $(this).val(); return(!(v && v.length == len && (parseInt(v) > max || parseInt(v) < min))); } return _func; } };})(jQuery);HTML react.html<form id=portfolio_form> <fieldset> <label>Zip</label> <input id=zip type=text value= /><br /> <label>2011 Income</label> <input id=income_2011 name=income[2011] /> </fieldset> <p>Display cities only when zip is between 19100 and 19400</p> <fieldset class=cities> <label>Cities</label> <select id=cities_select> <option value=></option> <option value=philadelphia>Philadelphia</option> <option value=media>Media</option> <option value=doylestown>Doylestown</option> </select> </fieldset> <p>Display checkboxes only for Philadelphia and income less than 40000</p> <fieldset class=philly_middle_to_low_income> <input type=checkbox /> Check One<br /> <input type=checkbox /> Check Two<br /> <input type=checkbox /> Check Three<br /> <input type=checkbox /> Check Four<br /> </fieldset> <p>Display checkboxes when zip is between 19000 and 20000 and income is lower than 25000</p> <fieldset class=low_income_select_zips> <input type=checkbox /> Check One<br /> <input type=checkbox /> Check Two<br /> <input type=checkbox /> Check Three<br /> <input type=checkbox /> Check Four<br /> </fieldset> </form>
|
Plugin that conditionally displays elements based on form values
|
javascript;jquery;html;form
|
The syntax is nice, but the necessity for the user to declare IS themselves is not ideal. You should look for a different solution. One possibility could be to supply the name of the conditional function as a string and its arguments as additional arguments of reactIf. That way the conditional functions would no longer need to be of higher-order (not that that is a bad thing). Example:$('.cities').reactIf('#zip', Between, 19100, 19400);// ...$.fn.reactIf = function(sel, exp_func) { var $sel = $(sel); var args = arguments.slice(2); var _func = function() { return $.fn.reactor.helpers[exp_func].apply($sel, args); }; // ...}$.fn.reactor.helpers = { // ... Between: function(min, max) { var v = $(this).val(); return(!(v && (parseInt(v) > max || parseInt(v) < min))); }, // ...}These is one more problem with the conditional functions: You supply a jQuery object as the this argument toapply, so it's not needed to wrap this in another jQuery call inside the conditional functions. You should either change to apply call to:return exp_func.apply($sel[0]);or in the conditional functions:var v = this.val();I'm not sure if it's a good idea to mark elements with a class. This can go wrong, for example, if a second JavaScript removes all classes from an element. Instead of if (!$(this).hasClass('reactor')) { $(this).reactor(); } var conditions_arry = $(this).data('conditions.reactor'); if (!$.isArray(conditions_arry)) { conditions_arry = []};I would use var conditions_arry = $(this).data('conditions.reactor'); if (!$.isArray(conditions_arry)) { $(this).reactor(); conditions_arry = []; };and similarly in reactor().You should consider short-circuiting the $.each() loop calling the conditional functions (which also makes the && unnecessary): $.each(conditionalArray, function() { r = this.call(); return r; // Stops the `each` loop if r is `false` });
|
_webapps.17783
|
I use GMail in both office and home where I use Firefox and Safari respectively. I see Reader in the list in Firefox but not in Safari. I need to select from the dropdown list. Is there a way I can get my selected list of items in the Google+ bar in both Safari and Firefox ?
|
Why does Google+ bar show different data in Firefox and Safari?
|
gmail;google plus;safari 5
| null |
_softwareengineering.107130
|
I've noticed that Node.js has become very popular, and I've seen several instances of people doing small-scale projects in it.I've also looked at pros and cons lists to get an idea of what Node.js can do, but I'm still not clear on how it differs from other, more mature server-side tech like PHP, Perl, or Ruby on Rails.What, specifically, differentiates Node.js from the current alternatives, and why?
|
How is Node.js different from other server-side frameworks?
|
web development;comparison;node.js
| null |
_cogsci.9005
|
Is it true that a person's emotional state (such as arousal, fear, etc) can be determined by looking solely at the persons eyes?Here I am assuming that this may be the case only in limited circumstances (specific scenarios or specific basic emotions such as fear) but if emotional state can be determined from the eyes, is there any research on the extent to which this is possible?
|
To what degree is emotional state visible in a person's eyes?
|
emotion
| null |
_softwareengineering.116922
|
I participated in a coding competition today, and I found that almost all of the command line input our programs needed to receive would start with an integer representing the amount of data sets to follow. There were 6 different problems, and they all started this way.For example, one sample problem had:Input to this problem will begin with a line containing a single integer N (1 <= N <= 100) indicating the number of data sets. Each data set consists of the following components:A line containing a single integer W that specifies the number of wormholesA series of W lines containing....etc.Pretty much all the competition problems had this format, with the first integer representing the amount of data sets to follow.My initial reaction (and the way I tried to solve the problem) was just using a vector of size N, where each element represented a data set. Trouble is, there are a whole bunch of things in these data sets. Using this approach often left me with a vector of vector of vectors (maybe an exaggeration but you get the idea) which was very hard to manage.Another idea was looping through the entire program N times, but this doesn't always seem that applicable.I realize this is a vague question, but that's because I'm looking for a general solution to this type of problem. What is the best approach to handling this type of input?
|
How to handle X data sets as input
|
algorithms
|
I don't think there's another option other than the ones you mentioned. You either:a) iterate through all the the data sets and work on them as they come uporb) store everything (in some suitable data structure, like an array, hash table, tree, etc) and work on it later.
|
_softwareengineering.207274
|
So I am building an application with Angular and have started to get into UI testing with DalekJS (http://dalekjs.com). As I have been writing these tests I have been thinking to myself, should I even bother with writing unit test that that are UI/UX components.Now my angular services generally don't have anything to do with the DOM or directly rendering stuff on the page so those I unit test and it make sense however angular directives are components that render things directly to the page and writing unit tests seems like 1. It is not an effective way to test UI/UX components and 2. It would overlap with UI/UX Tests.For point #1, unit test (at least ones I have seen) don't actually write anything to a browser and render it. For thing that require DOM, you generally mock the DOM in a variable and use that to test whatever you need to test. If you have an error with a test, you can't load it up in a browser and play around with it like you could with UI/UX tests (which in my experience runs against code that is the true application that renders and everything).For point #2, one of my directives has a property called contentVisible. Now I can write a unit test that make sure that property is the correct value at certain points but that really don't not test what I truly want to test because even if contentVisible is set to false, the content still might be rendering to the screen which UI/UX test would pick up.Is it still worth the effort to write unit test for UI/UX Components where UI tests would be able to pick up everything the unit test would plus also do a better job since it can test what is actually rendered?ExceptionThe one exception case where I would need a unit test is for certain ajax requests. For example, making sure an ajax request is not made of that an ajax request that does not make and changes to the UI are things that can only be tested with unit tests.
|
Should I bother to write unit test for UI/UX Components?
|
testing;unit testing
| null |
_cs.59634
|
Suppose I have a set of 1000 binary strings of fixed length. I wish to divide these 1000 strings into 10 subsets of 100 strings each, in such a way that the subsets are maximally homogeneous. I want each subset of 100 to be as internally similar as possible. Similarities between subsets of 100 are of no consequence.I believe the best way to quantify homogeneity for my purposes is with simple matching coefficient. A straightforward greedy algorithm to define the subsets appears to be $O(n^2)$, but I'm not convinced this finds the optimal result. Is there proof either way? Is there another algorithm I should consider? Another homogeneity metric?The resulting algorithm needs to be polynomial time.
|
How can I divide a set of strings into subsets of fixed size with maximal homogeneity?
|
greedy algorithms;string metrics
| null |
_softwareengineering.238173
|
If I use Spring Data Neo4j to develop a software, and I want to publish it for commercial use with charging, does there exist any license issue?I survey many posts about the license issue of Neo4j and Spring Data Neo4j. It seems Neo4j has two versions, community and enterprise, respectively. The Community version is GPL-3.0, and the enterprise version is AGPL-3.0. Spring Data Neo4j is Apache License-2.0.The role of spring data neo4j in my software:1.It is only part of my software to deal with storing relationship and searching data.2.I will combine it with MongoDB or DB2.
|
License issue of Spring Data Neo4j?
|
licensing;gpl;apache license
| null |
_unix.111501
|
I'm running Arch ARM on a PogoPlug and want to execute a file every hour, the file when call directly runs fine (it is executable), for testing the file/etc/cron.hourly/crontestcontains#!/bin/bashdate >> /root/logFirst I copied it to /etc/cron.daily but it wouldn't run, run-parts --test lists it as valid but nothing shows in the log file, then I created a crontab:*/5 * * * * /etc/cron.hourly/crontestTo run it every 5 minutes while monitoring the logfile, it doesn't fire.This is /etc/cron.d/0hourly# Run the hourly jobsSHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root01 * * * * root run-parts /etc/cron.hourlyandjournalctl -u croniejust returns-- Logs begin at Wed 1969-12-31 17:00:03 MST, end at Tue 2014-01-28 10:14:12 MST. --So even though the PogoPlug doesn't have a rtc it has the correct time via ntp. What else can I do to debug cron / get it to run?I'm tempted to just write a bash script that loops and sleeps x amount of seconds, but I'd rather figure this one out :-)
|
Neither crontab nor anacron is running, how to debug?
|
linux;bash;cron;arm
|
You need to make sure cronie is started. You can do so with the following command:systemctl start cronieThis command will enable cronie to start on boot:systemctl enable cronie
|
_softwareengineering.344737
|
I have general parallel programming question.Suppose there is a directed graph with cycles. Lets assume that each node has fairly small amount of incoming edges ~ from 0 to 20 and potentially pretty big amount of outgoing edges ~ from 0 to 500. Lets say that each node is a function that getting all incoming edges as input parameters, calculates result and then if calculated result differs from previous result of this function it will need to invoke recalculation of all the functions on the outgoing edges.I need functions to be calculated pretty much in waves from changed function to all that connected to it in the first wave and then all functions connected to functions of first wave and so on.Currently I have this done sequentially, with two lists: current wave with all functions that is calculating now and next wave that is going to be calculated in the next wave. Everything is working correctly, but I want to make it parallel - to be calculated on all available cores.The problem I am facing is actually each function is very simple and so it gets calculated very fast and so time of calculation is comparable with time to adding to the next wave. As a result, running on 4 cores is slower that sequential code.Is there a parallel algorithm that can deal with such graphs?
|
Parallel algorithm: calculations on graph
|
parallelism;parallel programming
| null |
_unix.154324
|
I have recently installed Cent OS7. Its looks very nice at first.But soon realized it has a horrible multimedia support. Its own player cannot install the codecs it requires, which was much easier in Debian OS.When I tried to manually install VLC using yum install vlc, it just showed a list of dependency problems: --> Finished Dependency ResolutionError: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates) Requires: libopenjpeg.so.2()(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates) Requires: libgnutls.so.26()(64bit)Error: Package: libcddb-1.3.2-8.el6.x86_64 (linuxtech-release) Requires: libcdio.so.10()(64bit)Error: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates) Requires: libgme.so.0()(64bit)Error: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates) Requires: libdc1394.so.22()(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates) Requires: libcdio_paranoia.so.0()(64bit) Available: libcdio-0.77-1.el5.rf.x86_64 (rpmforge) libcdio_paranoia.so.0()(64bit) Installed: libcdio-0.92-1.el7.x86_64 (@anaconda) Not foundError: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates) Requires: libudev.so.0()(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates) Requires: libcdio_cdda.so.0(CDIO_CDDA_0)(64bit) Available: libcdio-0.77-1.el5.rf.x86_64 (rpmforge) libcdio_cdda.so.0(CDIO_CDDA_0)(64bit) Installed: libcdio-0.92-1.el7.x86_64 (@anaconda) Not foundError: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates) Requires: libgnutls.so.26(GNUTLS_1_4)(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates) Requires: libgnutls.so.26(GNUTLS_1_4)(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates) Requires: libcelt0.so.1()(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates) Requires: libcdio_paranoia.so.0(CDIO_PARANOIA_0)(64bit) Available: libcdio-0.77-1.el5.rf.x86_64 (rpmforge) libcdio_paranoia.so.0(CDIO_PARANOIA_0)(64bit) Installed: libcdio-0.92-1.el7.x86_64 (@anaconda) Not foundError: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates) Requires: libproxy.so.0()(64bit)Error: Package: libcddb-1.3.2-8.el6.x86_64 (linuxtech-release) Requires: libcdio.so.10(CDIO_10)(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates) Requires: libcdio_cdda.so.0()(64bit) Available: libcdio-0.77-1.el5.rf.x86_64 (rpmforge) libcdio_cdda.so.0()(64bit) Installed: libcdio-0.92-1.el7.x86_64 (@anaconda) Not foundError: Package: librtmp-2.3-3.el6.x86_64 (linuxtech-release) Requires: libgnutls.so.26(GNUTLS_1_4)(64bit)Error: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates) Requires: libtiger.so.5()(64bit)Error: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates) Requires: libmtp.so.8()(64bit) Available: libmtp-0.3.7-1.el5.rf.x86_64 (rpmforge) libmtp.so.8()(64bit) Installed: libmtp-1.1.6-3.el7.x86_64 (@anaconda) ~libmtp.so.9()(64bit)Error: Package: ffmpeg-libs-0.10.11-1.el6.x86_64 (rpmfusion-free-updates) Requires: libdc1394.so.22()(64bit)Error: Package: librtmp-2.3-3.el6.x86_64 (linuxtech-release) Requires: libgnutls.so.26()(64bit)Error: Package: vlc-core-2.0.10-1.el6.x86_64 (rpmfusion-free-updates) Requires: libgnutls.so.26()(64bit) You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigestIs it possible at all to install it in Cent OS 7?So far I can only find some solutions for Cent OS 6 or lower, which is hardly helpful for me.
|
What multimedia support should I use in centOS 7
|
linux;vlc;centos
|
Your yum repos were not configured correctly as el6 packages were showing up. Try removing rpmfusion-free-updates, linuxtech-release, and rpmforge. You can add Epel7 and Atrpms el7 repos to solve the problem.
|
_computergraphics.1901
|
I'm working on a shadertoy snake game, using the new multi pass rendering abilities to save game state between frames.I'm using raytracing to render the board (an AABB), and am planning on using spheres to render sections of the snake's body.The game board is a 16x16 grid and each grid can either have a sphere there (a segment of the snake's body) or not. Snake body segments don't move, they are just either there on the grid or not. When the snake moves, a new sphere appears in the front and an old sphere disappears from the back.The problem I'm trying to solve is how to render the snake body spheres.For instance, a naive approach would be to store a 16x16 grid in pixels specifying whether there was a snake body in that grid cell or not.I would then do a ray vs sphere check for up to 256 different spheres within my pixel shader, which seems like a no go.Another method might be to figure out where the ray begins and ends on the game board (when it's between the high and low height values of where the spheres are) and then use something like bressenham line algorithm to go from the start to the end of the line the ray takes on the board, and check only the grid cells that the ray hits.The problem there is that it requires a dynamic loop.Maybe a more practical solution would be to make the camera have a nearly top down view and where the ray enters the playable game world, test any sphere in the cell it hits as well as the 8 neighboring cells.I'm betting there are some much better solutions that I'm not thinking of.Does anyone know of any interesting techniques or creative solutions?Thanks!Edit: here is an older version of this game i made, which was CPU / software rendered, to give an idea of what I'm planning.
|
Methods for grid traversal in a glsl pixel shader?
|
raytracing;real time;glsl;pixel shader
|
why not building a bounding box (or spheres) hierarchy ?(but for a shadertoy implementation, the lack of dynamic loop length might spoil the gain ).
|
_cstheory.3452
|
Many complexity classes defined with Turing machines have definitions in terms of uniform circuits. For example, P can also be defined using uniform polynomial size circuits, and similarly BPP, NP, BQP, etc. can be defined with uniform circuits.So is there a circuit-based definition of L?An obvious idea would be to allow polynomial size circuits with some depth limitation, but this turn out to define the NC hierarchy.I was thinking about this question a long time ago, but didn't find an answer. If I remember correctly, my motivation was to understand what the quantum analog of L would look like.
|
Does L have a definition in terms of circuits?
|
cc.complexity theory;complexity classes;circuit complexity
|
Well, $L = SC^1$, where $SC^1$ is the class of languages computed by polynomial size circuits of $O(\log n)$ width.As for $NL$, it could be characterized as the class languages computed by polynomial size skew circuits (which in some sense is just another way of saying nondeterministic branching programs).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.