id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.162039
What options do I have if I'd like to install manjaro on my usb-stick without having to reboot my maschine.In that manner I can do my work while Linux installes. And when the installation is finished I'd boot that OS on the Stick with VirtualBox as I found a howto here. I need to have that OS on a stick, so that I can use to boot that OS on other machines to fix stuff.
Install linux on a usb without rebooting
system installation;live usb;manjaro
null
_webmaster.54118
My client's website has just reached spot 1 for the most valuable keyword. We acquired the domain that was at #1 spot. It's a keyword domain (targetkeyword.tld). Just wondering what would be the best way to make use of it. A permanent redirect or a single page that hyperlinks to the brand website?Should I be concerned about anything negative associated to this keyword domain (poor backlinks and the fact that this website was down for about one month)?
How to utilise a newly acquired keyword domain to contribute to an already existing healthy website?
seo;domains
A domain name that is just the keywords you optimize for is generally called an Exact Match Domain (EMD). In September 2012, Google launched an algorithm that prevents EMDs from ranking very highly (or at least, not as highly as they once did).Your choices for an EMD are:Use for your site and redirect your old domain name to it.Use your existing brand URL, and redirect the EMD to it.Create a new site on the EMD.Google seems to love sites that build brands and value EMD much less than it used to. Given that, I would be very wary of trying for option #1.Option #2 would be good if the EMD gets type in traffic. Otherwise it won't get additional traffic.Option #3 could be good as long as you don't duplicate content between the sites, but it is a significant amount of work.
_vi.11901
A lot of times, I end up accidentally closing a file with :wq when I only want to do :w. Since I work with multiple tabs and windows, the buffer is still there and I can open it with :ls followed by :b <number>. However, my previous changes are lost and I cannot undo anymore. Is there any way to set up vim so that it remembers the undo tree of unclosed buffers?If that is not possible, a way to make vim confirm before quitting on :wq is also OK.
Any way to retrieve lost undo tree after closing window (but buffer is still open)
undo redo;quit
What is most likely happening in your case is that the buffer is automatically unloaded because you don't have the option 'hidden' enabled.This option not only resolves the issue you reported, but is also required when you want to navigate between buffers without being forced to write the changes before doing so. Personally, I can't imagine working in Vim without it.
_codereview.147823
I wrote a bit of code that takes a file, justifies the text and writes to another file.It uses a DP approach to minimise a badness metric, which is the amount of undershoot of the line length, cubed (see my answer below, the badness function isn't quite right if there is an overshoot, the badness should be inf - I believe this is how LaTeX justifies its text).I encapsulated it in a class (which is the bit I'm least confident about). Be careful running it on big files, because I think it's got a pretty nasty complexity (\$O(n^2)\$ maybe).class justifyText: def __init__(self, inFileName, outFileName, pageWidth): with open(inFileName, r) as fp: self.words = [word for line in fp for word in line.split()] self.outFileName = outFileName self.pageWidth = pageWidth self.memo = {} self.breakPointTrack = {} self.n = len(self.words) def badness(self, i, j): totalWidth = 0; for word in self.words[i:j]: totalWidth += len(word) return abs((self.pageWidth - totalWidth)**3) def minBadness(self, i): if i in self.memo: return self.memo[i] if i == self.n: f = 0 j_min = self.n else: f = None for j in range(i + 1, self.n + 1): temp = self.minBadness(j) + self.badness(i, j) if (f is None) or (temp < f): f = temp j_min = j self.memo[i] = f self.breakPointTrack[i] = j_min return f def justify(self): self.minBadness(0) fOut = open(self.outFileName, w) brk = 0 while brk < self.n: start = brk brk = self.breakPointTrack[brk] line = .join(self.words[start:brk]) + \n fOut.write(line) fOut.close()test = justifyText(test.txt, out.txt, 80)test.justify()Is this a standard way to implement a DP program? I know that global variables are evil, so I was mainly trying to avoid my memo etc. being that.
Justify text from a file using a LaTeX method
python;beginner;algorithm;formatting;dynamic programming
You should have a look at Python's official style-guide, PEP8. One of its recommendations is to use PascalCase for class names and lower_case for function and variable names.Since you read all words into memory anyway, you can just write:with open(in_file_name) as fp: self.words = fp.read().split()This is because split splits by default on all whitespace (so both space and newlines). Also note that the default behaviour of open is to open a file in read mode, so r is also not needed here.Caching (or memoization) of a functions return value is best done with a decorator. This way you avoid interleaving the actual implementation of the function with the caching. One example could be:import functoolsdef memoize_method(func): cache = func.cache = {} @functools.wraps(func) def wrapper(self, n): if n not in cache: cache[n] = func(self, n) return cache[n] return wrapperclass JustifyText: ... @memoize_method def min_badness(self, i): if i == self.n: f, j_min = 0, self.n else: f, j_min = min((self.min_badness(j) + self.badness(i, j), j) for j in range(i + 1, self.n + 1)) self.break_point_track[i] = j_min return fYour badness function can be simplified by using sum, similar to how I used min above:def badness(self, start, end): total_width = sum(len(word) for word in self.words[start:end]) return abs((self.page_width - total_width)**3)While it might be your most used use case, writing the output to a file prevents anyone from using this module in any other way. It would be better if justify just returned (even better and simpler: yielded) the justified text and writing to a file is left to the user or a dedicated method using justify internally.def justify(self): self.min_badness(0) # no-op or to populate the cache? brk = 0 while brk < self.n: start, brk = brk, self.break_point_track[brk] yield .join(self.words[start:brk]) + \ndef write(self): with open(self.out_file_name, w) as f_out: f_out.writelines(self.justify())I'm not exactly sure why you have a lone self.min_badness(0) in justify. is it just to populate the cache with the value for zero? If so, this is worth to put a comment here, because otherwise you might accidentally delete it.
_cs.30795
Given that $L_2$ is regular and infinite and $L_1 \cdot L_2$ is regular, then $L_1$ is also regular.I need some help on getting started on proving this is the case.My intuition is that if $L_1 \cdot L_2$ is regular there exists a DFA for it, in which case you can just remove the states that correspond to the $L_2$ part of the DFA and you are left with a DFA that recognizes $L_1$.
If both the concatenation of two languages and the second half are regular, is the first too?
formal languages;regular languages;closure properties
null
_codereview.128469
This code is a proof-of-concept which I intend to convert into a static utility / helper class. I'm looking at this review from a structure or performance viewpoint. Small detail such as whether it prints or returns something, or whether the output is well-formatted, don't concern me too much.The purpose of this code sample is:Given an input of an arbitrary set of strings, such as A B C, return all the sets of permutations or combinations of these, where each is used only once; in this example, it would return (or print) the following 7 sets:ABC (Use all 3)AB, BC, AC (Combinations of pairs)A, B, C (Each item individually)The sequence of each doesn't matter (They happen to be alphabetical in the output)If we have AB we don't also need BA (These can be permutated later by such libraries as Guava's Collections2.permutations()import java.util.Arrays;import java.util.Set;import java.util.TreeSet;public class PermutationTest { private String[] strings; private int t; private int[] i; private Set<String> unique = new TreeSet<>(); private PermutationTest(int t, String... strings) { this.strings = strings; this.t = t; this.i = new int[t]; for(int x = 0 ; x < this.t ; x++ ) { i[x] = x; } } private boolean permutate() { return permutate(this.t - 1); } private boolean permutate(int c) { if(c < 0) { return false; } this.i[c]++; int m = this.strings.length - (this.t - c - 1); if(this.i[c] >= m) { if(permutate(c - 1)) { this.i[c] = this.i[c - 1] + 1; } else { return false; } } return true; } private void print() { System.out.println(Arrays.toString(this.i)); StringBuilder sb = new StringBuilder(); for(int x = 0 ; x < this.t ; x++ ) { sb.append(this.strings[i[x]]); } this.unique.add(sb.toString()); } public static void main(String[] args) { String[] strings = (args.length > 0) ? args : new String[] {A, B, C}; Set<String> total = new TreeSet<>(); for(int z = 0 ; z < strings.length ; z++ ) { total.addAll(outer(z + 1, strings)); } System.out.println(total.size()); System.out.println(total); } private static Set<String> outer(int z, String[] strings) { PermutationTest p = new PermutationTest(z, strings); int c = 0; boolean running = true; while(running && c < 200) { p.print(); running = p.permutate(); c++; } System.out.println(String.format(Total %d permutation count, c)); System.out.println(String.format(Total %d unique strings, p.unique.size())); System.out.println(p.unique); return p.unique; }}
Give the variable length permutations (combinations) of a set of strings
java;performance;algorithm;combinatorics
null
_cstheory.7431
Given a set of pairs of words $P = \{(\alpha_1, \beta_1), \dots, (\alpha_n, \beta_n)\} \subseteq \Sigma^*\times\Sigma^*$, the Post Correspondence Problem (PCP) is to decide wether or not there are indices $i_1, \dots, i_k \in \{1\dots n\}$ such that $\alpha_{i_1}\cdot \dots \cdot \alpha_{i_k} = \beta_{i_1}\cdot \dots \cdot \beta_{i_k}$.It is well known that PCP is not computable in any Turing-equivalent machine model. Usually, this fact is proven by reducing the Halting Problem (HP) to PCP, i.e. describing how to create a PCP instance $\Pi$ for an arbitrary Turing machine $M$ and an input $x$ such that $\Pi$ has a solution if and only if $M$ terminates on $x$.Arguably, undecidability of PCP is more useful than of HP because it is removed from the notion of computation itself and therefore might be understood without having to read up on Turing machines (or equivalent models) first. Also, it is a more natural choice for many reduction proofs for not computation-related problems, e.g. in formal language theory.It seems only fair to ask: Is there a proof for undecidability of PCP that does not employ reduction to HP (or similar problems)?Note that I want to exclude chains of reductions that end up at HP in the end. Having such an independent proof might open up new ways for students and laymen to understand the underlying issues. Failing that, are there reasons for that lack? Do we need the kind of self-applicability we employ when proving HP not to be computable?PS: I was unsure wether or not this question should go here or rather onto math.SE. As the proper place might depend on the level of answers, I went with the specialist community.
Prove Post Correspondence Problem Non-Recursive Without Reduction
reference request;computability;post correspondence
null
_softwareengineering.159501
What exactly does the Model part mean? Is it the same as the domain model? I've read that it's a map, but I'm having a hard time understanding the concept.
What Exactly is a Model Relative to the ModelAndView Class in Spring
java;spring
I've always treated it as a View Model as opposed to a pure Domain Model, the ModelAndView class name lends itself to that distinction as well as the use of a Map to drop various bits of model data in for viewing purposes.
_codereview.143889
This code is supposed to search for a specific key in a object or an array or a mix between both. Is there anything I can improve? function getAllObjectsIn(key, data, casesensitive){ var returns = []; var searchForInner = function (key, data, returnParameter, casesensitive){ if(typeof(data) === 'object'){ for (var i in Object.keys(data)){ if(!(casesensitive)){ var searchTerm = Object.keys(data)[i].toLowerCase(); var key = key.toLowerCase(); }; if(searchTerm === key){ returns.push(data[Object.keys(data)[i]]); } else if (typeof(data[Object.keys(data)[i]]) === 'object'){ searchForInner(key,data[Object.keys(data)[i]],returnParameter); }; }; }; }; searchForInner(key,data,returns,casesensitive); return(returns);};
Search in a JSON structure after a key
javascript;object oriented;array;search
Your function name is not very meaningful in that;a) there is nothing to say values returned in the array will be objects (since you are just grabbing whatever data is stored for the key), andb) you are not getting all data items at all: in fact you are performing a specific key search.Perhaps something like recursiveKeySearch() or similar will makes more sense.I also question why you would include case insensitive search behavior against keys in the first place; that is contrary to the expected behavior of key/property names in JavaScript: the potential need to do case-insensitive key/property names evaluations might suggest bad code in other areas of the application where key/property cases are not being applied consistently.Don't put in hacks in your code which can make your code perform in unexpected manners.If you remove that requirement, you have no need to inspect object.keys anymore and can just directly check if the key exists, greatly simplifying your code.Your code does not really do anything to validate that the data being passed to it is sensible to work with.I am guessing that you are really wanting to do is require that data be either an Array specifically, or any other type of object in the Object prototype chain; you have some edge cases you are missing here like typeof(data) === 'object' returning true if data is null.When those edge cases happen (which could be often if you are iterating over arbitrary objects) I would think you would still need to handle them within your code.Do you truly wish for you function to be able to search against numeric keys (i.e. for case of Array object)?This might seem like a little bit odd of an approach based on JavaScript's inability to actually have numeric keys on an object (they will be converted to strings); this really means that if an integer key is passed, you can only meaningfully search in Arrays, whereas if a string key is passed, you can only meaningfully search in Objects: I personally would expect that this function would not be meaningful for searching numeric Array keys, as typically these keys only indicate order not some meaningful value for use in lookup.Thus you might consider handling Arrays differently - just iterating and recursing into them, but not actually evaluating them for matches.If you need to deep search for numeric key matches, perhaps go with another function altogether.The design of your recursion is a little odd.Why the need for an inner function?Your current code approach stops recursion for case where there is a key match; is this really desired?I would think expected behavior would be to deep search all values in all keys regardless as to whether the key matched the criteria.As it stands, you do not recurse into the value for any cases where you have a key match.You have a few errors in logic around your case sensitivity handling;In the case sensitive case, the searchTerm variable would have never been populated, thus your key comparison will always fail.In the case-insensitive logic path, you overwrite your key value, potentially breaking your code, as you are now potentially recursing and going through subsequent iterations with a totally new key value.This may not actually make a difference with code as written, but I would think you want key to be consistent throughout recursion.Also, if you truly want to support integer key values, these make no sense with cases sensitivity, and you would in fact significantly alter the key you are searching for by casting it to string when performing toLowerCase() on it.Per my earlier comment around need for case insensitive search, here is a good example for how you have introduced three potential bugs here just because of added complexity on supporting this use case, and not really implementing in best manner.You would be better off setting Object.keys(data) to a variable, so you don't have to keep extracting the keys every time you want to act against them.You can obviously avoid this altogether as you should probably simply just replaceThis:for (var i in Object.keys(data)){with this:for (var dataKey in data) {as there is no reason you need to know the (actually meaningless and technically unpredictable) index number around an array created from the key of the data object.Object properties in JavaScript do not have a guaranteed order, so it seems inappropriate to try to rely on index positions based on this behavior.Just work with the property names themselves.Putting it togetherIf you looked to refactor based on the considerations mentioned above, you might end up with something like:function recursiveKeySearch(key, data) { // not shown - perhaps validate key as non-zero length string // Handle null edge case. if(data === null) { // nothing to do here return []; } // handle case of non-object, which will not be searched if(data !== Object(data)) { return []; } var results = []; // Handle array which we just traverse and recurse. if(data.constructor === Array) { for (var i = 0, len = data.length; i < len; i++) { results = results.concat(recursiveKeySearch(key, data[i])); } return results; } // We know we have an general object to work with now. // Now we need to iterate keys for (var dataKey in data) { if (key === dataKey) { // we found a match results.push(data[key]); } // now recurse into value at key results = results.concat(recursiveKeySearch(key, data[dataKey])); } return results;}Or, if you REALLY need to add a case insensitive search:function recursiveKeySearch(key, data, caseSensitive = true) { // not shown - perhaps validate key as non-zero length string // not shown - perhaps validate caseSensitive as boolean // Handle null edge case. if(data === null) { // nothing to do here return []; } // handle case of non-object, which will not be searched if(data !== Object(data)) { return []; } var results = []; // determine 'key' value to be used for comparison var comparisonKey = key; if (caseSensitive === false) { comparisonKey = key.toLowerCase(); } // Handle array which we just traverse and recurse. if(data.constructor === Array) { for (var i = 0, len = data.length; i < len; i++) { results = results.concat(recursiveKeySearch(key, data[i], caseSensitive)); } return results; } // We know we have an general object to work with now. // Now we need to iterate keys for (var dataKey in data) { var isMatch = false; if(caseSensitive === false) { isMatch = (comparisonKey === dataKey.toLowerCase()); } else { isMatch = (comparisonKey === dataKey); } if(isMatch) { results.push(data[dataKey]); } // now recurse into value at key results = results.concat(recursiveKeySearch(key, data[dataKey], caseSensitive)); } return results;}
_cs.37904
$$T=\{\langle M\rangle \mid |L(M)| =1 \text{ or } |L(M)| >2\}$$I started with Rice's theorem (come up with an example where $|L(M)| = 2$) to see that $T$ was undecidable. Then I figured out $\bar{T}$ was unrecognizable, because $H =\{\langle M \rangle \mid M\text{ halts on the empty string} \}$ has a mapping-reduction to $T$, and $H$ is not co-recognizable, so $T$ is not co-recognizable.Now I'm stuck. I tried mapping-reductions from $H$, $E = \{\langle M \rangle \mid M \text{ doesn't accept anything} \}$ and $F = \{ \langle M \rangle \mid L(M) \text{ is finite} \}$.What's a good set to try and reduce from (or reduce to)? Am I right that $T$ is unrecognizable?
Is $T=\{\langle M\rangle \mid |L(M)| =1 \text{ or } |L(M)| >2\}$ recognizable?
computability;turing machines;semi decidability
null
_unix.77080
I have an Atmel 97SC3201 in my computer and set the following in the kernel:CONFIG_HW_RANDOM_TPMCONFIG_TCG_TPMCONFIG_TCG_ATMEL/dev has tpm0 and hwrng, but running this command returns the following:head -c 2 /dev/hwrngoutput:head: error reading /dev/hwrng: Input/output errorIn dmesg these messages appear:tpm_atmel tpm_atmel: A TPM error (2048) occurred attempting get randomadditional tries yield these messages:tpm_atmel tpm_atmel: A TPM error (6) occurred attempting get randomAny ideas why this fails or better, how to get it working?
Why doesn't `head -c 2 /dev/hwrng` work?
linux;devices;random;tpm
null
_softwareengineering.333853
After some serious quality problems in the last year, my company has recently introduced code reviews. The code review process was quickly introduced, without guidelines or any kind of checklist.Another developer and I where chosen to review all changes made to the systems, before they are merged into the trunk. We were also chosen as Technical Lead. This means we are responsible for code quality, but we don't have any authority to implement changes in the process, reassign developers, or hold back projects.Technically we can deny the merge, giving it back to development. In reality this ends almost always with our boss demanding that it be shipped on time.Our manager is an MBA who is mostly concerned with creating a schedule of upcoming projects. While he is trying, he has almost no idea what our software does from a business point of view, and is struggling to understand even the most basic customer demands without explanation from a developer.Currently development is done in development branches in SVN, after the developer thinks he is ready, he reassigns the ticket in our ticketing system to our manager. The manager then assigns it to us.The code reviews have lead to some tensions within our team. Especially some of the older members question the changes (I.e. We always did it like this or Why should the method have a sensible name, I know what it does?).After the first few weeks my colleague started to let things slide, to not cause trouble with the co-workers (she told me herself, that after a bug report was filed by a customer, that she knew of the bug, but feared that the developer would be mad at her for pointing it out).I, on the other hand, am now known for being an ass for pointing out problems with the committed code.I don't think that my standards are too high.My checklist at the moment is: The code will compile.There is at least one way the code will work.The code will work with most normal cases.The code will work with most edge cases. The code will throw reasonable exception if inserted data is not valid.But I fully accept the responsibility of the way I give feedback. I'm already giving actionable points explaining why something should be changed, sometimes even just asking why something was implemented in a specific way. When I think it is bad, I point out that I would have developed it in another way.What I'm lacking is the ability to find something to point out as good. I read that one should try to sandwich bad news in good news.But I'm having a hard time to find something that is good. Hey this time you actually committed everything you did is more condescending than nice or helpful.Example Code ReviewHey Joe,I have some questions about your changes in the Library\ACME\ExtractOrderMail Class.I didn't understand why you marked TempFilesToDelete as static? At the moment a second call to GetMails would throw an exception, because you add Files to it but never remove them, after you deleted them. I know that the the function is just called once per run, but in the future this might change. Could you just make it an instance variable, then we could have multiple objects in parallel.... (Some other points that don't work)Minor points: Why does GetErrorMailBody take an Exception as Parameter? Did I miss something? You are not throwing the exception, you just pass it along and call ToString. Why is that?SaveAndSend Isn't a good name for the Method. This Method sends error mails if the processing of a mail went wrong. Could you rename it to SendErrorMail or something similar?Please don't just comment old code, delete it outright. We still have it in subversion.
How to find positive things in a code review?
code reviews
How to find positive things in a code review?After some serious quality problems in the last year, my company has recently introduced code reviews. Great, you have a real opportunity to create value for your firm.After the first few weeks my colleague started to let things slide, to not cause trouble with the co-workers (she told me herself, that after a bugreport was filed by a customer, that she knew of the bug, but feared that the developer would be mad at her for pointing it out).Your coworker should not be doing code review if she can't handle telling developers what's wrong with their code. It's your job to find problems and get them fixed before they affect customers.Likewise, a developer who intimidates coworkers is asking to be fired. I've felt intimidated after a code-review - I told my boss, and it was handled. Also, I like my job, so I kept up the feedback, positive and negative. As a reviewer, that's on me, not anyone else.I, on the other hand, am now known for being an ass for pointing out problems with the committed code.Well, that's unfortunate, you say you're being tactful. You can find more to praise, if you have more to look for.Critique the code, not the authorYou give an example:I have some questions about your changes inAvoid using the words you and your, say, the changes instead. Did I miss something? [...] Why is that?Don't add rhetorical flourishes to your critiques. Don't make jokes, either. There's a rule I've heard, If it makes you feel good to say, don't say it, it's no good. Maybe you're buffing your own ego at someone else's expense. Keep it to just the facts. Raise the bar by giving positive feedbackIt raises the bar to praise your fellow developers when they meet higher standards. So that means the question,How to find positive things in a code review?is a good one, and worth addressing.You can point out where the code meets ideals of higher level coding practices. Look for them to follow best practices, and to keep raising the bar. After the easier ideals become expected of everyone, you'll want to stop praising these and look for even better coding practices for praise.Language specific best practicesIf the language supports documentation in code, namespaces, object-oriented or functional programming features, you can call those out and congratulate the author on using them where appropriate. These matters usually fall under style-guides:Does it meet in-house language style guide standards?Does it meet the most authoritative style guide for the language (which is probably more strict than in-house - and thus still compliant with the in-house style)?Generic best practicesYou could find points to praise on generic coding principles, under various paradigms. For example, do they have good unittests? Do the unittests cover most of the code? Look for:unit tests that test only the subject functionality - mocking expensive functionality that is not intended to be tested.high levels of code coverage, with complete testing of APIs and semantically public functionality.acceptance tests and smoke tests that test end-to-end functionality, including functionality that is mocked for unit tests.good naming, canonical data points so code is DRY (Don't Repeat Yourself), no magic strings or numbers.variable naming so well done that comments are largely redundant.cleanups, objective improvements (without tradeoffs), and appropriate refactorings that reduce lines of code and technical debt without making the code completely foreign to the original writers.Functional ProgrammingIf the language is functional, or supports the functional paradigm, look for these ideals:avoiding globals and global stateusing closures and partial functionssmall functions with readable, correct, and descriptive namessingle exit points, minimizing number of argumentsObject Oriented Programming (OOP)If the language supports OOP, you can praise the appropriate usage of these features:encapsulation - provides a cleanly defined and small public interface, and hides the details.inheritance - code reused appropriately, perhaps through mixins.polymorphism - interfaces are defined, perhaps abstract base classes, functions written to support parametric polymorphism.under OOP, there are also SOLID principles (maybe some redundancy to OOP features): single responsibility - each object has one stakeholder/owneropen/closed - not modifying the interface of established objectsLiskov substitution - subclasses can be substituted for instances of parentsinterface segregation - interfaces provided by composition, perhaps mixinsdependency inversion - interfaces defined - polymorphism...Unix programming principles:Unix principles are modularity, clarity, composition, separation, simplicity, parsimony, transparency, robustness, representation, least surprise, silence, repair, economy, generation, optimization, diversity, and extensibility.In general, these principles can be applied under many paradigms.Your criteriaThese are far too trivial - I would feel condescended to if praised for this: The code will compile.There is at least one way the code will work.The code will work with most normal cases.On the other hand, these are fairly high praise, considering what you seem to be dealing with, and I wouldn't hesitate to praise developers for doing this:The code will work with most edge cases. The code will throw reasonable exception if inserted data is not valid.Writing down rules for passing code review?That's a great idea in theory, however, while I wouldn't usually reject code for bad naming, I've seen naming so bad that I would reject the code with instructions to fix it. You need to be able to reject the code for any reason.The only rule I can think of for rejecting code is there's nothing so egregious that I would keep it out of production. A really bad name is something that I would be willing to keep out of production - but you can't make that a rule.ConclusionYou can praise best practices being followed under multiple paradigms, and probably under all of them, if the language supports them.
_webapps.85726
I own a domain but use Gmail as my email account. I have 4 addresses as email aliases that forward messages to my Gmail account. Recently I stopped receiving them, including to my spam folder. I verified with my host that the emails are being received and sent.Does anybody have any ideas to help fix this issue?
Emails to an alias forwarded to Gmail account not received
gmail
null
_webmaster.83902
I'm using WordPress and moved to https recently. I've had some issues since with the domain not redirecting properly.Currently it works OK but https://example.com is not redirecting to https://www.example.com.I have tried a lot of ways but I have not been successful so far.Here is my htaccess:RewriteEngine On RewriteCond %{HTTP_HOST} ^example.co.uk [NC]RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.example.co.uk/$1 [R,L]# BEGIN WordPress<IfModule mod_rewrite.c>RewriteEngine OnRewriteBase /RewriteRule ^index\.php$ - [L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule . /index.php [L]</IfModule># END WordPress# BEGIN rlrssslReallySimpleSSL rsssl_version[2.1.12]# END rlrssslReallySimpleSSL<IfModule mod_expires.c> ExpiresActive on ExpiresByType image/jpg access plus 1 month ExpiresByType image/jpeg access plus 1 month ExpiresByType image/gif access plus 1 month ExpiresByType image/png access plus 1 month</IfModule>
Wordpress https://example.com not redirecting to https://www.example.com htaccess
htaccess;wordpress;no www
null
_unix.296364
I have created a Live USB of Fedora 22 with rawrite32. It works fine, but:How can I save permanently my files? If I download a package, let's say git, how can I maintain it permanently? How can I change the keyboard (in the live workstation there is no layout option)? Is it possible to remove the install Fedora application? It is possible to run Fedora immediately without clickingtry Fedora?
Fedora live USB with persistent storage
fedora
null
_unix.204346
My linux distro is Arch Linux. I first noticed this error when trying to send emails using the PHP mail() function. Testing with a simple mail-test.php file with the mail() function sends the email when called from the command line, but will not send when using http://localhost/mail-test.php. I get the same error both times, but only using the command line sends the email.I get the error:PHP Startup: Unable to load dynamic library '/usr/lib/php/modules/libphp5.so' - /usr/lib/php/modules/libphp5.so: cannot open shared object file: No such file or directory at Unknown#0Using ls /usr/lib/php/modules shows the file does not exist, and searching the system results in /usr/lib/httpd/modules/libphp5.so existing.php-apache is installed and apache serves php sites just fine. (tested with a test php file containing <?php phpinfo(); ?>)I can't seem to find the cause of this error though. Any help is appreciated, thanks!
I keep getting error: PHP Startup - libphp5.so missing? PHP seems to run fine with Apache
php5
null
_unix.354377
For the purpose of a forensic mission, we must get a docker image without using the famous export from a docker command.Does copy and paste of the folder /var/lib/docker/containers in another server allow us to retrieve information without any corrupted data?Thanks.
Forensic - How to get a docker image without export command
docker;forensics
null
_unix.140397
This question is similar toCan I configure my shell to print STDERR and STDOUT in different colors?But I am looking for a solution that will allow me to change both STDOUT and STDERR to ONE color. I am not trying to set different color for STDOUT and STDERR, as this is problematic and may create problems, mentioned in the answer from the link above.I apologize, as I don't know much about Unix and Linux. I am looking for a solution that can allow me to add couple lines to my .bashrc or .bash_profile and permanently change the color of STDOUT and STDERR.
How to permanently change both STDOUT and STDERR color to grey?
shell;terminal;osx;colors
null
_codereview.85112
I've got an object $contest which is a Symfony entity that has some other entities assigned. I can get them by $content->getEntries();. That will return an object with the lazyloaded db objects. I need to display them in a random order.$tempEntries = $contest->getEntries();$entries = array();if (count($tempEntries)) { foreach ($tempEntries as $temp) { $entries[] = $temp; } shuffle($entries);}This is the code I use currently. I loop through all elements (if there are any) and then shuffle them. I feel like the looping through them is a wast of resources.Any advice on how to improve this?
Shuffle Symfony entities
php;random;php5;shuffle;symfony2
You can use native shuffling (if you don't use KnpPaginator):$entries = $contest->getEntries()->toArray();shuffle($entries);Also if you need all entities you can write:$entriesCollection = $contest->getEntries();if ($entriesCollection instanceof PersistentCollection) { $entriesCollection->initialize();}$entries = $entriesCollection->toArray();shuffle($entries);Alternatively you can dig to @ORM\OrderBy and custom DQL functions to use SQL ORDER BY RAND(). Also this approach would work better with KnpPaginatorIn response to comment:Doctrine mostly uses proxies on your classes instead of directly use them, because of lazy loading and optimization purposes, also doctrine has abstraction over basic arrays implementing own Collection interface that has some useful methods like map, exist and so on. PersistentCollection is proxy (lazy) collection implementing Collection interface it can be returned if you just requested some object from repository and trying to use some field that uses an array of objects so in some cases (like that) it's better to force loading of objects via initialize method (don't worry it won't load them twice). Also all objects requested from repository are not your classes they are just proxies extending your entities and implementing Proxy interface so be careful! If something gone wrong in your database layer try to add the following:if ($yourEntityLoadedFromSomeWhere instanceof Proxy) { $yourEntityLoadedFromSomeWhere->__load();}
_webapps.100672
So far it has been quite the trick trying to figure out how to display the Facebook Marketplace that is easily accessible on the Facebook mobile app:How can this be accessed on the desktop web interface for Facebook?
How to display Facebook Marketplace on web-based interface?
facebook
null
_opensource.1788
The Heartbleed-bug of the software OpenSSL was a security-nightmare for IT around the world. We already know the bug was caused by a patch from a german programmer named Robin Seggelmann. While he surely didn't intend it and is probably very sorry about the problem (and frankly - most programmers would have made the same error), I ask myself if he is in danger of legal repercussions. So, can anything happen to him legally (or any other programmer who makes similar errors in public software)?
Can Heartbleed have legal implications?
law
null
_softwareengineering.287900
Note: this question has been re-written to simplify and generalize the problem. The original is available below.Suppose I created a simple compression scheme for lists of 2-digit numbers. It has 2 modes:Mode 0: The numbers are written as-is, uncompressed.Mode 1: Only the ones digit is written for each number, but the run of numbers must have the same tens digit. This provides 2:1 compression given an infinite list of numbers with the same tens digit.The compressed output string must have only digits 0-9, except for the following 3-character magic values which must be used to switch the mode of compression:*** - switch to mode 0*x* - switch to mode 1, where x is the common tens digit for the numbers that follow. If the tens digit changes, the mode 1 switch needs to be written again, with a different common tens digit.The compressor can switch freely between the two compression modes. So, some two ways that the list of numbers 11 12 13 14 21 22 23 24 can be encoded are:***1112131421222324 (only mode 0, each number written out as-is)*1*1234*2*1234 (only mode 1, only ones digits are written after the mode switches, but mode 1 needed to be started twice, for each diff. tens digit)In the above example, using mode 1 saved 5 characters, but that is not always the case. Encoding the list 15 26 37 48:***15263748*1*5*2*6*3*7*4*8is shorter in mode 0. And obviously, in more complex texts, the modes need to be mixed correctly to provide the shortest result. For example, encoding the list 11 12 21 22 23 24 25 26 18 39:***11122122232425261839 (only mode 0)*1*12*2*123456*1*8*3*9 (only mode 1)*1*12*2*123456***1839 (mode 1 then mode 0)the third encoding provides the shortest result, by properly mixing the encoding modes.Given this specification, an encoder that exhaustively tries mixing the 2 modes while encoding a list of numbers will give the shortest possible compressed result. Obviously, such an encoder takes a ridiculously long time - O(n^n). Trying to think of a more efficient encoder, I got stumped.So my question - is it possible, given the above specification, to write an encoder that would perform better than O(n^n) - that could make decisions in mixing the 2 compression modes without exhaustively trying every single combination? Or is the exhaustive algorithm the only way to get the shortest possible compressed string?Thanks in advance to anyone who shares any insight on this. Note that my goal is to figure out the general compression problem illustrated in my question, rather than to simply find/create an efficient number list compressor.=============================================================================Below is my question as it was phrased originally, in terms of text encoding=============================================================================I thought up a simple UTF-16 text compression scheme that has 2 modes:Mode 0: UTF-16 byte pairs are written as-is, uncompressed.Mode 1: Only the least-significant-byte is written for each character, but the run of characters must have the same most-significant-byte (be from the same unicode block). This provides 2:1 compression given an infinite string of characters from the same unicode block.Assume that it takes 3 bytes to change the mode. Switching the active most-significant-byte (unicode block) on mode 1 likewise takes 3 bytes.Below are some examples of how UTF-16 text can be encoded given this specification. In the examples,a = any character from unicode block 1b = any character from unicode block 2=== = 3-byte value indicating mode 0 is now active--- = 3-byte value indicating mode 1 is now activeSo the text aaaabbbb (4 different characters from unicode block1, and 4 diff. chars. from unicode block 2) can be encoded as===aaaaaaaabbbbbbbb (each letter takes up 2 bytes) -or----aaaa---bbbb (each letter takes up 1 byte, but mode 1 needed to be started twice, because b is from a different block than a)In the above example, using mode 1 saved 5 bytes, but that is not always the case. Encoding the text abab,===aabbaabb---a---b---a---bis shorter in mode 0. And obviously, in more complex texts, the modes need to be mixed correctly to provide the shortest result. For example, encoding the text abbbbbbab,===aabbbbbbbbbbbbaabb---a---bbbbbb---a---b---a---bbbbbb===aabbthe third encoding provides the shortest result, by properly mixing the encoding modes.I wrote an encoder, given this specification, that exhaustively tries mixing the 2 modes while encoding a string and outputs the shortest result. Obviously, this takes a ridiculously long time - O(n^n). Trying to write a more efficient encoder, I got stumped.So my question - is it possible, given the above specification, to write an encoder that would perform better than O(n^n) - that could make decisions in mixing the 2 compression modes without exhaustively trying every single combination? Or is the exhaustive algorithm the only way to get the shortest possible compressed string?Thanks in advance to anyone who shares any insight on this. Note that my goal is to figure out the general compression problem illustrated in my question, rather than to simply find/create an efficient text encoder.
Minimizing compression overhead in a simple compression algorithm
algorithms;compression
null
_unix.383157
In the root users crontab on a Centos 7 server I have the following:30 4 1-7 * * test $(date +\%u) -eq 7 && /usr/bin/needs-restarting -r || /usr/sbin/shutdown -rIt should run every day at 4:30 between the 1st and 7th day of the month, then it tests if the day of the week is Sunday and only then execute the next command to check if a reboot is required, and then reboot if it is. However my server rebooted today (1st Aug 2017) which is a Tuesday. Can anyone explain why?
Cron Job executing on the wrong day
centos;scripting;cron
In a && b || c, command c is executed when either a or b exit with a value other than 0. Consequently, when test $(date +\%u) -eq 7 is false, your server reboots.According to its name /usr/bin/needs-restarting probably returns 0 when the server needs a reboot. Are you sure that this should not be a && b && c instead?Else, try a && { b || c; }
_webmaster.9606
I know that I may just have to link the image to make this happen, but I figured it was worth asking, just in case there's some other semantic markup or tips I could use... I have a site that uses the textual Creative Commons blurb in the footer. The markup is like so: <div class=footer> <!-- snip --> <!-- Creative Commons License --> <a rel=license href=http://creativecommons.org/licenses/by-nc-sa/3.0/us/><img alt=Creative Commons License style=border-width:0 src=http://i.creativecommons.org/l/by-nc-sa/3.0/us/80x15.png /></a><br />This work by <a xmlns:cc=http://creativecommons.org/ns# href=http://www.xmemphisx.com/ property=cc:attributionName rel=cc:attributionURL>xMEMPHISx.com</a> is licensed under a <a rel=license href=http://creativecommons.org/licenses/by-nc-sa/3.0/us/>Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License</a>. <!-- /Creative Commons License --></div>Within Google Webmaster Tools, the list of relevant keywords is heavily saturated with the text from that blurb. For instance, 50% of my top-ten most relevant keywords (including the site name): [site name]license [keyword]commons creative [keyword]alike [keyword]attribution [keyword] I have not done any extensive testing to find out rather or not this list even matters, and so far this doesn't impact performance in any way. The site is well designed for humans, and it is as findable as it needs to be at the moment. But, out of mostly curiosity: Do you have any tips for decreasing the relevancy of the text from the Creative Commons footer blurb?
How can I decrease relevancy of Creative Commons footer text? (In Google Webmaster Tools)
seo;html;google search console;keywords;creative commons
Being this is probably in the footer of every page it's natural that it would appear so high in that list.Still, your goal shouldn't be to decrease the relevancy of those terms. It should be to increase the relevancy of the other terms on your pages. If the creative commons content is that relevant then you probably need to do a better job of making the actual content on your pages seem relevant to Google.
_unix.93000
I was trying the following combination in order to get the pid of the ssh session (running in the background displays the pid) and than fg to get back to the ssh session and introduce the password: ssh targetHost &; fgI get the following error: -bash: syntax error near unexpected token `;'Why does the ; not work to as expected in this case? My aim is to start a ssh session and know its pid and I need to do this in as few lines as possible. I need to start several ssh sessions, put them in the background and at the end kill them - that's why I need the pids.
ssh targetHost &; fg - does not work, but why?
background process;pid
You are mixing up two different cases:foo ; bar will run foo, wait for it to finish and then run barfoo & bar will start foo, put it in background and start bar directly afterwards.You have to decide, either use the one or the other. You cannot do both. ;)To solve you problem, you can simply run all jobs in background and then use job to list the pids:michas@lenny:~$ sleep 10 &[1] 18007michas@lenny:~$ sleep 10 &[2] 18011michas@lenny:~$ sleep 10 &[3] 18015michas@lenny:~$ sleep 10 &[4] 18019michas@lenny:~$ sleep 10 &[5] 18026michas@lenny:~$ jobs -p1800718011180151801918026michas@lenny:~$ You also do not necessarily need the pids to send kill signals. For example kill %1 will kill the first background process.
_unix.56153
Possible Duplicate:What does etc stand for? And why isn't it named /cnf or /syscf or /cfg? No one I have ever asked has been able to tell me, not that I have access to any of the minds that created UNIX. When I was a youngster, I saw the /etc and assumed it was for 'et cetera', namely, other files that had no place elsewhere, and I used it for that in a few of my early Linux installs (cringeworthy, I know) in the mid-90's. I continued learning and trying to do better, and I have, since. But the mystery remains, and even the FSSTND does not seem to contain this info. Anyone?
How did the system settings directory on UNIX come to be named /etc?
directory structure;history
null
_codereview.109601
I have been programming for a couple months now and really wanted to make my own game, so I chose battle ship due to is simplicity (I learned out how wrong I was). I know one thing I am going to hear about is that it isn't portable due to the fact I am using the windows library. All I have to say is I tried finding other ways but sadly I am not smart enough. I would also love to convert it to OOP, but I have no idea how to start.#include <iostream>#include <ctime>#include <limits>#include <string>#include <Windows.h>using namespace std;const int COLS = 10;const int ROWS = 10;const int CARRIER = 5;const int BATTLE_SHIP = 4;const int CRUISER = 3;const int SUBMARINE = 3;const int PATROL = 2;//Prototypesvoid playerSetUp(HANDLE, char[][COLS], int, int playerCarrier[], int playerBattleShip[], int playerCruiser[], int playerSubmarine[], int playerPatrol[]);void mapGenerator(char[][COLS], int, int carrier[], int battleShip[], int cruiser[], int submarine[], int patrol[]);void displayScoreBoard(HANDLE, char[][COLS], char[][COLS], int, int enemyCarrier[], int enemyBattleShip[], int enemyCruiser[], int enemySubmarine[], int enemyPatrol[], int &, int &, int &, int &, int &, int &, int &, int &, int &, int &, int playerCarrier[], int playerBattleShip[], int playerCruiser[], int playerSubmarine[], int playerPatrol[]);void placeCursor(HANDLE, int, int);int winCondition(int, int);int startMenu();int shipCheck(char[][COLS], int, int ship[], int);int letterVal(char);int numValidation(int);void displayBoard(HANDLE, char[][COLS], int);void playerTurn(HANDLE, char[][COLS], char[][COLS], int);void enemyTurn(HANDLE, char[][COLS], int, int);void stringInputCheck(HANDLE, string, int&, int&, int, int);int main(){ //computer map char computer[ROWS][COLS] = { { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, }; //map the player will see char enemyDisplay[ROWS][COLS] = { { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, }; //player map char player[ROWS][COLS] = { { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, { 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O' }, }; int startNumber, gameOver; int enemyCarrier[7], enemyBattleShip[6], enemyCruiser[5], enemySubmarine[5], enemyPatrol[4]; //holds numbers for points of ship location int playerCarrier[7], playerBattleShip[6], playerCruiser[5], playerPatrol[4]; //holds numbers for points of ship location int playerSubmarine[5]; int enemyCarrierAlive = 1, enemyBattleShipAlive = 1, enemyCruiserAlive = 1, enemySubmarineAlive = 1, enemyPatrolAlive = 1; //1 = ship alive 2 = ship dead int playerCarrierAlive = 1, playerBattleShipAlive = 1, playerCruiserAlive = 1, playerSubmarineAlive = 1, playerPatrolAlive = 1; //1 = ship alive 2 = ship dead int enemyAlive, playerAlive; //holds number 1-5 for how many ships are left HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE); //needed for color and cursor control startNumber = startMenu(); //gets player choice for difficulty if (startNumber == 1 || startNumber == 2){ system(CLS); playerSetUp(screen, player, ROWS, playerCarrier, playerBattleShip, playerCruiser, playerSubmarine, playerPatrol); //function that lets player place ships accordingly mapGenerator(computer, ROWS, enemyCarrier, enemyBattleShip, enemyCruiser, enemySubmarine, enemyPatrol); //function that sets computer ships do{ placeCursor(screen, 0, 0); //places cursor for boards displayBoard(screen, enemyDisplay, ROWS); //displays computer board displayBoard(screen, player, ROWS); //displays player board displayScoreBoard(screen, player, computer, ROWS, enemyCarrier, enemyBattleShip, enemyCruiser, enemySubmarine, enemyPatrol, enemyCarrierAlive, enemyBattleShipAlive, enemyCruiserAlive, enemySubmarineAlive, enemyPatrolAlive, playerCarrierAlive, playerBattleShipAlive, playerCruiserAlive, playerSubmarineAlive, playerPatrolAlive, playerCarrier, playerBattleShip, playerCruiser, playerSubmarine, playerPatrol); //displays score board playerTurn(screen, computer, enemyDisplay, ROWS); //lets player choose a point to attack enemyTurn(screen, player, COLS, startNumber); //computer chooses a point to attack enemyAlive = enemyCarrierAlive + enemyBattleShipAlive + enemyCruiserAlive + enemySubmarineAlive + enemyPatrolAlive; playerAlive = playerCarrierAlive + playerBattleShipAlive + playerCruiserAlive + playerSubmarineAlive + playerPatrolAlive; gameOver = winCondition(enemyAlive, playerAlive); //checks if all ships are destroyed } while (gameOver == 1); if (gameOver == 2){ system(CLS); placeCursor(screen, 0, 0); cout << You Win! << endl; cin.get(); } else{ system(CLS); placeCursor(screen, 0, 0); cout << You Lost! << endl; cin.get(); } } else{ char quitKey; cout << Press any key then enter to exit: ; cin >> quitKey; } return 0;}//This function lets the player pick between playing or quitting, then from computer or human, then from which difficultyint startMenu(){ int start; char choice; cout << \t\tBattle Ship Game 1.0\n\n\n; cout << This game is real beta stuff right now. << endl; cout << Please press the maxmize screen button for best quality. << endl << endl << endl; cout << A. Start \nB. Quit\nChoose: ; cin >> choice; while (!(choice == 'A' || choice == 'a' || choice == 'B' || choice == 'b' || choice == 'C' || choice == 'c')){ cout << Invalid choice. Please select A, B, or C: ; cin >> choice; } if (choice == 'A' || choice == 'a'){ cout << Would you like to face the computer or another person? << endl; cout << A. Computer\nB. Human\nC. Quit << endl; cout << Your choice: ; cin >> choice; while (!(choice == 'A' || choice == 'a' || choice == 'B' || choice == 'b' || choice == 'C' || choice == 'c')){ cout << Invalid choice. Please select A, B, or C: ; cin >> choice; } if (choice == 'A' || choice == 'a'){ cout << What difficulty would you like? << endl; cout << A. Easy\nB. Medium\nC. Hard (Under Construction} << endl; cout << Your choice: ; cin >> choice; if (choice == 'A' || choice == 'a'){ start = 1; } else if (choice == 'B' || choice == 'b'){ start = 2; } else{ cout << Hard still under constuction. Loading Medium difficulty.; start = 2; } } else if (choice == 'B' || choice == 'b'){ cout << Still under construction. Now exiting program. << endl; start = 0; } else start = 0; } else start = 0; return start;}//This function displays the game board of the player or the computervoid displayBoard(HANDLE screen, char map[][COLS], int row){ cout << 0 1 2 3 4 5 6 7 8 9 << endl; cout << -----------------------\n; for (int x = 0; x < 10; x++){ if (x == 0) cout << A ; if (x == 1) cout << B ; if (x == 2) cout << C ; if (x == 3) cout << D ; if (x == 4) cout << E ; if (x == 5) cout << F ; if (x == 6) cout << G ; if (x == 7) cout << H ; if (x == 8) cout << I ; if (x == 9) cout << J ; cout << | ; for (int y = 0; y < 10; y++){ if (map[x][y] == 'O'){ SetConsoleTextAttribute(screen, 7); cout << map[x][y] << ; } else if (map[x][y] == 'A'){ SetConsoleTextAttribute(screen, 1); cout << map[x][y] << ; SetConsoleTextAttribute(screen, 7); } else if(map[x][y] == 'M'){ SetConsoleTextAttribute(screen, 6); cout << map[x][y] << ; SetConsoleTextAttribute(screen, 7); } else{ SetConsoleTextAttribute(screen, 4); cout << map[x][y] << ; SetConsoleTextAttribute(screen, 7); } } cout << |; cout << endl; } cout << -----------------------\n;}//This function will allow the player to place his ships anywhere on the array.void playerSetUp(HANDLE screen, char playerSetUp[][COLS], int rows, int playerCarrier[], int playerBattleShip[], int playerCruiser[], int playerSubmarine[], int playerPatrol[]){ static int shipCount = 0; int place1 = 0, place2 = 0, place3 = 0, place4 = 0, shipSize, sizeDifference; string shipName, point; int overLapCheck = 1; char choice; displayBoard(screen, playerSetUp, ROWS); cout << Welcome to BattleShip! This is your board where you get to place your ships! << endl; cout << Please type the letter followed by the number (example: a6) then press enter. << endl; cout << Then type in the second coordinate in the same format. Please only place ships << endl; cout << from left to right or from up to down. The game will crash otherwise :( << endl; cout << Do you wish to place your ships manually or have a randomly generated board? << endl; cout << Type A to make your own board or B to have one make for you: ; cin >> choice; if (choice == 'A' || choice == 'a'){ do{ system(CLS); displayBoard(screen, playerSetUp, ROWS); if (shipCount == 0){ shipName = carrier; shipSize = CARRIER; } else if (shipCount == 1){ shipName = battle_ship; shipSize = BATTLE_SHIP; } else if (shipCount == 2){ shipName = cruiser; shipSize = CRUISER; } else if (shipCount == 3){ shipName = submarine; shipSize = SUBMARINE; } else if (shipCount == 4){ shipName = patrol; shipSize = PATROL; } cout << Placing << shipName << that is << shipSize << spaces long. << endl; cout << Please type the letter first followed by the number\nfor one point followed by the other point << endl; placeCursor(screen, 17, 0); cout << First point(e.g. a5) << endl; /*cin.ignore();*/ stringInputCheck(screen, point, place1, place2, 18, 0); /*cin >> placer1; place1 = letterVal(placer1); cin >> placer2; place2 = numValidation(placer2);*/ placeCursor(screen, 19, 0); cout << << endl; placeCursor(screen, 17, 0); cout << Second point (e.g. a8) << endl; /*cin.ignore();*/ stringInputCheck(screen, point, place3, place4, 18, 0); /*cin >> placer3; place3 = letterVal(placer3); cin >> placer4; place4 = numValidation(placer4);*/ if (place1 == place3){ sizeDifference = place4 - place2 + 1; if (sizeDifference == shipSize){ for (int x = place2; x <= place4; x++){ if (playerSetUp[place1][x] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ for (int x = place2, t = 2; x <= place4; x++, t++){ if (shipCount == 0){ playerCarrier[0] = 1; playerCarrier[1] = place1; playerCarrier[t] = x; } else if (shipCount == 1){ playerBattleShip[0] = 1; playerBattleShip[1] = place1; playerBattleShip[t] = x; } else if (shipCount == 2){ playerCruiser[0] = 1; playerCruiser[1] = place1; playerCruiser[t] = x; } else if (shipCount == 3){ playerSubmarine[0] = 1; playerSubmarine[1] = place1; playerSubmarine[t] = x; } else{ playerPatrol[0] = 1; playerPatrol[1] = place1; playerPatrol[t] = x; } playerSetUp[place1][x] = 'A'; system(CLS); } } else{ system(CLS); cout << You already have a ship there! << endl; shipCount--; } } else{ do{ system(CLS); cout << Invalid size. << endl; displayBoard(screen, playerSetUp, ROWS); cout << Placing << shipName << that is << shipSize << spaces long. << endl; cout << Please type the letter first followed by the number\nfor one point followed by the other point << endl; placeCursor(screen, 17, 0); cout << First point(e.g. a5) << endl; /*cin.ignore();*/ stringInputCheck(screen, point, place1, place2, 18, 0); /*cin >> placer1; place1 = letterVal(placer1); cin >> placer2; place2 = numValidation(placer2);*/ placeCursor(screen, 19, 0); cout << << endl; placeCursor(screen, 17, 0); cout << Second point (e.g. a8): ; /*cin.ignore();*/ stringInputCheck(screen, point, place3, place4, 18, 0); /*cin >> placer3; place3 = letterVal(placer3); cin >> placer4; place4 = numValidation(placer4);*/ sizeDifference = place4 - place2 + 1; } while (sizeDifference != shipSize && overLapCheck == 2); for (int x = place2; x <= place4; x++){ if (playerSetUp[place1][x] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ for (int x = place2, t = 2; x <= place4; x++, t++){ if (shipCount == 0){ playerCarrier[0] = 1; playerCarrier[1] = place1; playerCarrier[t] = x; } else if (shipCount == 1){ playerBattleShip[0] = 1; playerBattleShip[1] = place1; playerBattleShip[t] = x; } else if (shipCount == 2){ playerCruiser[0] = 1; playerCruiser[1] = place1; playerCruiser[t] = x; } else if (shipCount == 3){ playerSubmarine[0] = 1; playerSubmarine[1] = place1; playerSubmarine[t] = x; } else{ playerPatrol[0] = 1; playerPatrol[1] = place1; playerPatrol[t] = x; } playerSetUp[place1][x] = 'A'; system(CLS); } } else{ system(CLS); cout << You already have a ship there! << endl; shipCount--; } } } else if (place2 == place4){ sizeDifference = place3 - place1 + 1; if (sizeDifference == shipSize){ for (int x = place1; x <= place3; x++){ if (playerSetUp[x][place2] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ for (int x = place1, t = 2; x <= place3; x++, t++){ if (shipCount == 0){ playerCarrier[0] = 2; playerCarrier[1] = place2; playerCarrier[t] = x; } else if (shipCount == 1){ playerBattleShip[0] = 2; playerBattleShip[1] = place2; playerBattleShip[t] = x; } else if (shipCount == 2){ playerCruiser[0] = 2; playerCruiser[1] = place2; playerCruiser[t] = x; } else if (shipCount == 3){ playerSubmarine[0] = 2; playerSubmarine[1] = place2; playerSubmarine[t] = x; } else{ playerPatrol[0] = 2; playerPatrol[1] = place2; playerPatrol[t] = x; } playerSetUp[x][place2] = 'A'; system(CLS); } } else{ system(CLS); cout << You already have a ship there! << endl; shipCount--; } } else{ do{ system(CLS); displayBoard(screen, playerSetUp, ROWS); cout << Invalid size. << endl; cout << Placing << shipName << that is << shipSize << spaces long. << endl; cout << Please type the letter first followed by the number\nfor one point followed by the other point << endl; placeCursor(screen, 17, 0); cout << First point (e.g. a5) << endl; /*cin.ignore();*/ stringInputCheck(screen, point, place1, place2, 18, 0); /*cin >> placer1; place1 = letterVal(placer1); cin >> placer2; place2 = numValidation(placer2);*/ placeCursor(screen, 19, 0); cout << << endl; placeCursor(screen, 17, 0); cout << Second point (e.g. a8) << endl; /*cin.ignore();*/ stringInputCheck(screen, point, place3, place4, 18, 0); /*cin >> placer3; place3 = letterVal(placer3); cin >> placer4; place4 = numValidation(placer4);*/ sizeDifference = place4 - place2 + 1; } while (sizeDifference != shipSize && overLapCheck == 2); for (int x = place1; x <= place3; x++){ if (playerSetUp[place1][x] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ for (int x = place1, t = 2; x <= place3; x++, t++){ if (shipCount == 0){ playerCarrier[0] = 2; playerCarrier[1] = place2; playerCarrier[t] = x; } else if (shipCount == 1){ playerBattleShip[0] = 2; playerBattleShip[1] = place2; playerBattleShip[t] = x; } else if (shipCount == 2){ playerCruiser[0] = 2; playerCruiser[1] = place2; playerCruiser[t] = x; } else if (shipCount == 3){ playerSubmarine[0] = 2; playerSubmarine[1] = place2; playerSubmarine[t] = x; } else{ playerPatrol[0] = 2; playerPatrol[1] = place2; playerPatrol[t] = x; } playerSetUp[place1][x] = 'A'; system(CLS); } } else{ system(CLS); cout << You already have a ship there! << endl; shipCount--; } } } else{ system(CLS); cout << Must enter ships vertical or horizontal. << endl; cout << Please enter the smaller point first followed by the bigger point. << endl; shipCount--; } shipCount++; } while (shipCount <= 4); } else{ mapGenerator(playerSetUp, ROWS, playerCarrier, playerBattleShip, playerCruiser, playerSubmarine, playerPatrol); system(CLS); }}//This function makes the computer make a random map for the 5 shipsvoid mapGenerator(char setUp[][COLS], int rows, int carrier[], int battleShip[], int cruiser[], int submarine[], int patrol[]){ int computerShipDirection, computerPoint1, computerPoint2; //1 = horizontal 2 = vertical int overLapCheck; srand(time(0)); //place carrier computerShipDirection = rand() % 2 + 1; if (computerShipDirection == 1){ //horizontal computerPoint1 = rand() % 10; computerPoint2 = rand() % 6; setUp[computerPoint1][computerPoint2] = 'A'; setUp[computerPoint1][computerPoint2 + 1] = 'A'; setUp[computerPoint1][computerPoint2 + 2] = 'A'; setUp[computerPoint1][computerPoint2 + 3] = 'A'; setUp[computerPoint1][computerPoint2 + 4] = 'A'; carrier[0] = computerShipDirection; carrier[1] = computerPoint1; carrier[2] = computerPoint2; carrier[3] = computerPoint2 + 1; carrier[4] = computerPoint2 + 2; carrier[5] = computerPoint2 + 3; carrier[6] = computerPoint2 + 4; } else{ //vertical computerPoint1 = rand() % 6; computerPoint2 = rand() % 10; setUp[computerPoint1][computerPoint2] = 'A'; setUp[computerPoint1 + 1][computerPoint2] = 'A'; setUp[computerPoint1 + 2][computerPoint2] = 'A'; setUp[computerPoint1 + 3][computerPoint2] = 'A'; setUp[computerPoint1 + 4][computerPoint2] = 'A'; carrier[0] = computerShipDirection; carrier[1] = computerPoint2; carrier[2] = computerPoint1; carrier[3] = computerPoint1 + 1; carrier[4] = computerPoint1 + 2; carrier[5] = computerPoint1 + 3; carrier[6] = computerPoint1 + 4; } //place battleship do{ computerShipDirection = rand() % 2 + 1; if (computerShipDirection == 1){ //horizontal computerPoint1 = rand() % 10; computerPoint2 = rand() % 7; for (int z = computerPoint2; z < computerPoint2 + 3; z++){ if (setUp[computerPoint1][z] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ setUp[computerPoint1][computerPoint2] = 'A'; setUp[computerPoint1][computerPoint2 + 1] = 'A'; setUp[computerPoint1][computerPoint2 + 2] = 'A'; setUp[computerPoint1][computerPoint2 + 3] = 'A'; battleShip[0] = computerShipDirection; battleShip[1] = computerPoint1; battleShip[2] = computerPoint2; battleShip[3] = computerPoint2 + 1; battleShip[4] = computerPoint2 + 2; battleShip[5] = computerPoint2 + 3; } } else{ //vertical computerPoint1 = rand() % 7; computerPoint2 = rand() % 10; for (int z = computerPoint1; z < computerPoint1 + 3; z++){ if (setUp[z][computerPoint2] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ setUp[computerPoint1][computerPoint2] = 'A'; setUp[computerPoint1 + 1][computerPoint2] = 'A'; setUp[computerPoint1 + 2][computerPoint2] = 'A'; setUp[computerPoint1 + 3][computerPoint2] = 'A'; battleShip[0] = computerShipDirection; battleShip[1] = computerPoint2; battleShip[2] = computerPoint1; battleShip[3] = computerPoint1 + 1; battleShip[4] = computerPoint1 + 2; battleShip[5] = computerPoint1 + 3; } } } while (overLapCheck == 2); //Cruiser do{ computerShipDirection = rand() % 2 + 1; if (computerShipDirection == 1){ //horizontal computerPoint1 = rand() % 10; computerPoint2 = rand() % 8; for (int z = computerPoint2; z < computerPoint2 + 2; z++){ if (setUp[computerPoint1][z] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ setUp[computerPoint1][computerPoint2] = 'A'; setUp[computerPoint1][computerPoint2 + 1] = 'A'; setUp[computerPoint1][computerPoint2 + 2] = 'A'; cruiser[0] = computerShipDirection; cruiser[1] = computerPoint1; cruiser[2] = computerPoint2; cruiser[3] = computerPoint2 + 1; cruiser[4] = computerPoint2 + 2; } } else{ //vertical computerPoint1 = rand() % 8; computerPoint2 = rand() % 10; for (int z = computerPoint1; z < computerPoint1 + 2; z++){ if (setUp[z][computerPoint2] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ setUp[computerPoint1][computerPoint2] = 'A'; setUp[computerPoint1 + 1][computerPoint2] = 'A'; setUp[computerPoint1 + 2][computerPoint2] = 'A'; cruiser[0] = computerShipDirection; cruiser[1] = computerPoint2; cruiser[2] = computerPoint1; cruiser[3] = computerPoint1 + 1; cruiser[4] = computerPoint1 + 2; } } } while (overLapCheck == 2); //submarine do{ computerShipDirection = rand() % 2 + 1; if (computerShipDirection == 1){ //horizontal computerPoint1 = rand() % 10; computerPoint2 = rand() % 8; for (int z = computerPoint2; z < computerPoint2 + 2; z++){ if (setUp[computerPoint1][z] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ setUp[computerPoint1][computerPoint2] = 'A'; setUp[computerPoint1][computerPoint2 + 1] = 'A'; setUp[computerPoint1][computerPoint2 + 2] = 'A'; submarine[0] = computerShipDirection; submarine[1] = computerPoint1; submarine[2] = computerPoint2; submarine[3] = computerPoint2 + 1; submarine[4] = computerPoint2 + 2; } } else{ //vertical computerPoint1 = rand() % 8; computerPoint2 = rand() % 10; for (int z = computerPoint1; z < computerPoint1 + 2; z++){ if (setUp[z][computerPoint2] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ setUp[computerPoint1][computerPoint2] = 'A'; setUp[computerPoint1 + 1][computerPoint2] = 'A'; setUp[computerPoint1 + 2][computerPoint2] = 'A'; submarine[0] = computerShipDirection; submarine[1] = computerPoint2; submarine[2] = computerPoint1; submarine[3] = computerPoint1 + 1; submarine[4] = computerPoint1 + 2; } } } while (overLapCheck == 2); //patrol do{ computerShipDirection = rand() % 2 + 1; if (computerShipDirection == 1){ //horizontal computerPoint1 = rand() % 10; computerPoint2 = rand() % 9; for (int z = computerPoint2; z < computerPoint2 + 1; z++){ if (setUp[computerPoint1][z] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ setUp[computerPoint1][computerPoint2] = 'A'; setUp[computerPoint1][computerPoint2 + 1] = 'A'; patrol[0] = computerShipDirection; patrol[1] = computerPoint1; patrol[2] = computerPoint2; patrol[3] = computerPoint2 + 1; } } else{ //vertical computerPoint1 = rand() % 9; computerPoint2 = rand() % 10; for (int z = computerPoint1; z < computerPoint1 + 1; z++){ if (setUp[z][computerPoint2] == 'O'){ overLapCheck = 1; } else{ overLapCheck = 2; break; } } if (overLapCheck == 1){ setUp[computerPoint1][computerPoint2] = 'A'; setUp[computerPoint1 + 1][computerPoint2] = 'A'; patrol[0] = computerShipDirection; patrol[1] = computerPoint2; patrol[2] = computerPoint1; patrol[3] = computerPoint1 + 1; } } } while (overLapCheck == 2);}//This function displays a scoreboard and displays ships that are alive or have been destroyedvoid displayScoreBoard(HANDLE screen, char playerBoard[][COLS], char enemyBoard[][COLS], int rows, int enemyCarrier[], int enemyBattleShip[], int enemyCruiser[], int enemySubmarine[], int enemyPatrol[], int& enemyCarrierAlive, int& enemyBattleShipAlive, int& enemyCruiserAlive, int& enemySubmarineAlive, int& enemyPatrolAlive, int& playerCarrierAlive, int& playerBattleShipAlive, int& playerCruiserAlive, int& playerSubmarineAlive, int& playerPatrolAlive, int playerCarrier[], int playerBattleShip[], int playerCruiser[], int playerSubmarine[], int playerPatrol[]){ int size; int alive; placeCursor(screen, 0, 38); cout << -----Scoreboard----- << endl; //1 = horizontal 2 = vertical //Enemy Ships placeCursor(screen, 2, 30); cout << Enemy Ships Left: << endl; placeCursor(screen, 3, 30); size = 7; alive = shipCheck(enemyBoard, ROWS, enemyCarrier, size); if (alive == 1){ cout << Carrier << endl; enemyCarrierAlive = 1; } else{ cout << Carrier Destroyed! << endl; enemyCarrierAlive = 0; } placeCursor(screen, 4, 30); size = 6; alive = shipCheck(enemyBoard, ROWS, enemyBattleShip, size); if (alive == 1){ cout << Battle Ship << endl; enemyBattleShipAlive = 1; } else{ cout << Battle Ship Destroyed! << endl; enemyBattleShipAlive = 0; } placeCursor(screen, 5, 30); size = 5; alive = shipCheck(enemyBoard, ROWS, enemyCruiser, size); if (alive == 1){ cout << Cruiser << endl; enemyCruiserAlive = 1; } else{ cout << Cruiser Destroyed! << endl; enemyCruiserAlive = 0; } placeCursor(screen, 6, 30); size = 5; alive = shipCheck(enemyBoard, ROWS, enemySubmarine, size); if (alive == 1){ cout << Submarine << endl; enemySubmarineAlive = 1; } else{ cout << Submarine Destroyed! << endl; enemySubmarineAlive = 0; } placeCursor(screen, 7, 30); size = 4; alive = shipCheck(enemyBoard, ROWS, enemyPatrol, size); if (alive == 1){ cout << Patrol << endl; enemyPatrolAlive = 1; } else{ cout << Patrol Destroyed! << endl; enemyPatrolAlive = 0; } //Player Ships placeCursor(screen, 2, 53); cout << Your Ships Left: << endl; placeCursor(screen, 3, 53); size = 7; alive = shipCheck(playerBoard, ROWS, playerCarrier, size); if (alive == 1){ cout << Carrier << endl; playerCarrierAlive = 1; } else{ cout << Carrier Destroyed! << endl; playerCarrierAlive = 0; } placeCursor(screen, 4, 53); size = 6; alive = shipCheck(playerBoard, ROWS, playerBattleShip, size); if (alive == 1){ cout << Battle Ship << endl; playerBattleShipAlive = 1; } else{ cout << Battle Ship Destroyed! << endl; playerBattleShipAlive = 0; } placeCursor(screen, 5, 53); size = 5; alive = shipCheck(playerBoard, ROWS, playerCruiser, size); if (alive == 1){ cout << Cruiser << endl; playerCruiserAlive = 1; } else{ cout << Cruiser Destroyed! << endl; playerCruiserAlive = 0; } placeCursor(screen, 6, 53); size = 5; alive = shipCheck(playerBoard, ROWS, playerSubmarine, size); if (alive == 1){ cout << Submarine << endl; playerSubmarineAlive = 1; } else{ cout << Submarine Destroyed! << endl; playerSubmarineAlive = 0; } placeCursor(screen, 7, 53); size = 4; alive = shipCheck(playerBoard, ROWS, playerPatrol, size); if (alive == 1){ cout << Patrol << endl; playerPatrolAlive = 1; } else{ cout << Patrol Destroyed! << endl; playerPatrolAlive = 0; }}//This function places the cursor on the screen in a specific locationvoid placeCursor(HANDLE screen, int row, int col){ COORD position; position.Y = row; position.X = col; SetConsoleCursorPosition(screen, position);}//This function lets the player shoot at a pointvoid playerTurn(HANDLE screen, char enemyMap[][COLS], char enemyDisplayMap[][COLS], int rows) { //char v; string attack; int attack1, attack2, errorCount = 0; char holder; placeCursor(screen, 15, 30); cout << Choose which point you would like to attack. << endl; stringInputCheck(screen, attack, attack1, attack2, 16, 30); holder = enemyMap[attack1][attack2]; while (holder == 'M' || holder == 'X'){ placeCursor(screen, 13, 30); cout << You already attacked there! << endl; placeCursor(screen, 17, 30); cout << << endl; stringInputCheck(screen, attack, attack1, attack2, 16, 30); holder = enemyMap[attack1][attack2]; } if (holder == 'A'){ enemyMap[attack1][attack2] = 'X'; enemyDisplayMap[attack1][attack2] = 'X'; system(CLS); placeCursor(screen, 23, 30); cout << Direct hit! << endl; } else{ enemyMap[attack1][attack2] = 'M'; enemyDisplayMap[attack1][attack2] = 'M'; system(CLS); placeCursor(screen, 23, 30); cout << You missed! << endl; }}//This function lets the computer shoot at a pointvoid enemyTurn(HANDLE screen, char playerMap[][COLS], int rows, int difficulty){ //AI functions that lets the computer have its turn srand(time(0)); //Computer(Medium); static char computerLastAttack1, computerLastAttack2, computerMemory = 'O'; int computerAttack1, computerAttack2, computerNewAttack1, computerNewAttack2; char computerHolder; if (difficulty == 2){ if (computerMemory == 'O'){ computerAttack1 = rand() % 10; computerAttack2 = rand() % 10; computerHolder = playerMap[computerAttack1][computerAttack2]; while (computerHolder == 'M' || computerHolder == 'X'){ computerAttack1 = rand() % 10; computerAttack2 = rand() % 10; computerHolder = playerMap[computerAttack1][computerAttack2]; } if (computerHolder == 'A'){ playerMap[computerAttack1][computerAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Medium) got a Direct hit! << endl; } else{ playerMap[computerAttack1][computerAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Medium) missed! << endl; } computerLastAttack1 = computerAttack1; computerLastAttack2 = computerAttack2; computerMemory = computerHolder; } //Computer Logic else{ //Top Left Corner if (computerLastAttack1 == 0 && computerLastAttack2 == 0){ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 + 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1 + 1; computerNewAttack2 = computerLastAttack2 - 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } while (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = rand() % 10; computerNewAttack2 = rand() % 10; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } if (computerHolder == 'A'){ playerMap[computerNewAttack1][computerNewAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Medium) got a Direct hit! << endl; } else{ playerMap[computerNewAttack1][computerNewAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Medium) missed! << endl; } } //Bottom Right Corner else if (computerLastAttack1 == 9 && computerLastAttack2 == 9){ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 - 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1 - 1; computerNewAttack2 = computerLastAttack2 + 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } while (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = rand() % 10; computerNewAttack2 = rand() % 10; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } if (computerHolder == 'A'){ playerMap[computerNewAttack1][computerNewAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Medium) got a Direct hit! << endl; } else{ playerMap[computerNewAttack1][computerNewAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Medium) missed! << endl; } } //Top Right Corner else if (computerLastAttack1 == 0 && computerLastAttack2 == 9){ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 - 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1 + 1; computerNewAttack2 = computerLastAttack2 + 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } while (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = rand() % 10; computerNewAttack2 = rand() % 10; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } if (computerHolder == 'A'){ playerMap[computerNewAttack1][computerNewAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Medium) got a Direct hit! << endl; } else{ playerMap[computerNewAttack1][computerNewAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Medium) missed! << endl; } } //Bottom Left Corner else if (computerLastAttack1 == 9 && computerLastAttack2 == 0){ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 + 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1 - 1; computerNewAttack2 = computerLastAttack2 - 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } while (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = rand() % 10; computerNewAttack2 = rand() % 10; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } if (computerHolder == 'A'){ playerMap[computerNewAttack1][computerNewAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Medium) got a Direct hit! << endl; } else{ playerMap[computerNewAttack1][computerNewAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Medium) missed! << endl; } } //Top Wall else if (computerLastAttack1 == 0){ if (computerLastAttack2 == 9){ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 - 1; } else{ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 + 1; } computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1 + 1; computerNewAttack2 = computerLastAttack2; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } while (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = rand() % 10; computerNewAttack2 = rand() % 10; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } if (computerHolder == 'A'){ playerMap[computerNewAttack1][computerNewAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Medium) got a Direct hit! << endl; } else{ playerMap[computerNewAttack1][computerNewAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Medium) missed! << endl; } } //Left Wall else if (computerLastAttack2 == 0){ if (computerLastAttack1 == 9){ computerNewAttack1 = computerLastAttack1 - 1; computerNewAttack2 = computerLastAttack2; } else{ computerNewAttack1 = computerLastAttack1 + 1; computerNewAttack2 = computerLastAttack2; } computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 + 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } while (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = rand() % 10; computerNewAttack2 = rand() % 10; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } if (computerHolder == 'A'){ playerMap[computerNewAttack1][computerNewAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Medium) got a Direct hit! << endl; } else{ playerMap[computerNewAttack1][computerNewAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Medium) missed! << endl; } } //Right Wall else if (computerLastAttack2 == 9){ if (computerLastAttack1 == 8){ computerNewAttack1 = computerLastAttack1 - 1; computerNewAttack2 = computerLastAttack2; } else{ computerNewAttack1 = computerLastAttack1 + 1; computerNewAttack2 = computerLastAttack2; } computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 - 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } while (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = rand() % 10; computerNewAttack2 = rand() % 10; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } if (computerHolder == 'A'){ playerMap[computerNewAttack1][computerNewAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Medium) got a Direct hit! << endl; } else{ playerMap[computerNewAttack1][computerNewAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Medium) missed! << endl; } } //Bottom Wall else if (computerLastAttack1 == 9){ if (computerLastAttack2 == 8){ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 - 1; } else{ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 + 1; } computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1 - 1; computerNewAttack2 = computerLastAttack2; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } while (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = rand() % 10; computerNewAttack2 = rand() % 10; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } if (computerHolder == 'A'){ playerMap[computerNewAttack1][computerNewAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Medium) got a Direct hit! << endl; } else{ playerMap[computerNewAttack1][computerNewAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Medium) missed! << endl; } } //anywhere else on map else{ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 + 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1; computerNewAttack2 = computerLastAttack2 - 1; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } else if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1 - 1; computerNewAttack2 = computerLastAttack2; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } else if (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = computerLastAttack1 + 1; computerNewAttack2 = computerLastAttack2; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } while (computerHolder == 'M' || computerHolder == 'X'){ computerNewAttack1 = rand() % 10; computerNewAttack2 = rand() % 10; computerHolder = playerMap[computerNewAttack1][computerNewAttack2]; } if (computerHolder == 'A'){ playerMap[computerNewAttack1][computerNewAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Medium) got a Direct hit! << endl; } else{ playerMap[computerNewAttack1][computerNewAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Medium) missed! << endl; } } } } //Computer(Easy); else{ computerAttack1 = rand() % 10; computerAttack2 = rand() % 10; computerHolder = playerMap[computerAttack1][computerAttack2]; while (computerHolder == 'M' || computerHolder == 'X'){ computerAttack1 = rand() % 10; computerAttack2 = rand() % 10; computerHolder = playerMap[computerAttack1][computerAttack2]; } if (computerHolder == 'A'){ playerMap[computerAttack1][computerAttack2] = 'X'; placeCursor(screen, 24, 30); cout << Computer(Easy) got a Direct hit! << endl; } else{ playerMap[computerAttack1][computerAttack2] = 'M'; placeCursor(screen, 24, 30); cout << Computer(Easy) missed! << endl; } }}//This function checks if there are any ships leftint winCondition(int enemy, int player){ if (enemy == 0){ return 2; } else if (player == 0){ return 3; } else{ return 1; }}//outdated functions//This function checks if the letter entered by the user is valid//int letterVal(char c){// int attack;// if (!(c == 'A' || c == 'a' || c == 'B' || c == 'b' || c == 'C' || c == 'c' || c == 'D' || c == 'd' || c == 'E' || c == 'e' || c == 'F' || c == 'f' || c == 'G' || c == 'g' || c == 'H' || c == 'h' || c == 'I' || c == 'i' || c == 'J' || c == 'j')){// do// {// cin.clear();// cout << Invalid input, please enter a letter that is from A-J: ;// cin.get(c);// } while (!(c == 'A' || c == 'a' || c == 'B' || c == 'b' || c == 'C' || c == 'c' || c == 'D' || c == 'd' || c == 'E' || c == 'e' || c == 'F' || c == 'f' || c == 'G' || c == 'g' || c == 'H' || c == 'h' || c == 'I' || c == 'i' || c == 'J' || c == 'j'));// }// if (c == 'A' || c == 'a')// attack = 0;// else if (c == 'B' || c == 'b')// attack = 1;// else if (c == 'C' || c == 'c')// attack = 2;// else if (c == 'D' || c == 'd')// attack = 3;// else if (c == 'E' || c == 'e')// attack = 4;// else if (c == 'F' || c == 'f')// attack = 5;// else if (c == 'G' || c == 'g')// attack = 6;// else if (c == 'H' || c == 'h')// attack = 7;// else if (c == 'I' || c == 'i')// attack = 8;// else if (c == 'J' || c == 'j')// attack = 9;// return attack;//}//This function checks if the number entered by the user is valid//int numValidation(int z){// if (cin.fail() || z < 0 || z > 9){// do{// cin.clear();// cout << Invalid input. Please enter a number 0-9: ;// cin >> z;// } while (cin.fail());// }// return z;//}//This function checks which ships are alive or dead when called int shipCheck(char board[][COLS], int rows, int ship[], int size){ int holder; if (ship[0] == 1){ for (int x = 2; x < size; x++){ if(board[ship[1]][ship[x]] == 'A'){ holder = 1; break; } else{ holder = 2; } } } else{ for (int x = 2; x < size; x++){ if (board[ship[x]][ship[1]] == 'A'){ holder = 1; break; } else{ holder = 2; } } } return holder;}//This function validates the player choice of where to attackvoid stringInputCheck(HANDLE screen, string attack, int &attack1, int &attack2, int row, int col){ int errorCount = 0; do{ if (errorCount > 0){ placeCursor(screen, row + 1, col); cout << << endl; } placeCursor(screen, row, col); cout << Please type the letter first followed by << endl; placeCursor(screen, row + 1, col); cout << the number: ; cin.ignore(); cin >> attack; errorCount++; } while (!(attack == a0 || attack == a1 || attack == a2 || attack == a3 || attack == a4 || attack == a5 || attack == a6 || attack == a7 || attack == a8 || attack == a9 || attack == b0 || attack == b1 || attack == b2 || attack == b3 || attack == b4 || attack == b5 || attack == b6 || attack == b7 || attack == b8 || attack == b9 || attack == c0 || attack == c1 || attack == c2 || attack == c3 || attack == c4 || attack == c5 || attack == c6 || attack == c7 || attack == c8 || attack == c9 || attack == d0 || attack == d1 || attack == d2 || attack == d3 || attack == d4 || attack == d5 || attack == d6 || attack == d7 || attack == d8 || attack == d9 || attack == e0 || attack == e1 || attack == e2 || attack == e3 || attack == e4 || attack == e5 || attack == e6 || attack == e7 || attack == e8 || attack == e9 || attack == f0 || attack == f1 || attack == f2 || attack == f3 || attack == f4 || attack == f5 || attack == f6 || attack == f7 || attack == f8 || attack == f9 || attack == g0 || attack == g1 || attack == g2 || attack == g3 || attack == g4 || attack == g5 || attack == g6 || attack == g7 || attack == g8 || attack == g9 || attack == h0 || attack == h1 || attack == h2 || attack == h3 || attack == h4 || attack == h5 || attack == h6 || attack == h7 || attack == h8 || attack == h9 || attack == i0 || attack == i1 || attack == i2 || attack == i3 || attack == i4 || attack == i5 || attack == i6 || attack == i7 || attack == i8 || attack == i9 || attack == j0 || attack == j1 || attack == j2 || attack == j3 || attack == j4 || attack == j5 || attack == j6 || attack == j7 || attack == j8 || attack == j9)); if (attack == a0){ attack1 = 0; attack2 = 0; } if (attack == a1){ attack1 = 0; attack2 = 1; } if (attack == a2){ attack1 = 0; attack2 = 2; } if (attack == a3){ attack1 = 0; attack2 = 3; } if (attack == a4){ attack1 = 0; attack2 = 4; } if (attack == a5){ attack1 = 0; attack2 = 5; } if (attack == a6){ attack1 = 0; attack2 = 6; } if (attack == a7){ attack1 = 0; attack2 = 7; } if (attack == a8){ attack1 = 0; attack2 = 8; } if (attack == a9){ attack1 = 0; attack2 = 9; } if (attack == b0){ attack1 = 1; attack2 = 0; } if (attack == b1){ attack1 = 1; attack2 = 1; } if (attack == b2){ attack1 = 1; attack2 = 2; } if (attack == b3){ attack1 = 1; attack2 = 3; } if (attack == b4){ attack1 = 1; attack2 = 4; } if (attack == b5){ attack1 = 1; attack2 = 5; } if (attack == b6){ attack1 = 1; attack2 = 6; } if (attack == b7){ attack1 = 1; attack2 = 7; } if (attack == b8){ attack1 = 1; attack2 = 8; } if (attack == b9){ attack1 = 1; attack2 = 9; } if (attack == c0){ attack1 = 2; attack2 = 0; } if (attack == c1){ attack1 = 2; attack2 = 1; } if (attack == c2){ attack1 = 2; attack2 = 2; } if (attack == c3){ attack1 = 2; attack2 = 3; } if (attack == c4){ attack1 = 2; attack2 = 4; } if (attack == c5){ attack1 = 2; attack2 = 5; } if (attack == c6){ attack1 = 2; attack2 = 6; } if (attack == c7){ attack1 = 2; attack2 = 7; } if (attack == c8){ attack1 = 2; attack2 = 8; } if (attack == c9){ attack1 = 2; attack2 = 9; } if (attack == d0){ attack1 = 3; attack2 = 0; } if (attack == d1){ attack1 = 3; attack2 = 1; } if (attack == d2){ attack1 = 3; attack2 = 2; } if (attack == d3){ attack1 = 3; attack2 = 3; } if (attack == d4){ attack1 = 3; attack2 = 4; } if (attack == d5){ attack1 = 3; attack2 = 5; } if (attack == d6){ attack1 = 3; attack2 = 6; } if (attack == d7){ attack1 = 3; attack2 = 7; } if (attack == d8){ attack1 = 3; attack2 = 8; } if (attack == d9){ attack1 = 3; attack2 = 9; } if (attack == e0){ attack1 = 4; attack2 = 0; } if (attack == e1){ attack1 = 4; attack2 = 1; } if (attack == e2){ attack1 = 4; attack2 = 2; } if (attack == e3){ attack1 = 4; attack2 = 3; } if (attack == e4){ attack1 = 4; attack2 = 4; } if (attack == e5){ attack1 = 4; attack2 = 5; } if (attack == e6){ attack1 = 4; attack2 = 6; } if (attack == e7){ attack1 = 4; attack2 = 7; } if (attack == e8){ attack1 = 4; attack2 = 8; } if (attack == e9){ attack1 = 4; attack2 = 9; } if (attack == f0){ attack1 = 5; attack2 = 0; } if (attack == f1){ attack1 = 5; attack2 = 1; } if (attack == f2){ attack1 = 5; attack2 = 2; } if (attack == f3){ attack1 = 5; attack2 = 3; } if (attack == f4){ attack1 = 5; attack2 = 4; } if (attack == f5){ attack1 = 5; attack2 = 5; } if (attack == f6){ attack1 = 5; attack2 = 6; } if (attack == f7){ attack1 = 5; attack2 = 7; } if (attack == f8){ attack1 = 5; attack2 = 8; } if (attack == f9){ attack1 = 5; attack2 = 9; } if (attack == g0){ attack1 = 6; attack2 = 0; } if (attack == g1){ attack1 = 6; attack2 = 1; } if (attack == g2){ attack1 = 6; attack2 = 2; } if (attack == g3){ attack1 = 6; attack2 = 3; } if (attack == g4){ attack1 = 6; attack2 = 4; } if (attack == g5){ attack1 = 6; attack2 = 5; } if (attack == g6){ attack1 = 6; attack2 = 6; } if (attack == g7){ attack1 = 6; attack2 = 7; } if (attack == g8){ attack1 = 6; attack2 = 8; } if (attack == g9){ attack1 = 6; attack2 = 9; } if (attack == h0){ attack1 = 7; attack2 = 0; } if (attack == h1){ attack1 = 7; attack2 = 1; } if (attack == h2){ attack1 = 7; attack2 = 2; } if (attack == h3){ attack1 = 7; attack2 = 3; } if (attack == h4){ attack1 = 7; attack2 = 4; } if (attack == h5){ attack1 = 7; attack2 = 5; } if (attack == h6){ attack1 = 7; attack2 = 6; } if (attack == h7){ attack1 = 7; attack2 = 7; } if (attack == h8){ attack1 = 7; attack2 = 8; } if (attack == h9){ attack1 = 7; attack2 = 9; } if (attack == i0){ attack1 = 8; attack2 = 0; } if (attack == i1){ attack1 = 8; attack2 = 1; } if (attack == i2){ attack1 = 8; attack2 = 2; } if (attack == i3){ attack1 = 8; attack2 = 3; } if (attack == i4){ attack1 = 8; attack2 = 4; } if (attack == i5){ attack1 = 8; attack2 = 5; } if (attack == i6){ attack1 = 8; attack2 = 6; } if (attack == i7){ attack1 = 8; attack2 = 7; } if (attack == i8){ attack1 = 8; attack2 = 8; } if (attack == i9){ attack1 = 8; attack2 = 9; } if (attack == j0){ attack1 = 9; attack2 = 0; } if (attack == j1){ attack1 = 9; attack2 = 1; } if (attack == j2){ attack1 = 9; attack2 = 2; } if (attack == j3){ attack1 = 9; attack2 = 3; } if (attack == j4){ attack1 = 9; attack2 = 4; } if (attack == j5){ attack1 = 9; attack2 = 5; } if (attack == j6){ attack1 = 9; attack2 = 6; } if (attack == j7){ attack1 = 9; attack2 = 7; } if (attack == j8){ attack1 = 9; attack2 = 8; } if (attack == j9){ attack1 = 9; attack2 = 9; }}
Battle ship game
c++;game
null
_unix.326506
I am trying to enable code coverage in 4.4 kernel. Steps followed for the sameAdded the following changes in the msmcortex_defconfig file in arch/arm64/configs folderCONFIG_GCOV_KERNEL=yCONFIG_DEBUG_FS=yAdded GCOV_PROFILE := y in the make file of the directories which need to be profiledAfter doing these changes the respective .gcno files are generated. But after flashing the kernel, there is a panic causing a continuous restart of the target.Below are the serial logs of the panic[ 5.335448] Unable to handle kernel paging request at virtual address 955b12b0[ 5.340733] pgd = ffffff8009ed2000[ 5.347786] [955b12b0] *pgd=0000000000000000, *pud=0000000000000000[ 5.357240] ------------[ cut here ]------------[ 5.357480] Kernel BUG at ffffff8008358c70 [verbose debug info unavailable][ 5.362177] Internal error: Oops - BUG: 96000005 [#1] PREEMPT SMP[ 5.542195] Exception stack(0xffffffc0f2c3bb10 to 0xffffffc0f2c3bc30)[ 5.544377] bb00: 00000000955b12b8 ffffff800814330c[ 5.550979] bb20: ffffffc0f2c3bcd0 ffffff8008358c70 ffffffc0f2c3bb60 ffffff800808bf10[ 5.558791] bb40: 0000000000000001 ffffff8008f424ec 0000000000000140 ffffffc0f2c30000[ 5.566604] bb60: ffffffc0f2c3bba0 ffffff80080cf918 0000000000000001 ffffff8008f424ec[ 5.574415] bb80: 0000000000000140 ffffffc0f2c30000 ffffff8009bfa000 0000000000000000[ 5.582229] bba0: ffffffc0f2c3bbc0 ffffff8008f424ec 00000000955b12b8 00000000955b12b0[ 5.590040] bbc0: ffffff80098ef000 0000000000000000 ffffffc0f2c3bcf0 ffffffc0f2c3bc70[ 5.597853] bbe0: 0000000000000000 fffffffffffffff8 ffffffc0f075da38 756dff7364726471[ 5.605665] bc00: 7f7f7f7f7f7f7f7f 0101010101010101 0000000000000028 0000000000000020[ 5.613477] bc20: 0ffffffffffffffe ffffffc0f2c98e00[ 5.621281] [<ffffff8008358c70>] strlen+0x60/0x90[ 5.625971] [<ffffff800814330c>] gcov_event+0x158/0x344[ 5.630834] [<ffffff8008142834>] gcov_enable_events+0x58/0x88[ 5.635867] [<ffffff8009734ea4>] gcov_fs_init+0x9c/0xcc[ 5.641771] [<ffffff8008081c38>] do_one_initcall+0x19c/0x1b8[ 5.646806] [<ffffff8009720e14>] kernel_init_freeable+0x1e8/0x288[ 5.652714] [<ffffff8008f39ef4>] kernel_init+0x18/0x100[ 5.658696] [<ffffff8008084cd0>] ret_from_fork+0x10/0x40[ 5.663734] Code: 8b4c0c00 d65f03c0 f10020ff cb0703e7 (a8c10c22)[ 5.669327] ---[ end trace 96c7a79c91d422a5 ]---[ 5.675324] Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000000bLooks like it has crashed in gcov_event() function. Any lead on this issue would be appreciated.Please let me know if any one faced this issue and fixed it earlier.
Kernel panic after enabling GCOV code coverage
kernel;kernel panic
null
_unix.248929
I am experiencing wireless stability issues and I'd like to upgrade my debian kernelSo I'd like to know how can I upgrade my current kernel to the latest stable kernel on kernel.org ? (4.3.2)
How can I upgrade my debian kernel to 4.3.2?
debian;kernel
null
_unix.32437
We have a few servers running CentOS 6.2 deploying web applications using Apache/ MySQL/ PHP.In the past we've just regularly run yum update to keep all the software up to date.As of right now the installed versions are:Apache 2.2.15MySQL 5.1.61PHP 5.3.3When the latest released versions are:Apache 2.4.1MySQL 5.5.21PHP 5.3.10We're web developers with a bit of Linux knowledge rather than server administrators so we want to be able keep everything patched to the latest (or near) version without having to go into the depths of compiling software or too much command line jiggery-pokery.What is the best way for us to easily maintain the latest versions (or at least late as possible versions) on CentOS 6.2?
How to easily maintain the latest versions of Apache/ MySQL/ PHP on CentOS 6.2?
centos;package management;yum;software updates
So I'm digging through old questions but hopefully this will still be of some use to you.So if you want the absolute most up to date releases of those, your best bet is to get them directly from the projects themselves and build from sources.If you are looking just looking to regularly make sure everything is up to date you might want to set a cron job that runs yum update nightly. The guide that I keep in my bookmarks for when I'm having brain fart moments is this one here. It should help you out in setting that up.Lastly if you are looking to pull through yum the most recent packages possible, the fasttrack repo from CentOS might be your best bet. Do a ctrl-f fasttrack on this wiki page for the info on it. Although be forewarned I've never used that repo before and can't really say 100% that it's what you will need or that it won't break things.
_datascience.19865
Forgive me if this is a duplicate question, I haven't found anything that answers my question specifically after searching for a while.I have a dataset which I'm using to predict mobile app user retention, using the RandomForestClassifier in the SciKit Learn package. I'm pleased with the accuracy I'm getting and I'm planning on including a number of other metrics including precision, recall, Matthew's Corr Coefficient etc. I'm pretty sure the model is good.The key thing that I'm interested in here are the features themselves. I want to know what is contributing to my user churn. I have extracted the feature importances and plotted a nice looking graph, but now I'm stuck. I'd ideally like to know how each variable influences the churned/not churned outcome. The problem with GINI feature importances is that I can see which ones are most influential, but for example with continuous variables I want to know at which value the RF found best to split on. I don't need to see this for every feature as I have 70+ only the most 'important' ones.I saw a very nice decision tree plot here, but cannot find any way of reproducing something similar using scikit learn. I'm open to other suggestions. Thanks in advance :)
How to further Interpret Variable Importance?
machine learning;feature selection;random forest
The documentation offers a couple options. To plot the individual trees in your forest, one can access them like model.estimators_[n].tree_ and then plot them with export_graphviz as explained in the documentation, or you can follow this example that directly prints the structure in text format.However, I would say this is not the best idea, because a feature can occur in different trees and nodes with different split points. You probably get a better intuition about your features from partial dependence plots that try to isolate the effect of one variable on your response variable.As a bonus, here is a good article about more alternatives to gain insight into your model (not all applicable to random forests).
_unix.82731
I want to have a separate folders for cron jobs like:/mydata/cronjobsNow in that folder I want to have files like backup_server which will have the content like:30 3 * * 1-5 /home/user/scripts/backup.sh 30 3 * * 1-5 /home/user/scripts/backup2.sh Similarly, I want to have more files in that directory for each separate cron job so that I can centralize and separate the cron jobs from one folder.How can I make root run those jobs for all files in that folder?
How can I create cron jobs in specific files?
linux;centos;cron
null
_softwareengineering.235294
I have a fairly simple data structure like this:create table project (id int auto increment primary key, name text);create table item (id int auto increment primary key, name text, project_id int not null, project_sort_index int not null, sort_index int not null, foreign key fk_project(project_id) references project(id));A project can have many items. Items have two different fields for maintaining sort order, project_sort_index and sort_index.These sort order fields apply in the following way. When I view all items belonging to a project, I need a sort order specific to each project for the items. When I view all items globally, I need a sort order for them globally. I have a couple of questions as to how best to maintain and modify sort order for these items. Lets say that I have moved an item at index 4 to index 2. How do I propagate that change to my database efficiently? For example, how do I now update all index numbers >= 2 to move everything down, yet close the gap left in place 4? Is there a better way of sorting lists in SQL?
Maintaining indices for location in a sorted list in database rows
database design;sql
null
_unix.101312
I'm looking to install the package for tempfile but am not finding it?possibly use mktemp but I'm not sure if there is a difference in behaviourbesides a dot notation in the temp name?$ tempfile # /tmp/file1wJzkz$ mktemp # /tmp/tmp.IY8k24NayM
Command(s) to install tempfile on CentOS 6.4
command line;centos;tmp
The name generated by mktemp can be modified to have no dots. For example: mktemp XXXXX => 8U5ycmktemp /tmp/XXXXX => /tmp/tsjoGFrom man mktemp:DESCRIPTION Create a temporary file or directory, safely, and print its name. TEM PLATE must contain at least 3 consecutive 'X's in last component. If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied. Files are created u+rw, and directories u+rwx, minus umask restric tions.In any case, forget about tempfile, just use mktemp. The following is from man tempfile on my Debian (emphasis mine):BUGSExclusive creation is not guaranteed when creating files on NFS partitions. tempfile cannot make temporary directories. tempfile is deprecated; you should use mktemp(1) instead.
_unix.187292
I have a fairly simple apache 2.4.7 config on CentOS 6.5 Linux and an active web server.No PHP or CGI, just some static pages and a proxypass to a different server tier.I'm doing some security probing and purposely sending invalid data in the form of URL's with ~usernames that don't exist. I expect to get a 405 error.HTTP/1.1 405 Method Not AllowedDate: Fri, 27 Feb 2015 21:28:51 GMTServer: Apache-Coyote/1.1X-Frame-Options: SAMEORIGINAllow: GET,DELETE,POST,PUTX-Frame-Options: SAMEORIGINAnd that's what I get 90-95% of the time. But about 1 in 20-30 tries get a 200 return code with an otherwise blank page.200 27/Feb/2015:21:02:50HTTP/1.1 200 OKDate: Fri, 27 Feb 2015 21:28:50 GMTServer: ApacheX-Frame-Options: SAMEORIGINContent-Length: 1If it was a simple configuration issue, I would expect every call to either fail or work, not 3-5% failing. I only see this on the SSL port, the http port is also configured (though not open to the public) and it does NOT show the same issue. I can send hundreds of calls though http with no errors, but get at least one or two every 50 calls are so on https.Some of the tests I've already tried unsuccessfully, are:Logs just report the fact that either a 405 or a 200 was sent but no apparent difference in the url. Or any errors.Eliminate any inbound firewall issues, by trying call on local loopback, same issue.Eliminate issue with outbound load balancer by calling proxy connection directly. My reasoning for this test, is there nothing in this tier layer to handle ~username calls and it likely being ignored and passed by the wildcard proxypass to the next layer. Next sever layer is responding perfectly. No errors even with hundreds of calls in test blast.Ran same test on Development environment which is configured exactly the same (AWS image is the same so differences is only in IP addresses) No errors, so volume in production maybe issue, but not a very helpful one. Server is currently averaging around 5-10 hits/sec with short peeks up to 25.CPU load is 0.00 to 0.02 with over 2G of 7G free memory and no disk issues. I don't want to post the full configuration file here, but it's pretty vanilla with the relevant parts of the VirtualHost reading. (URL's changed to protect the innocent and keep stackexchange from thinking they're links) Listen 443SSLCipherSuite ***REDACTED***SSLHonorCipherOrder onSSLSessionCache shmcb:/opt/httpd/logs/ssl_scache(512000)SSLSessionCacheTimeout 300SSLProtocol ALL -SSLv2 -SSLv3 +TLSv1 +TLSv1.1 +TLSv1.2SSLCompression OffSSLEngine onSSLCertificateFile ***REDACTED***SSLCertificateKeyFile ***REDACTED***SSLCertificateChainFile ***REDACTED***BrowserMatch MSIE [2-5] \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0CustomLog /opt/httpd/logs/ssl_request_log \ %t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \%r\ %b Order deny,allow Allow from allSSLProxyEngine onProxyPass /terms !ProxyPass /static !ProxyPass /images !ProxyPass /terms_ccm !ProxyPass /pay/ https ://pay.ACME.COM/payment/ProxyPassReverse /payment/ https ://pay.ACME.COM/payment/ProxyPass / http: //mbg.ACME.COM/mobgate/ProxyPassReverse http: //mbg.ACME.com/mobgate /
Apache modssl returning random unwanted 200's rather than 404's
apache httpd;ssl;http proxy;https
null
_codereview.59135
I'm making a demo program for a job interview and I'd like to know if there is anything I can make work faster in my current solution. It's a C# console application that accepts input in form of a single string with the words delimited by , symbol. The task is to find the most commonly encountered combination of three characters throughout all the words. It's not specified what I should do if there are multiple triplets with the same rate of appearance, so I'm just returning whatever ends up sorted to the first place. Here is my take on this:using System;using System.Collections.Generic;using System.Linq;class Program{ static void Main(string[] args) { string input = args.Length > 0 ? args[0] : null; if (input == null) // demo input input = Lorem,ipsum,etiam,habitasse,conubia,sed,habitasse,tristique,,erat,varius,vitae,nunc,vulputate,etiam,proin,,interdum,malesuada,nam,curabitur,nibh,pharetra,ultricies,elit,elementum,viverra,vehicula,lacinia,vestibulum,dapibus,,bibendum,vestibulum,quisque,potenti,dictum,ad,curabitur,neque,,taciti,consequat,malesuada,quisque,ultrices,scelerisque,in,fermentum,fringilla,per,ad.Tortor,habitasse,auctor,consequat,imperdiet,vel,iaculis,suscipit,torquent,,porta,eget,cubilia,cras,quisque,sociosqu,auctor,neque,,ac,dictum,elit,rhoncus,ornare,augue,cras,quis,tempor,sodales,congue,nulla,dictum,quisque,iaculis,magna,mattis,odio,,elementum,varius,turpis,pretium,consequat,gravida,ut,hendrerit,metus,,pulvinar,scelerisque,eu,et,neque,cubilia,mauris,elementum,porttitor,eleifend,vestibulum,luctus,id,diam,pellentesque,convallis,nisi,libero,ante,aliquam,maecenas,facilisis.Suscipit,posuere,gravida,luctus,cursus,erat,eleifend,,magna,tempor,iaculis,arcu,rutrum,viverra,lorem,,posuere,ipsum,leo,aenean,donec,praesent,mollis,phasellus,sociosqu,orci,magna,potenti,donec,curabitur,feugiat,,ultricies,integer,lacus,mollis,porta,consectetur,fames,dolor,,himenaeos,enim,quisque,dapibus,viverra,maecenas,nam,ac,eget,est,sed,conubia,ad,aliquet,sed,consequat,augue,,quisque,bibendum,luctus,id,tempus,lacinia,facilisis,,fames,eget,ut,taciti,nullam,malesuada,integer.Massa,egestas,enim,urna,magna,ultrices,placerat,at,,adipiscing,taciti,bibendum,sodales,consequat,mollis,tempus,platea,,lorem,nisi,congue,vehicula,lacinia,fusce.Donec,gravida,interdum,malesuada,vel,erat,velit,massa,pulvinar,fringilla,potenti,,habitasse,ullamcorper,varius,vel,lobortis,proin,risus,nulla,senectus,,amet,pharetra,quam,elit,convallis,quis,laoreet,vestibulum,rhoncus,eget,lectus,hendrerit,elementum,etiam,viverra,sit,porttitor,etiam,sollicitudin,porta,nibh,non,,nibh,ipsum,inceptos,pellentesque,placerat,conubia,neque,donec,id,vivamus,sed,eget,suscipit,tristique,orci,id,ipsum,ligula,morbi,aliquam,eros,inceptos,leo,curabitur,vehicula,aliquam,aenean,porta,tempor,cras,aenean,nostra,sapien,,ac,lacus,donec,ut,placerat,bibendum,potenti,pellentesque,cubilia,,nunc,nisi,tristique,nam,tristique,varius,ultrices.Maecenas,bibendum,himenaeos,ut,a,ornare,sociosqu,integer,mi,scelerisque,congue,dolor,suspendisse,mattis,eu,,pulvinar,maecenas,etiam,fermentum,leo,eleifend,quis,semper,hac,cursus,aenean,ornare,at,potenti,class,donec,dapibus,dictum,vitae,id,suspendisse,taciti,,placerat,sem,elementum,id,metus,vehicula,nostra,curae,aliquet,,inceptos,quisque,massa,augue,sollicitudin,porta,cras,senectus.Aliquam,sit,nec,vulputate,mauris,lorem,inceptos,volutpat,hac,quisque,,iaculis,blandit,vel,erat,condimentum,orci,massa,luctus,placerat,,fermentum,facilisis,purus,eget,potenti,sem,nec,hendrerit,tempus,habitant,eros,sit,curabitur,congue,porttitor,curabitur,praesent,tortor,,mattis,donec,vehicula,massa,a,donec,fames,lacinia,,est,sodales,fringilla,aliquam,lacus,class,nisi,hac.Hac,venenatis,himenaeos,volutpat,a,at,semper,aenean,erat,etiam,dapibus,quis,diam,,erat,mi,curabitur,nisl,proin,praesent,suspendisse,bibendum,nibh,erat,mollis,consequat,congue,etiam,feugiat,rhoncus,tempor,libero,pellentesque,duis,id,eu,,mattis,in,integer,lectus,non,sed,sapien,eu,felis,donec,,taciti,purus,vulputate,tellus,massa,malesuada,litora,nisl,feugiat,sollicitudin,accumsan,porta,ligula,lobortis,vitae,suspendisse,varius,,in,lorem,habitant,arcu,pellentesque,blandit,,viverra,nulla,class,molestie,pharetra,duis,ac,eu,tempus,aliquam,eros,tristique,quam,a,tempor,netus,neque,vel,tincidunt.Inceptos,porta,id,nunc,platea,aptent,orci,litora,maecenas,vivamus,,at,consequat,convallis,tempus,pharetra,lorem,enim,est,,ultrices,nunc,velit,urna,gravida,sem,molestie,sem,faucibus,habitasse,feugiat,id,pulvinar,etiam,pretium,,a,donec,eu,sapien,suscipit,pretium,nam,,elit,nam,sagittis,suspendisse,fermentum,bibendum,sed,adipiscing,scelerisque,id,et,faucibus,adipiscing,aenean,nostra,,duis,purus,odio,feugiat,fringilla,eu,primis,donec,,ultrices,lacinia,justo,euismod,nullam,class,litora,est,tempus,tortor,phasellus,massa,praesent,sit,vehicula,eu,consectetur,felis,dapibus,interdum.Class,fringilla,luctus,a,semper,hendrerit,quisque,mattis,,netus,potenti,pellentesque,risus,scelerisque,mi,pulvinar,morbi,,aenean,eros,posuere,rhoncus,semper,aliquam,eget,mi,aliquam,sapien,sem,scelerisque,ornare,ultricies,,sem,tempus,aliquet,potenti,nulla,vel,bibendum,,ornare,accumsan,varius,at,himenaeos,suscipit,netus,nisi,fermentum,habitant.Volutpat,at,iaculis,nam,a,habitasse,dictum,ipsum,hac,quisque,aliquam,vestibulum,gravida,vehicula,arcu,donec,dolor,faucibus,consequat,vivamus,,curabitur,luctus,justo,vivamus,duis,accumsan,tellus,,blandit,commodo,etiam,vivamus,ultricies,fermentum,curabitur,pretium,sociosqu,in,praesent,vulputate,dictumst,aptent,,tempor,porttitor,ligula,duis,nulla,non,platea,consequat,fermentum,,platea,tortor,convallis,feugiat,tincidunt,donec,scelerisque,ultricies,convallis,pulvinar,porta,nam,porttitor,lacus,,aenean,euismod,cubilia,magna,ut,,tortor,dolor,dui,nam,egestas.Dui,eros,nisi,in,habitasse,vulputate,bibendum,pulvinar,fusce,,platea,integer,rutrum,mattis,varius,cras,lorem,,etiam,nisi,lectus,nullam,egestas,consectetur,at,non,eros,nostra,pellentesque,hac,nullam,curabitur,consequat,nunc,,inceptos,lacinia,quisque,donec,porta,placerat,potenti,non,nam,tempor,et,odio,lectus,netus,auctor,,sollicitudin,sodales,erat,etiam,arcu,ligula,faucibus,,aenean,mauris,vel,elementum,duis,mollis,convallis.Suscipit,lobortis,purus,gravida,euismod,duis,luctus,eu,lacus,condimentum,,duis,vitae,leo,lacinia,proin,laoreet,vehicula,sollicitudin,,feugiat,ut,viverra,per,mattis,integer,quisque,erat,semper,scelerisque,inceptos,neque,lacinia,varius,vehicula,ac,,hac,mauris,rutrum,pulvinar,cursus,amet,,eros,ullamcorper,ad,non,facilisis,eu,primis,venenatis,commodo,phasellus,enim,fringilla,maecenas,convallis,eget,duis,ornare,lacinia,id,eros,class,malesuada,aenean,proin,etiam,aliquam,faucibus,tempor,,at,arcu,pretium,luctus,ut,curae,iaculis,varius,,lorem,tempus,a,fermentum,duis,ut,erat,sollicitudin,id,tincidunt,quisque,cursus,sed,imperdiet,volutpat,torquent,mattis,placerat,quis.Lectus,class,vulputate,ut,lacus,litora,,dictum,sollicitudin,sociosqu,platea,vivamus,,fermentum,libero,quam,commodo.Sollicitudin,blandit,urna,quam,egestas,risus,condimentum,varius,semper,,magna,enim,pharetra,molestie,rhoncus,tempus,interdum,,ad,taciti,malesuada,lobortis,felis,class,a,tincidunt,duis,convallis,netus,vitae,per,orci,viverra.Morbi,nibh,tincidunt,aenean,nulla,sapien,volutpat,tellus,interdum,facilisis,potenti,aliquam,ante,mauris,,varius,neque,ultrices,nisl,tempus,est,risus,vehicula,pretium,maecenas,class,sollicitudin,blandit,a,sodales,per,tincidunt,viverra,eros,,torquent,cras,curae,volutpat,torquent,sociosqu,,luctus,nibh,lacus,tincidunt,vulputate.Auctor,sapien,vivamus,sapien,aenean,ligula,cursus,cubilia,vehicula,aliquam,,neque,purus,ultricies,mauris,fringilla,varius,ante,proin,etiam,neque,odio,habitasse,curabitur,id,magna,diam,tincidunt,fringilla,,vulputate,fermentum,taciti,vel,quisque,volutpat,eget,vehicula,per,quisque,eleifend,aenean,risus,torquent,quisque,,risus,netus,torquent,accumsan,netus,,sodales,habitant,malesuada,tempor.Consectetur,lobortis,molestie,senectus,pharetra,rhoncus,,amet,pellentesque,eleifend,proin,porttitor,etiam,,congue,pellentesque,iaculis,nibh,cubilia,velit,leo,per,fringilla,risus,class,augue,netus,,placerat,habitant,integer,mollis,scelerisque,aenean,pulvinar,,molestie,leo,iaculis,posuere,eget,dictum,lobortis,commodo,ac,elementum,ullamcorper,dictumst,dui,lectus,fames,etiam,eleifend,,dolor,interdum,vitae,tortor,taciti,vel,tellus,sagittis,quam,iaculis,,fermentum,phasellus,himenaeos,mauris,aliquet,vehicula,ut,fringilla,tempor,habitant,ligula,viverra,fusce,sapien,euismod,rhoncus,orci,ultrices,,enim,etiam,purus,fringilla,nulla,varius,pulvinar,ac,suspendisse,curabitur,,rutrum,habitant,quis,taciti,pulvinar,aenean,duis,augue,per,primis,diam,ultrices.Ac,eleifend,elementum,sollicitudin.Semper,feugiat,quisque,ut,sociosqu,orci,hendrerit,ad,pulvinar,,curae,aliquam,interdum,condimentum,nulla,duis,sapien,metus,,diam,dictum,porttitor,quisque,id,semper,etiam,augue,cursus,ante,faucibus,metus,interdum,pulvinar,,lectus,sem,maecenas,mattis,leo,,urna,potenti,iaculis,arcu,augue,conubia,congue,dolor,hendrerit,tempor,primis,praesent,pretium,molestie,,pharetra,eros,posuere,aliquam,lacus,maecenas,imperdiet,nec,congue,suspendisse,enim,vulputate,turpis,viverra,himenaeos,dapibus,potenti,egestas,augue,mattis,sem; var words = input.Split(','); int totalWords = words.Length; string[] trimmedWords = new string[totalWords]; for (int i = 0; i < totalWords; i++) trimmedWords[i] = words[i].Trim(); var hs = new HashSet<string>(); var dic = new Dictionary<string, int>(); for (int j = 0; j < totalWords; j++) { string word = trimmedWords[j]; int wordLength = word.Length; for (int i = 0; i <= wordLength - 3; i++) { string triplet = word.Substring(i, 3); if (!hs.Contains(triplet)) { hs.Add(triplet); dic[triplet] = 1; } else dic[triplet]++; } } // there might be a faster way to sort by value var sortedList = dic.OrderByDescending(x => x.Value); string output = sortedList.First().ToString(); // shows 50 most used triplets, just for checking //var sortedList = dic.OrderByDescending(x => x.Value).ToList(); //string output = string.Join(Environment.NewLine, sortedList.GetRange(0, sortedList.Count >= 50 ? 50 : sortedList.Count)); Console.WriteLine(output); Console.ReadKey(); }}I'm using HashSet to lookup and add new triplets, because it's the fastest thing I know in C# that can do this.I am not entirely sure about using a Dictionary<string, int> for storing the number of triplet occurrences. A faint voice in my head says something about arrays, but I can't make out the rest :)Also just sorting the dictionary and getting the first element with Linq doesn't seem like the best approach, but unfortunately I don't know a better way yet.How could this application be improved in terms of performance and code quality?
Finding the most frequently used sequence of characters in a comma-delimited input string of words
c#;performance;strings
string[] trimmedWords = new string[totalWords];for (int i = 0; i < totalWords; i++) trimmedWords[i] = words[i].Trim();You should learn about LINQ. (Or maybe just learn more, you're using it elsewhere.) With it, you can write this as (possibly adding ToArray() if you require the result to be an array):vat trimmedWords = words.Select(w => w.Trim());for (int j = 0; j < totalWords; j++){ string word = trimmedWords[j];This is the only place in the whole loop where you're using j, so you should have used foreach instead, since it's simpler.if (!hs.Contains(triplet)){ hs.Add(triplet); dic[triplet] = 1;}else dic[triplet]++;I don't see any reason for the HashSet here, Dictionary works just as well for deciding whether it contains something (use its ContainsKey() method).var sortedList = dic.OrderByDescending(x => x.Value); string output = sortedList.First().ToString();If you want just the largest value, then sorting the whole collection is unnecessary. You could use MaxBy() from MoreLINQ to do this (or write one yourself, it's not hard).You could also use LINQ instead of the Dictionary and HashSet, a fully LINQed solution would be:input.Split(',') .Select(w => w.Trim()) .SelectMany(w => Enumerable.Range(0, w.Length - 2).Select(i => w.Substring(i, 3))) .GroupBy(t => t) .MaxBy(g => g.Count()) .Key(Though I'm not saying writing everything in a single LINQ expression is the best solution here.)
_unix.242374
After extracting Popcorn-Time-linux32.tar.gz, it shows these 4 files: libffmpegsumo.so, nw.pak, package.nw e o Popcorn-time.How to install it on Linux Mint 17 Cinnamon 32-bit (v 2.2.16)?
Installing Popcorn Time SE
linux;linux mint
null
_softwareengineering.259930
As a junior developer, I'm working in a company that develops software for the airline industry. We have a test team, so I don't have any motivation to learn testing software. My friend is working for a small company as an back-end developer. Their team doesn't have any specific test team, and they do their tests on their own. Should a back-end developer learn about testing software?
As back-end developers, should we learn software testing?
testing;backend
Absolutely and unequivocally: yes!It's a core skill which you will be expected to have at a large percentage of companies you'll want to work for in the future.As a developer, the technical aspects of testing are more interesting than than the methodological ones: learn using a unit testing framework, set up automated testing, try doing test-driven development to see how you like it.If you want to specialize in it, performance/stress testing and security/penetration testing are quite sought-after skills.
_codereview.30895
I wrote this class to make cookie management easier.I know it makes use of serialize(), but I have no intention of storing very much data in the cookie, and it seemed a cleaner solution than, say, the JSON functions (like, even if a class implements the JSONSerializable interface, it doesn't retain the class name by default, etc.). serialize() seemed more robust, although if there's a way to compress the output without it losing its integrity, please share. Probably the worst pitfall is that, if the cookie is messed with, unserialize() will trigger a notice and who knows what else -- but I don't feel I need to cater to the user experience of users who mess with cookies. (Although if the cookie is maxed out at a number of bytes, like 4,096, and it truncates, that could be an issue....)I am in the process of writing a class to put on top of this one for managing user sessions implementing Charles Miller's solution.I decided against implementing exceptions because it was simple enough to just return constants.<?php/** * Cookie.class.php, the Cookie class * * Contains a class for making cookies easier to manage via PHP * @author Miller <wyattstorch42 at outlook dot com> * @version 1.0 * @package Miller * @subpackage Utils */namespace Miller\Utils;if (!function_exists('array_copy')) { /** * array_copy Properly and recursively clones an array * @param array $source The original array * @return array The clone */ function array_copy ($source) { $return = array (); $keys = array_keys($source); $values = array_values($source); for ($i = 0; $i < count($keys); ++$i) { if (is_object($values[$i])) { $return[$keys[$i]] = clone $values[$i]; } else if (is_array($values[$i])) { $return[$keys[$i]] = array_copy($values[$i]); } else { $return[$keys[$i]] = $values[$i]; } } return $return; }}/** * A class for making cookies easier to manage via PHP * @package Miller\Utils */class Cookie { /** * Class constants * SESSION, EXPIRE, DAY, WEEK, MONTH, and YEAR are used to define the life of the cookie * ERROR_HEADERS_SENT, ERROR_SET_COOKIE, and ERROR_NONE are possible return values for the sent() method. */ const SESSION = 0, EXPIRE = -3600, DAY = 86400, WEEK = 604800, MONTH = 2592000, YEAR = 31536000, ERROR_HEADERS_SENT = -1, ERROR_SET_COOKIE = -2, ERROR_NONE = 1; protected /** * Holds the name of the cookie * @var string */ $name, /** * Holds the expiration timestamp of the cookie * @var integer */ $expiry, /** * Holds the path of the cookie * @var string */ $path, /** * Holds the domain of the cookie * @var string */ $domain, /** * A flag that sets the secure option for the cookie * @var boolean */ $secure, /** * A flag that sets the httponly option for the cookie * @var boolean */ $httponly, /** * An array that holds the current unserialized properties stored in the cookie * @var array */ $properties, /** * An array that holds the properties that will be stored and serialzed in the cookie on send() * @var string */ $internalProperties; public function __construct ($name, $expiry = self::WEEK, $path = '', $domain = '', $secure = null, $httponly = false) { /** * Constructor * @param string $name The name of the cookie * @param null|integer|string $expiry The expiration timestamp of the cookie (if null, sets a session cookie; if string, converts using strtotime()) * @param string $path The path of the cookie * @param string $domain The domain of the cookie * @param null|boolean $secure The flag that sets the secure option for the cookie (if null, sets to true if $_SERVER['HTTPS'] is set, false otherwise) * @param boolean $httponly The flag that sets the httponly option for the cookie */ $this->name = (string) $name; if ($expiry === self::SESSION) { $this->expiry = $expiry; } else if (is_numeric($expiry)) { $this->expiry = time()+$expiry; } else { $this->expiry = strtotime($expiry); } $this->path = (string) $path; $this->domain = (string) $domain; $this->secure = $secure === null ? isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] : (bool) $secure; $this->httponly = (bool) $httponly; $this->properties = array (); $this->internalProperties = array (); if (isset($_COOKIE[$this->name])) { $properties = unserialize($_COOKIE[$this->name]); $this->internalProperties = array_copy($properties); $this->properties = array_copy($properties); } } public function exists () { /** * Checks if the cookie was sent from the last browser request * @return bool True if the cookie is set, false otherwise */ return (bool) $this->properties; } public function __isset ($property) { /** * Checks if the given property is set on the cookie * @param string $property The property key * @return bool True if the property is set, false otherwise */ return isset($this->properties[$property]); } public function __get ($property) { /** * Returns the value of the given property on the cookie * @param string $property The property key * @return bool The value of the property if it is set, null otherwise (use __isset() to differentiate a null value from an undefined value) */ return $this->__isset($property) ? $this->properties[$property] : null; } public function __set ($property, $value) { /** * Sets or overrides the given property (will not be accessible until the cookie is sent) * @param string $property The property key * @param mixed $value The value * @return void */ $this->internalProperties[$property] = $value; }public function __unset ($property) { /** * Unsets the given property (will not be accessible until the cookie is sent) * @param string $property The property key * @return void */ if (isset($this->internalProperties[$property])) { unset($this->internalProperties[$property]); }} public function send () { /** * Serializes the properties and sends the cookie to the browser. On success, updates the values of the properties. * @return integer ERROR_HEADERS_SENT if the headers have already been sent, ERROR_SET_COOKIE if the setcookie() function failed, or ERROR_NONE on success */ if (headers_sent()) { return self::ERROR_HEADERS_SENT; } $value = $this->expiry === self::SESSION ? false : serialize($this->internalProperties); if (setcookie($this->name, $value, $this->expiry, $this->path, $this->domain, $this->secure, $this->httponly)) { $this->properties = array_copy($this->internalProperties); return self::ERROR_NONE; } return self::ERROR_SET_COOKIE; }}?>Example usage:<?phpnamespace Miller\Utils;error_reporting(E_ALL);require 'Cookie.class.php';ob_start();$cookie = new Cookie('example_cookie', Cookie::SESSION);var_dump($cookie->exists()); // true if cookie is stored in the browser already, false otherwisevar_dump(isset($cookie->example_prop)); // true if example_prop exists in cookie, false otherwisevar_dump($cookie->example_prop); // the value of example_prop, or null if it is not set$cookie->example_prop = 123;var_dump($cookie->example_prop); // will still be the previous value, because the cookie hasn't been sentvar_dump($cookie->example_prop_2); // the value of example_prop_2, or null if it is not setunset($cookie->example_prop_2);var_dump($cookie->example_prop_2); // will still be previous value, because cookie hasn't been sent$cookie->current_time = new \DateTime('now', new \DateTimeZone('America/Phoenix')); // will serialize objects using PHP native function and unserialize automaticallyvar_dump($cookie->send()); // -1, -2, or 0 (ERROR_HEADERS_SENT, ERROR_SET_COOKIE, or ERROR_NONE)var_dump($cookie->example_prop); // if send() was successful, this will now be 123var_dump(isset($cookie->example_prop_2)); // if send() was successful, this will now be falsevar_dump($cookie->current_time); // if send() was successful, this will now be the recorded timeob_end_flush();?>
Cookie Management Class
php;object oriented;classes;recursion;php5
First off, I've posted a fairly length answer on the subject of request classes, which can be found here. Because you state you're thinking of writing a Session class on top of this one, I'm posting a link to my answer here.In that answer, I discuss what you should keep in mind when doing so. For example: using setters and getters, sanitize all request data etc...Then, as I said in the comment, I noticed you're using the ?> closing tag, which is optional. Omitting it, especially in those files that will be include or require-ed is considered good practice. It's, amoungst other things, to avoid excess whitespace. Read more hereAnother part of good practice is to write the doc-blocks just before the method definition, not in the function body. As soon as you start using the ReflectionClass (especially the getDocBlock method), you'll see the value of this. Even if you don't use it, other libs might (like Doctrine to name one, not unimportant example)You're also defining a method called __isset. The double underscore would suggest this is a magic-method, that enables the user of this class to write something like:if (isset($instance['cookieName']))And that php will convert that into if ($instance->__isset('cookieName')). That's not the case. The magic isset method only works when you write isset($instance->cookieName), which, to all intents and purpouses still is a different syntax.If I were in your shoes, I'd implement a Travesable interface, or the ArrayAccess interface. read through the examples, and you'll see array-like usage of isset is possible thanks to this interface.The last remark I'd like to make is the fact that your file is called Cookie.class.php, so I'd expect its contents to be just a class definition. It isn't, though: you're defining a function, too. That's just not nice. I'd suggest you read, and make sure to comply with the unofficial PHP-FIG standards. Though not official, all major players (check list here) subscribe to these standards. If your code complies, too, autoloaders from any of the major frameworks will just work with your classes.While I'm on the subject of autoloaders: implement them, use them, rely on them. If your classes are defined according to the aforementioned standards, you can do away with all those pesky require's. Even if you do need the occasional require: use the safer require_once variant. Sure it's a tad slower, but at least it's safe.Oh, and if you still need that array_copy in the Miller\Utils namespace, you could use a static method, since PHP statics are just globals in drag, or declare a global function and call it with a leading \.Still, look at where you're using it:public function __construct ($name, $expiry = self::WEEK, $path = '', $domain = '', $secure = null, $httponly = false){ $this->name = (string) $name; if ($expiry === self::SESSION) { $this->expiry = $expiry; } else if (is_numeric($expiry)) { $this->expiry = time()+$expiry; } else { $this->expiry = strtotime($expiry); } $this->path = (string) $path; $this->domain = (string) $domain; $this->secure = $secure === null ? isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] : (bool) $secure; $this->httponly = (bool) $httponly; $this->properties = array (); $this->internalProperties = array (); if (isset($_COOKIE[$this->name])) { $properties = unserialize($_COOKIE[$this->name]); $this->internalProperties = array_copy($properties); $this->properties = array_copy($properties); }}You're clearly using it to set properties inside the class, so why isn't this function a private method?Moving on to some actual code review: Your constructor is doing way to much work. Besides, when I create a cookie, I'd like to be able to set the data when I choose, not passing it all to the constructor. I'd like to use a Cookie class to check if a given cookie exists, and if it does, check when it expires, if it doesn't I'd like to create it and maybe determine its expiration date/time later on. Implement setters and getters for that.Also use these setters to sanitize whatever data is being passed to the constructor. Sure:$this->name = (string) $name;Assures you that the name property is bound to be a string. Good, but what if I passed an object. I'm not going to get an exception thrown, though I clearly passed an argument that is a good reason to throw an InvalidArgumentException. Don't just cast to the types you want, check if the arguments passed are:Castable to the type without loss of dataValid types in the first placeBy the second I mean that, if I were to accidentally pass an instance of PDO as name, I should be notified of the error in my code. Basically: your class is too reliant on magic-methods, it allows overloading of properties, which is terrible, especially with request objects (the request shouldn't be subject to change, unless there's a good method defined for it). Some constants (like the SESSION constant indicate a class of responsability, check first link to find out more).As ever: don't hush-up/work around errors. Throw exceptions when something is not quite right. You don't know why or how the name property was passed, and why it's not a string, nor does your class need to know. Just throw an exception. Let the user of your class fix his code.On the use of serialize: Since you're thinking about a session object: if you're going to use serialize, save it for the session, just don't use a cookie.On the __set method: check what the value is. If I'm setting something like:$instance->connection = $pdo;Your code won't complain, but you can't serialize a DB connection! In fact, there are quite a few things that can't be serialized. Google around a bit
_unix.348599
I have the following in my ~/.bashrc to hide the listing of test from the output of ls:alias ls='ls -I test'But I want it to only hide test if my current working directory is the root (/) folder, not if I am in some other folder.How may I achieve this?
Only if in / : alias ls='ls -I test'?
bash;ls;alias
Something like this i thought it would work:alias ls='[[ $PWD = / ]] && ls -I test ||ls'$PWD is the current working directory&& has the action to perform if pwd is / (condition check =true)|| has the action to perform if pwd is not / (condition check=false) But after carefull testing above solution IS NOT WORKING correctly.On the other hand this will work ok as alternative to functions:alias ls='{ [[ $PWD == / ]] && a=-I tmp2 ||a=; };ls $a 'Or even better, similar to other answers but without the need of function:alias lstest='{ [[ $PWD == / ]] && set -- -I tmp2 || set --; }; ls $@'Possible extra flags and/or full paths given in command line when invoking this alias are preserved and sent to ls.
_codereview.29521
I am quite new to Java, and I am trying to read a file into a string (or should I use byte arrays for this?). File can be anything, such as a text file or executable file etc. I will compress what I read and write it to another file.I am thinking of using this code:public static String readFile(File f) { StringBuilder sb = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(f))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { sb.append(sCurrentLine); } } catch (IOException e) { System.err.println(I/O Exception: + e.getMessage()); return null; } return sb.toString();}Does this look good to you? I was reading Reading and writing text files and I was a little bit confused over all the different ways one can use to read files.
Reading a file into string in Java
java;beginner;io
null
_webmaster.86702
How can I handle the Swedish, Danish and Russian characters in URLs so that Webmaster tools would stop returning 404 errors.Note that opening the URL using the character as is is fine, but Google encodes the characters such as: becomes %25C3%25A4 and becomes %25C3%25B6. Any help would be appreciated.
404 errors in webmaster tools on URLs containing swedish characters like ,
google search console;url encoding
null
_unix.157569
when doing a locate to find a specific file, it shows alot of stuff, but is there a way to inverse what is shown? Ex. locate anything that has the word drupal in it, but don't show anything from the home directory.
How do you inverse a locate command. Ex. Show everything except X
locate
null
_unix.354807
I have a file with a start and end number, like belowStart,end,code43786,67883,avb200,400,add12,14,adfI need to however rewrite this so that all the numbers in the range between start and end are written with their code:43786,Avb43787,avb43788,avb43789,avbTill the last 67883,avb in that range and continue to200,add201,add202,add
Expand a range of a file based on columns
awk
null
_scicomp.27674
I would like to solve a system of second-order differential equations to describe the dynamics of a system of particles.Two Newton-like forces are responsible for the motion of each particle $i$: A force acting on each particle due to other particles $f_{i,j}$ and a stochastic term of noise $f_{\mathrm{noise}}$.The force acting on each particle due to other particles $f_{i,j}$ depends on the current position $s_i$ and velocity $v_i$ of particle $i$ and the position $s_j$ and velocity $v_j$ of the other particles $j$ of the system. $$F_i= f_{i,j}(v_i,v_j,s_i,s_j) + f_{\mathrm{noise}}$$ The two components of motion in 2D are included for every term before mentioned.Under an Euler scheme, the velocity and position of each particle would be updated as follows:$$\begin{alignat}{1}v_i & v_{i} + \frac{F_i}{m} \Delta t \\s_i & s_i + v_i \Delta t\end{alignat}$$where $m$ is the mass of particle $i$ and $\Delta t$ is the integration step.However, I would like to use the Milsteins algorithm for the velocity update (since we have a term of noise) and the fourth-order Runge-Kutta method to update the position $s_i$. I am confused due to having $f_{i,j}$ dependent on $s_i$, $s_j$, $v_i$ and $v_j$. How should I operate?
Runge Kutta and Milstein system of second-order coupled differential equations with noise
runge kutta;stochastic;differential equations;particle
null
_softwareengineering.224350
I am talking based on experience with Java and C#. I do not know if other language have different exception handling implementation.In order to achieve loose coupling, we need our code being programmed to use abstraction rather than implementation. However the exception handling case is the opposite. The best practice is you need to handle specific exception type (SqlException, StackOverflowException, etc).This thing may be better (or not) in java thanks for it's Checked Exception, there is a kind of contract between the interface and the consumer. But in C# or for the Unchecked Exception there is no contract about what exception can be thrown by the interface.For example, say that we use Repository Pattern to decouple the DAL with BLL. The simple catch exception usually be used like:public void Consume(){ try{ productRepository.Get(k=>k.Id == 0001); } catch(Exception e){ // handle }}In more specific case we usually use SqlException. However it means that we must know that the ProductRepository is a repository to database server. What if the implementation changed to use file repository instead? Now you need to catch FileNotFoundException or something like that.Why does it violates the code to abstraction principle? And what can we do to prevent it?
Does Exception Handling Violates Program to Abstraction?
object oriented;exceptions;abstraction;separation of concerns
You should handle a specific case where it's appropriate to handle that specific case.In your example, the consumer is not the appropriate abstraction level to handle a SqlException, as you've surmised.The repository itself, which knows it is retrieving from a database, should be what handles the SqlException, perhaps repackaging it into a more application-specific and custom DataAccessException that can then be handled appropriately by the consumer.If you change the repository implementation to pull data from, say, a web service, that repository can handle an HttpException and repackage it into the DataAccessException. Or an XML repository can handle XML-specific exceptions and repackage them. And so forth.
_webmaster.71206
I ask because a few of my servers are currently being scanned by 5+ bots: Bing, Google, Baidu, Sougu, and Yandex, along with Google's mobile bots and others. Is this just bad luck or could something have prompted all of these bots to scan my sites?These sites have been up for a long time, and only one has had any recent changes. Even those changes were minor.
What would prompt multiple web crawlers to scan a site?
webserver;web crawlers;googlebot
null
_codereview.47636
Is it possible to shorten this piece of PHP code?Honestly, I think it does not look clean but like a mess.if(Input::exists() && $token) { if($validation->error('firstname') && $validation->error('lastname')) { echo str_repeat(' ', 20), '<div class=addition error> You did not enter your name.</div>', \n; } else if($validation->error('firstname')) { echo str_repeat(' ', 20), '<div class=addition error> You did not enter your first name</div>', \n; } else if($validation->error('lastname')) { echo str_repeat(' ', 20), '<div class=addition error> You did not enter your last name.</div>', \n; }}if(!Input::exists()) { echo str_repeat(' ', 20), '<div class=addition> We will address you by this name.</div>', \n;}if(Input::exists() && $token) { if($validation->error('emailConfirm') == 'match') { echo str_repeat(' ', 20), '<div class=addition error> The email address you entered does not match.</div>', \n; } else if($validation->error('emailConfirm') == 'type') { echo str_repeat(' ', 20), '<div class=addition error> You did not re-enter a valid email address.</div>', \n; } else if($validation->error('emailConfirm')) { echo str_repeat(' ', 20), '<div class=addition error> You did not re-enter your email to confirm.</div>', \n; }}else if(!Input::exists()) { echo str_repeat(' ', 20), '<div class=addition> Re-enter your email to make sure it\'s correct.</div>', \n; }
Shortening if-statements of displaying errors
php;validation
You are repeating the same code:echo str_repeat(' ', 20), '<div class=addition error> You did not enter your name.</div>', \n;Replace it with a function which will do the job:function message($content, $class = ''){ return str_repeat(' ', 20) . '<div' . (($class) ? class='$class' : '') . >$content</div>\n;}You are using construction:if () {} else if() {}This is the same as: if () {} else { if() {} }I guess, that it is not what you want to use, the correct construction should be:if () {} elseif() {} The code itself can be rewritten like this:function message($content, $class = ''){ return str_repeat(' ', 20) . '<div' . (($class) ? class='$class' : '') . >$content</div>\n;}if (!Input::exists()){ echo message('We will address you by this name.', 'addition'); echo message('Re-enter your email to make sure it\'s correct.', 'addition');} elseif (Input::exists() && $token) { if($validation->error('firstname') && $validation->error('lastname')) { echo message('You did not enter your name.', 'addition error'); } elseif($validation->error('firstname')) { echo message('You did not enter your first name', 'addition error'); } else { echo message('You did not enter your last name.', 'addition error'); } if($validation->error('emailConfirm') == 'match') { echo message('The email address you entered does not match.', 'addition error'); } elseif($validation->error('emailConfirm') == 'type') { echo message('You did not re-enter a valid email address.', 'addition error'); } else { echo message('You did not re-enter your email to confirm', 'addition error'); }}
_softwareengineering.96589
I just recently learnt ruby on rails using ruby 1.9.2 and rails 3 using Michael Hartl's tutorial. I'm making an application which I wanted to host on my preexisting server. However, I found that they still do not support rails 3 as it breaks compatibility with mongrel.My question is: How difficult will it be to port my whole Rails 3 app onto Rails 2 if need be? Keep in mind that although I understand rails 3 quite well by now, I have never used rails 2 and do not have any idea of the differences between them.
Ruby on Rails: Converting a Rails 3 app to Rails 2?
ruby on rails;porting
null
_unix.323755
For some strange reason I can't execute curl -L https://github.com/Blosc/c-blosc/archive/v1.8.1.tar.gz. I need it for some package installation of Blosc that utilizes curl.I get the error:curl: (77) Error reading ca cert file /etc/pki/tls/certs/ca-bundle.crt - mbedTLS: (-0x3E00) PK - Read/write of file failedSo there is not cert in the location. Fine. So I converted my ca-bundle.pem from /etc/ssl into .crt and copied it to that location.Now I get:url: (51) Cert verify failed: BADCERT_NOT_TRUSTEDGreat. I read something about the update-ca-trust tool, but that doesn't seem to be installed on openSUSE 42.1 Leap. So I could add the cert to /etc/pki/ca-trust/source/ and update. Anyhow why is it not trusted. Its already there. Or do I need to create a new one in YAST?Thanks
curl -L not working on openSUSE Issue with Certificate
opensuse;curl;certificates
null
_unix.65741
I have two drives in a mirror (linux sw raid/mdadm); one drive somehow left the mirror in the past and its content is now several days old. At this moment, I'm using degraded mirror (with one drive missing) and considering:clone uptodate drive to the second one with ddadd second drive and resync, but I don't know how resync process works and which data will be overwritten (there are LVM volumes on that mirror)I think dd is safe way, anyway I'm interested in how resychronization works.
How does mdraid resync work?
dd;synchronization;software raid;mdadm
The right thing to do is something like mdadm --add /dev/md0 /dev/sdb1. Use the correct array in place of md0 and the correct partition in place of sdb1.The key thing is the array is running. Its completely unambiguous which data to copy: the data that is currently running. If you have bitmaps enabled, the resync will be fairly fast as it'll only copy what has changed. Otherwise, it'll copy everything.If you are extremely paranoidor you're worried that your disk system may have lost writes, and the bitmap may not be correctand don't mind forcing a full copy, you can wipe the superblock on the disk you're about to add using mdadm --zero-superblock /dev/sdb1 (once again, use the correct partition).If the array wasn't currently running (e.g., if this were a rebuild on assemble from an unclean shutdown), then the decision on what to copy is made using the update count fields stored in the superblock. Its possible that it may refuse to re-add a disk with a too-high update count (forcing you to zero the superblock), but it won't overwrite the active data.If you were to use the dd approach, then: (a) You'd wind up copying the superblock, and you'd wind up with two disk 1s (the superblock stores the position of the disk in the array); (b) you'd have an inconsistent copy, unless you had the array stopped (or maybe in read-only mode) during the copy. (And then, to fix a and b, you'd wipe the superblock and let mdraid copy the data, as above).In short, when you decide to use mdraid (or any other RAID), you give management of redundancy to it. You almost never want to go around it. Same with LVM: if you want to move data around, you use pvmove, etc. You don't use dd.PS: one drive somehow left the mirror is not something you should accept. There are logs; figure out why it left the mirror. With even a half-recent kernel, bad blocks don't drop drives out anymore, so random drive drops should not happen. Check smart status, etc.
_unix.97062
I tried to transfer ('cut and paste') about 2gb of files from my system (running Linux Mint 15, KDE 4.2) onto my USB stick (8gb capacity). The notifications manager indicated that the copy was complete, so I removed the USB drive and mounted it on my other computer. Then it showed that only one of the files had been written to the USB.Is there any way for me to recover the missing files?
Recover Files Incorrectly Written to a USB?
linux mint;data recovery
mv returns as soon as the files have been moved from the applications' point of view. If any program tries to read the files after mv returns, it will find them on the USB stick and not on the hard disk. However, it is possible that the content of the files and the updated directory on the USB stick are still in the disk buffers and not yet written out to the USB stick.If you pull out the USB stick without unmounting it first, there is no guarantee that the USB stick has all the data that it's supposed to have, or indeed that it's in a consistent state (it's unlikely, but possible, that old files will be temporarily unreachable).Always unmount removable drives before disconnecting them.The sync mount option reduces the window of risk at the expense of making writes slower, but it does not remove the risk. It also kills older USB sticks faster.The files may or may not still be on your computer. Linux does not make recovering deleted files easy. If this was a lot of small files, forget it. If this was a few big files, especially if the files have a recognizable format (pictures, mp3s, videos, ), you have a chance. Stop writing to the drive immediately: anything you write reduces the chance of recovery. If this is your system drive, download and reboot to a special-purpose distribution. If not, install carving tools with your distribution's package manager. See How to recover data from a bad SD card? for some tool names.
_cs.60601
Do CPUs have big circuits such as asynchronous multipliers or BCD to binary converters?An asynchronous multiplier is much bigger than an adder. It's about 18*n^2 NOR gates where n is the number of bits. An adder is about 15*n NOR gates. But for a 32-bits multiplication, a multiplier with successive additions will need 32 clock cycles, while an asynchronous mutliplier only 1. I think it's a big performance gain.The same is for BCD to binary converter.
Do CPUs have big circuits such as asynchronous multipliers or BCD to binary converters?
circuits;cpu
null
_unix.304268
I need to run a script that sshs to another machine on my local network,(I've RSA key paired them), after sshing in, I need to run a command and get the results of the command in the local script (to parse), and then run another command built from some of the info from the first command.Here is a step by step account of what I want to do:ssh into a machine running FileMaker Server 11get a list of the clientssearch for a certain clientif that client is logged on, get its ID from the listsend a Disconnect ID command to the FileMaker serverexit out.Hope this isn't too garbled.
pseudo interactive ssh script
shell script;ssh
null
_softwareengineering.221644
A class loads properties from a file and uses those as it performs its duties. For testing purposes I want to be able to modify said properties directly without having to use a test properties file. I did the implementation, but it seems filled with smells -- I'm wrestling with keeping this thing small (avoiding frameworks like Spring that will wrap and inject the properties).In particular, I cannot recall seeing a constructor that initializes itself via a statically loaded set of properties -- particularly that it sets variable values from somewhere other than passed-in parameters.I'm looking for arguments for/against this approach, and hoping to hit upon some alternatives if this is really as uncool as I think it is. private static final String CONFIG_FILE_NAME = String.format(config-%s.properties, null != System.getProperty(JAVA_ENV) ? System.getProperty(JAVA_ENV) : development);static { PROPERTIES = new Properties(); try { PROPERTIES.load(MyClass.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME)); if (PROPERTIES.keySet().size() < 1) { LOGGER.error(String.format(failed to load %s: no properties, CONFIG_FILE_NAME)); } } catch (final IOException ie) { LOGGER.error(String.format(failed to load %s, CONFIG_FILE_NAME), ie); }}private String property1;private String property2;public MyClass() { property1 = PROPERTIES.getProperty(prop.1); property2 = PROPERTIES.getProperty(prop.2);}/* public accessors for property1 and property2 go here */
Initializing properties that aren't parameters in a constructor: alternatives
java;constructors
To start with, static initializer of a named class or interface can not throw a checked exception (JLS 11.2.3. Exception Checking). That is, if application design somehow involves checked exceptions for various problems at initialization, static initializers are simply not an option.Given your code snippet, you already noticed this - your catch block just logs IOException without re-throwing it. But even without checked exceptions, this is quite a troublesome practice. You can test that by adding code that re-throws runtime exception from your catch block (this will compile) and simulating the absence of config file.Think of how it would feel to those maintaining your application when they get logs reporting an obscure ExceptionInInitializerError for a routine typo in config file name.Yet another reason why this practice isn't convenient can be found in JLS 12.4.1. When Initialization Occurs...Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization...Above means that you give up a lot of control for when initialization occurs. Some framework may trigger it when you don't even expect it. If memory serves, in my practice this happened once when logging was't yet fully initialized - believe me, it was no fun to investigate why application crashes when log files were empty.The last but not the least, this design is very inconvenient for unit testing purposes. Whenever you would want to use MyClass in unit tests, you'd have to ensure that 1) config file is there in file system and 2) that it is stuffed with desired values and properties.Compare this design to constructor that simply takes Properties as a parameter: MyClass(Properties properties) { this.properties = properties; // initialize field from constructor parameter }Testing with class constructed like above is as easy as it gets. No messing with the filesystem, no messing with filling the file with desired properties and values, plain Java code. You create Properties object and stuff it however you want, straight from your test code, wherever it is, whenever it is convenient to you.Summing up, there are plenty reasons why you cannot recall seeing a constructor that initializes itself via a statically loaded set of properties.
_softwareengineering.332475
I have basic viewmodel on server-side, let it be on C# language and ASP.NET Core server-side, for example:public class BookViewModel{ public string Id { get; set; } public string Name { get; set; } //other properties removed for brevity}Then, I send it to client page. On client-side, I have rich UI with some Javascript MVVM framework.These frameworks manipulates with viewmodels as I understand. So, the trouble, is that I don't understand what we really must do with viewmodels on client-side?I mean, If I want send my viewmodel from client to server via Ajax, I need explicitly define all properties of that viewmodel. So, I need explicitly define all my server-side viewmodels, as Javascript objects in special file, whatever. How can I avoid such routine work?
Misunderstanding of viewmodels relations on client and server side
c#;javascript;productivity;server side;client side
Using tooling. Most mature frameworks have mechanisms to produce client code from a server model/wsdl/schema etc. Sometimes these are known as code generators. Typically something is inspected on the server side and then produces code that is native to the framework being used on the client.Be aware that auto-generated code can sometimes be less then optimal but it can be tweaked as needed.Here's an example:C# to Knockout View ModelThe client model is sometimes different than the server's model so sometimes there a translation layer between the server model and the client. The items that come down from the server are not used directly, but translated from the message into the client's model.Code it manually. Yes this is laborious/tedious.
_codereview.114205
I am new to Java / OOP and I'm concerned that I have a method which is doing far too much stuff - but I don't easily see how it can be shortened in a way which is not contrived / arbitrary.This is a server-side API method built using Google App Engine.Currently, the method (which is really just a template at this stage):Validates a user's Facebook OAuth token against Facebook's ownservers - this is all done behind the scenes in a FacebookHelperclass I have written. Catches any exceptions (most likely an IOException) thrown during this validation process.Asks the user to log in again if their token is invalid (if (authToken == null)).Else if authentication has been successful, tries to get the user record from my database.If it doesn't exist, adds the user to the database. (registerUserInDatabase).Responds with a personalised welcome to the user - after having registered the user if they were not already registered.Code:@ApiMethod(name = getUserData, path = get_user_data)public Bean getUserData(@Named(token) String token) { Bean response = new Bean(); FacebookAuthToken authToken; User user; String userPersonalisedWelcome; try { authToken = ServerFacebookHelper.getAuthToken(token); } catch (Exception e) { response.setData(Exception occurred); return response; } if (authToken == null) { response.setData(Token invalid, please log in); return response; } else { user = getUserFromDatabase(authToken); if (user == null) { user = registerUserInDatabase(authToken); userPersonalisedWelcome = user.getPersonalisedWelcome; response.setData(userPersonalisedWelcome); } else { response.setData(user.getPersonalisedWelcome); } return response; }}Obviously there is already a huge amount of work being done outside this method, such as API calls and database reads/writes, but it still feels far too procedural and frankly dumb. At the same time, everything it encapsulates is required in order to service this getUserData API request - so perhaps I am overthinking here.
API method to validate Facebook OAuth token
java;api;google app engine;facebook;oauth
null
_webmaster.54080
As an example, how would I enter the following key words in google adwords/keywords tab:Best guaranteed jump rope -freeFor example, I would want to get any googler who entered anything similar to the following...best guaranteed jumpropetop guaranteed jump ropesBest jump ropes with guarantees..and NOT get the anything like the following..best jump ropestop free jump ropesNote the terms are fictional but in general what I want to do is have two critical adjectives (ex: best and guaranteed) a critical two-word phrase (ex: jump rope) and a critical negative keyword (ex: -free)How exactly would this need to appear in the key word screen?I am a little confused because there is a Phrase Match but that seems to make the whole textbox a phrase rather than just one component within the textbox a phrase.And there are multiple textboxes. And a separate section for negative key words but also a negative symbol which implies no need for a negative keywords section.is this right?+best +guaranteed +jump +rope -free(do I select broad or exact match?)Thx
how do I enter multiple keywords and phrase in google adwords
google;keywords;google adwords
null
_ai.1401
It is possible of normal code to prove that it is correct using mathematical techniques, and that is often done to ensure that some parts are bug-free. Can we also prove that a piece of code in AI software will cause it to never turn against us, i.e. that the AI is friendly? Has there any research been done towards this?
Can we prove that a piece of code in AI software will cause it to never turn against us?
friendly ai
Unfortunately, this is extremely unlikely.It is nearly impossible to make statements about the behaviour of software in general. This is due to the Halting problem, which shows that it is impossible to prove whether a program will stop for any given input. From this result, many other things have been shown to be unprovable.The question whether a piece of code is friendly, can very likely be reduced to a variant of the halting problem.An AI that operates in the real world, which is a requirement for friendliness to have a meaning, would need to be Turing complete. Input from the real world cannot be reliably interpreted using regular or context-free languages.Proofs of correctness work for small code snippets, with clearly defined inputs and outputs. They show that an algorithm produces the mathematically right output, given the right input.But these are about situations that can be defined with mathematical rigour.Friendliness isn't a rigidly defined concept, which already makes it difficult to prove anything about it. On top of that, friendliness is about how the AI relates to the real world, which is an environment whose input to the AI is highly unpredictable.The best we can hope for, is that an AI can be programmed to have safeguards, and that the code will raise warning flags if unethical behaviour becomes likely - that AI's are programmed defensively.
_cstheory.17523
Are there any size depth trade-offs known for monotone arithmetic circuits that compute permanent and determinant?
Size depth tradeoffs for monotone arithmetic circuits
arithmetic circuits
null
_webapps.57681
I've heard that Google has supported, for a while now, multiple email addresses linked to a single account. Now, I've had, for many years already, accounts for two addresses of mine - with different group memberships etc. Can I merge these two accounts somehow? And if so, how?
How can I join the Google accounts for two email addresses?
google account
It isn't currently possible to merge separate Google Accounts.Source: https://support.google.com/accounts/answer/63304?hl=en
_unix.106601
I have a function which converts epoch time to date. Here is the definitiondate1(){ date -d @$1}I'd like to be able to write:$ date1 xxxyyyWhere xxxyyy is the parameter I pass into my function so I can get the corresponding date. I understand I have to add it in either .bash_profile, .profile, or .bashrc and then source it:$ source fileBut, I'm not sure which file to put it in. Currently, I have it in .profile.But to run it, I have to do source .profile every time.Ideally, it should make it available, when the computer starts up like the environment variable.
How to add a function to .bash_profile/.profile/bashrc in shell?
bash;shell;function;profile
From man bash:When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable.In other words, you can put it in any one of ~/.bash_profile, ~/.bash_login or ~/.profile, or any files sourced by either of those. Typically ~/.profile will source ~/.bashrc, which is the personal initialization file, executed for login shells.To enable it, either start a new shell, run exec $SHELL or run source ~/.bashrc.
_webapps.105180
My spreadsheet is as follows (sorry about the crude setup). A B C D E F G1 Order FB? TW G+ YT LI Frequency?2 1 x - x - x daily3 2 - - - x x monthly4 3 - - - - x daily5 4 x x - - x never6 5 - - - - - never +1000 more rows with the same logicOn another sheet, I'm using COUNTIFS to extract the total number of those with daily, monhtly, etc frequency of publishing. Now, to my problem.Notice how in the sixth row nothing is marked? My problem is that this isn't the only row with that setup, and, as far as I can tell by skimming the filtered table, it only happens in the rows with the frequency of never.I would like to make a COUNTIFS which would look at the rows with the frequency of never and check if there's no x in any of the B-F columns for the corresponding row. These values shouldn't be counted. Or, to put things differently, it should only count a row with the frequency of never if there's at least one x in any of the B-F columns for the current row.I'm guessing I should use a combination of COUNTIFS and OR, but I'm not sure how.How can I achieve that?
Countifs with OR over a range
google spreadsheets
Crude but simple, please try:=countifs(G:G,never,B:B,<>x,C:C,<>x,D:D,<>x,E:E,<>x,F:F,<>x)There may be better answers (eg that don't apply countifs) but possibly depending upon whether your dashes are in your spreadsheet or just included above for presentation. For example, if those nevers are not to be counted you might consider whether you could filter to select those rows and delete them (presumably would leave gaps in Order however).Leave out the first pair (G:G,never,) and it count rows without any x regardless of what is in ColumnG.
_codereview.7727
I have a Rectangle class, of which I have 5-6 vectors for each instance. The main vectors are the center and color of the object, while the secondary vectors represent more or less the north, south, east, and west directions of the rectangle itself. These vectors are used to detect collision by pointing outside of the sides of the rectangle to detect collision. I may end up creating more fields of the NW, SW, NE, SE, equivalents as well, but I'd like to know if this is actually a good implementation before I do this. The only Vec2f I have allocated as a pointer is the mWidthHeight vector, which of course is just a representation of the width and the height (x = width, y = height) of the rectangle. Will this allocate too much memory if there are thousands of these on the screen, or is this an OK (at least) implementation?Rect.h Note - I'm debating with the idea of making the N, S, E, W vectors pointers to memory. Is that a good idea, or no?#pragma once#include <QGLWidget>#include <GL/glext.h>#include <cmath>#include <QDebug>#include Shape.h#include Vec3f.h#include rand.hconst int DEFAULT_SQUARE_WIDTH = 5;const int DEFAULT_SQUARE_HEIGHT = 5;typedef enum { V2D_NORTH, V2D_SOUTH, V2D_EAST, V2D_WEST} V2D_DIRECTION;class Rectangle : public Shape{public: Rectangle( Vec2f center = Vec2f(), Vec2f widthheight = Vec2f(DEFAULT_SQUARE_WIDTH, DEFAULT_SQUARE_HEIGHT), float radius = 0, Vec3f color = Vec3f() ); ~Rectangle(); inline Vec2f* getWidthHeight() const { return mWidthHeight; } inline Vec2f getDirection(V2D_DIRECTION dir) const { switch(dir) { case V2D_NORTH: return mNorth; case V2D_SOUTH: return mSouth; case V2D_EAST: return mEast; case V2D_WEST: return mWest; } } virtual void Collide( Shape &s ); virtual void Collide( Rectangle &r ); virtual void Collide ( Circle &c ); virtual bool Intersects( const Shape& s ) const; virtual bool Intersects( const Rectangle& s ) const; virtual bool IsAlive( void ) const; virtual float Mass( void ) const;protected: virtual void Draw( void ) const; Vec2f* mWidthHeight; Vec3f mColor;private: Vec2f mNorth; Vec2f mSouth; Vec2f mEast; Vec2f mWest; void InitDirections();};
Is this a good algorithm for 2D collision, or will it allocate too much memory?
c++;memory management;computational geometry
null
_cogsci.4984
Is it possible to still gain muscle strength by performing exercises but without load? Is there some kind of memory mechanism that would allow this?
Is it possible to gain strength by imagining working out?
physiology;visualization
null
_unix.4511
I have scenario in whichmy host is : x86 32 bit processormy target is : x86 64 bit processor I have a couple of questions : I want to know if i can simplycompile a program in my host usingthe available gcc and run it on thetarget?Do i need to cross compile it for x8664 bit processor? If yes, how can i specify it while compiling?Do i need to use separate tool-chainfor cross-compiling the program?
Do I need to cross-compile my program when my target is 64 bit arch. and host is 32 bit arch from x86 family?
linux;compiling
All amd64 (i.e. 64-bit x64) processors can run 32-bit x86 binaries. Also, on most operating systems, you can run x86 programs on an amd64 OS. So it is often possible to deploy x86 binaries on amd64 processors.Whether it's desirable to do so is a different matter. 64-bit OSes often come with a restricted set of 32-bit libraries, so if your program uses some uncommon libraries it will be easier to install a 64-bit executable. Depending on your application, there may or may not be a performance advantage to 32-bit or 64-bit binaries.If you decide you want to deploy 64-bit executables, you'll need a cross-compililation environment for the amd64 (a.k.a. x86_64) architecture running on an x86 architecture. This means both a compiler, and static libraries to link against.A gcc installation can share frontends and include multiple backends. But not many distributions ship with amd64 development tools on x86 platforms, so you may have to get your own (gcc is fairly straightforward to cross-compile). The same goes for libraries to link against (of course, once you have the compiler, you can recompile them from source).As an example, Ubuntu 10.04 on x86 comes with a multilib version of gcc and an amd64 backend, plus a small set of 64-bit development packages (libc6-dev-amd64 Install libc6-dev-amd64 http://bit.ly/software-small and depending and dependent packages).
_cs.783
The 3-Partition problem asks whether a set of $3n$ integers can be partitioned into $n$ sets of three integers such that each set sums up to some given integer $B$. The Balanced Partition problem asks whether $2n$ integers can be partitioned into two equal cardinality sets such that both sets have the same sum. Both problems are known to be NP-complete. However, 3-Partition is strongly NP-complete. I haven't seen in the literature any reduction from 3-Partition to Balanced Partition.I'm looking for (simple) reduction from the 3-Partition to the Balanced Partition problem.
Reduction from 3-Partition problem to Balanced Partition problem
complexity theory;reductions;np complete
null
_softwareengineering.349605
I'm looking for a collection that would suit my scenario:I will be inserting key-value pairs (both integers) of ID and timestamp. The ID must be unique.At some interval I will be checking that collection for expired items (as in the timestamp + X < current_timestamp) and will need to both remove the key-value pair and act on the key.I stated that I'm looking for sorted collection, because I think with the collection sorted by value (descending order) I could break the loop over the collection at the point I reach first not expired timestamp (that would mean rest of them is active too).I predict that 95% of my entries will not be expired at the time I loop over them.There will be way more inserts/modifications than reads.I couldn't find anything that would match this scenario, the closest one is SortedMap.Is there anything that would be more suitable? Perhaps completely other approach?I think it's also important to point out it will hold up to 10000 keys (pairs).If there's anyone with JavaScript (node) background then providing some links to implementations would also be great.
Javascript queue-like key-pair sorted collection
data structures;sorting;map
It is not necessary to have a single collection that satisfies your requirements. Instead, you can combine two collections to get the required properties. You then only modify these collections through an interface that ensures that the two collections are kept in sync.for uniqueness, keep a Set of IDs.for ordering, keep a Queue of Timestamps.Deleting old entries requires that you can remove the IDs from the Set, so you need to find the ID from a Queue-item. We could therefore implement this as a Map from IDs to Timestamps, and a Queue of IDs, sorted by corresponding timestamp.Pseudocode:queue: min-priority queue for map[entry]insert(map, queue, ID): map[ID] = now() queue.insert(ID)delete-expired(map, queue): while map[queue.first] is expired: delete map[queue.first] queue.unqueue()Ah, but what about updating the timestamp? If memory is not the limiting factor, I would leave the old entries in the queue but mark them as invalid. This defers their removal until they are dequeued.queue: min-priority queue for entry.timestampinsert(map, queue, ID): if ID in map: map[ID].valid = false entry = { timestamp: now(), id: ID, valid: true } map[ID] = entry queue.insert(entry)delete-expired(map, queue): while queue is not empty: entry = queue.first if entry.valid and entry.timestamp is not expired: return delete map[entry.id] queue.unqueue()Alternatively, you can delete the entry from the middle of the queue. However, queue-removal generally requires you to scan or move all elements in the queue, and is therefore a very time-intensive operation. This might be the correct choice if you are memory-constrained.The priority queue can in general be implemented as a heap.Since you only insert newer elements, an array-like data structure would also be a good choice. But dynamic arrays (the lists JavaScript gives you by default) are not desirable since the elements have to be regularly moved into the space freed up at the front by dequeuing entries. An alternative that doesn't have to move elements is a ring buffer, which could be made self-resizing like a dynamic array.
_cogsci.9951
Is there an existing research area focusing on brain to brain interfaces? If so, what are some papers that have been published in this area?
What research has been done on brain-to-brain interfaces?
reference request;theoretical neuroscience;brain computer interface
null
_unix.297081
I am asking user for input and taking input in the variables such as $1, $2 etc.I am checking the variable for null value and wants to replace the value if null.if [ $2 == ]; then2=valuefiBut something I am missing. Any suggestions?
How to assign value to input variable in shell
shell script;test;variable substitution;parameter
You can't directly set values to the positional paramaters like this.You can set them with the set command, but this will set all the values ($1, $2, ...)e.g.$ set -- first second third fourth fifth$ echo $1first$ echo $2secondNow there are two cases where $2 can be the empty string; first if no value has been passed, or second if is passed as an actual argument and so there may still be a $3, $4 etc.We can handle each case in a slightly complicated way:#!/bin/bashecho Before 1=$1 2=$2 3=$3 4=$4if [ -z $2 ]then first=$1 shift 2 set -- $first value $@fiecho After 1=$1 2=$2 3=$3 4=$4The bit inside the if test will ensure all other values are retained.e.g.% ./testing arg1 arg 3 and arg 4Before 1=arg1 2= 3=arg 3 4=and arg 4After 1=arg1 2=value 3=arg 3 4=and arg 4But you might be able to do things simpler and just use ${2:-value} which will evaluate to value if $2 is not set, so then you don't need to worry about rewriting the arguments.
_codereview.106659
It's taking my machine quite a long time to execute 1 billion (1st loop x 10, 2nd loop x 1000, 3rd loop x 100,000) instructions. Suggestions for performance enhancements? Sources of potential concern: global variables slower than local variables?using for loops instead of something like map?overhead for class instantiation?overhead of storing results in a dictionary before making a pandas frame? from numpy import randomfrom pandas import DataFrame, concatclass coin(object): HEADS = 1 TAILS = 0 FLIP_TIMES = 10 def __init__(self): self.frequency = self.flip10() def flip10(self): choices = [coin.HEADS, coin.TAILS] record = [] for i in xrange(coin.FLIP_TIMES): record.append(random.choice(choices)) return sum(record) / float(coin.FLIP_TIMES)class trial(object): NUM_COINS = 1000 DEFAULT_VAL = 11.0 / 10.0 C_RAND_IDX = random.randint(0, NUM_COINS) def __init__(self): self.results = self.flip1000() def flip1000(self): v_rand = trial.DEFAULT_VAL v_first = trial.DEFAULT_VAL v_min = trial.DEFAULT_VAL for i in xrange(trial.NUM_COINS): # grab frequency v_i = coin().frequency # hold on to pocket minimum frequency if v_i < v_min: v_min = v_i # get random frequency if i == trial.C_RAND_IDX: v_rand = v_i # get first if i == 0: v_first = v_i # some error checking to make sure they don't # still have their default values at this point # would be great return {'rand': v_rand, 'first': v_first, 'min': v_min} data = DataFrame([trial().results for i in xrange(100000)])
Generating a PANDAS DataFrame of simulated coin tosses
python;performance;python 2.7;simulation;pandas
null
_unix.159454
Some applications allow to pass password as an argument. For example:mysql --user=user_name --password=your_password db_nameIs it safe? Besides the fact that typed password would be saved in bash history, someone can type w command in the appropriate moment and will see the full command line of process (including password).It's quite surprising for me that every user can see what command I'm currently executing.
Is w command safe for users?
command line;security;password
The command line arguments of every process in the system is considered public. Not just the w command, but ps and top and many other commands access that information as a matter of course. Indeed no special privileges are required to get that information. On Linux, you can read the command line of another process, even a process belonging to another user, by reading /proc/<pid>/cmdline.This is not a flaw or unsafe behaviour on the part of w or top or ps (or cat). Rather, the onus is on the side of not passing sensitive information on command lines on multi-user systems, ever.Most utilities that have the ability to accept passwords on the command line document that it's not recommended to do it. For example, from mysql's manpage:Specifying a password on the command line should be considered insecure. See Section 5.3.2.2, End-User Guidelines for Password Security. You can use an option file to avoid giving the password on the command line.By the way, passing passwords or sensitive data in environment variables is less blatantly unsafe, but is also actually unsafe on most systems.
_cstheory.14875
Assume that I have an array $A$ of $n$ numerical values where some are known and some are unknown (with $A[0]$ and $A[n-1]$ assumed to be known). If I want to estimate an unknown value $A[i]$, a reasonable way is to perform linear interpolation: find the largest $j < i$ such that $A[j]$ is known, find the smallest $k > i$ such that $A[k]$ is known, and do a weighted average $A[j] := {k-i \over k-j}A[k] + {i-j \over k-j}A[j]$. In particular, this ensures that the following property (*) holds: $$\text{if } A[j] \leq A[k] \text{ then } A[j] \leq A[i] \leq A[k]$$Now, you can see an array as a totally ordered structure, and wonder about what would happen in the case of a partial order. Assume that I have a DAG $G = (V, E)$ of $n$ nodes where every node $v \in V$ has a numerical value $\mu(v)$ where some values are known and some are unknown (with the values of the roots and leaves assumed to be known). If I want to estimate some unknown $\mu(v)$, it seems that I should interpolate it out of the values of the closest ancestors and descendents of $v$ whose values are known. The question is: what should we do, exactly? Is there a generalization of linear interpolation in this setting?[Here is a possible choice: for every couple $(u, w)$ of ancestors and descendents of $v$, perform linear interpolation along all the possible chains between $u$, $v$ and $w$ to get a value for $v$, and average all the values over all chains and ancestor-descendent pairs to get your final estimate. Is this the correct way to do things? Can this estimation be computed more efficiently than with this definition? (i.e., could we do it in linear time in the size of the neighborhood of $v$ under consideration, rather than in a quadratic way?). Do we still have some variant of property (*)? (note that, even if you assume monotonicity, i.e. for each ancestor-descendent couple $(u, w)$ you assume $\mu(u) \leq \mu(w)$, then the estimation $\mu(v)$ obtained by the previous process may still violate monotonicity, i.e. $\mu(v) > \mu(u)$ for some ancestor $u$ of $v$)]
Generalizing linear interpolation to posets
ds.algorithms;reference request;graph algorithms;partial order
In a recent paper, we propose such a scheme. The scheme is illustated in a specific crowdsourcing application setting, but the idea is fairly simple. We just see the order constraint $\mu(u) \leq \mu(v)$ of each DAG edge $(u, v)$ as a linear inequality constraint, we consider the admissible convex polytope of assignments to these linear inequalities, and we choose the center of mass of this polytope as our interpolation result.The paper explains the scheme in more detail, includes an algorithm, computational hardness results, an approximation scheme that derives from existing work, a tractable case when the DAG is a tree, and a discussion of alternate schemes.
_cs.49163
Does it make sense for a Turing machine to have infinite number of states ? I had previously asked a question Can Turing machines have infinite length input. From which I came to know about Type-2 Turing machines. If there can be infinite states, encoding of such a Turing machine would be infinite ( but again I am not sure if it make sense to encode a Turing machine with infinite states thus having an infinite description ). So it would make sense that if I have to give the encoding of such a Turing machines as input, I would give it as input to Type-2 Turing machines. But is there any use of infinite states ( and what is there link to Type-2 Turing machines ? ) ? If I am not wrong there is no function which is uncomputable by normal Turing machine but computable by Turing machine with infinite states.
Can a Turing machine have infinite states?
turing machines;computation models
No. The definition of Turing machines requires that the finite-state control unit have a finite number of states. It's not allowed to have an infinite number of states.A machine that could have infinitely many states in its control could accept any language (unlike a Turing machine). However such a machine could not be implemented in practice. For these two reasons, it would not be a good model of the computational power of real computers.In addition, once you allow an infinite-state automaton, there's no need to have any tape -- the tape doesn't add any computational power, because an infinite-state automaton can already do everything. For these reasons, while it would be possible to construct machines that look like Turing machines but have infinite state, there would be little point: their power would be equivalent to an infinite-state automaton on their own, i.e., every language can be accepted by such a machine.
_softwareengineering.333515
Pull requests are a great feature of modern vcs hosting. They provide a consolidated view of everything that's happened within a branch's development, including a master diff of the composite change, and all the discussion that's taken place.My question is this: Is there any downside to issuing a pull request immediately from a new branch?I suppose traditionally pull requests are issued when someone feels their contribution is ready to be reviewed. Issuing it early can cause some confusion for those accustomed to the more traditional workflow.On the other hand, issuing early means reviewers can check in and see if someone's changes are going in the wrong direction before unnecessary effort is expended.Perhaps there are other pros and cons that I haven't considered?
How soon can/should someone issue a pull request for a new branch?
version control;git;github;pull requests;bitbucket
null
_webmaster.5444
Right now I am using OpenX. But over the years it got more and more bloated. I barely use 10% of its functionality. What are the alternatives and what is it that makes them good?I need:image bannershtml bannersstats on impressions and clickseven distribution of booked impressions over the booked time (like max 10000 impressions per day for 10 days)weekly stats per email (for admin and for customer)Please list one ad server per answer for easier ranking...
What is a good, free ad server?
advertising;banners
How about Google DFP - it nearly meets all your requirements (except for sending weekly stats) and you don't have to worry about hosting, upgrades, etc. Here's a quick tutorial to help you get started.
_webmaster.102182
I have a website. It has content that already exists somewhere on other sites.I have added a canonical tag, nevertheless Google index those URLs.I'm not concerned about these pages being indexed, only thing I want to know is whether Google will take manual action and perhaps inflict a penalty for thin content on my site?
Google indexing duplicate content despite a canonical tag pointing to an extarnal URL. Am I risking a penalty from Google?
google;index
null
_softwareengineering.199171
I'm going to start an open source project from scratch, using git (via github) to manage the source. The project will be written in C# and will depend on at least two external libraries (more are likely to come). I wonder how I should reference the libraries, and the following ideas came to my mind:A folder within the project that contains all external libraries as dllThis would mean I have the dll files in my repo, which I think is bad, because it isn't source. Also, I don't know how Visual Studio (or other IDEs) store the path the libraries, if they use absolute paths, that would be impossible.Get the external libraries via nugetThis would be a clean and nice way to have the libraries organized, but what what if a library I need doesn't have a nuget-package? I can't just create one, can I?Storing the source of the external library as part of my repoSounds like a stupid idea, it would make updating the libraries a pain.Reference the repositories of the other projects via git somehow.Sounds good, I could make my own fork of it to keep a state or just point to a commit. But is that even possible? Is that a good way?tl;dr: How should I handle external libraries in an open-source C# project?
Third party libraries in an open-source C# project
c#;version control;git;third party libraries
If nuget is not available, the cleanest way may be to provide an export script which pulls the source code of the needed library from their external repository (of the library vendor) into your working directory. This will work even if the SCC system of the external libs is different from Git (as long as it has a command-line interface). EDIT: this will work also when the source code is not available in an SCC system at all, just as ftp or http download, for example.You can integrate that script into your build process, of course. When using Visual Studio, as you mentioned it, you can write either a classic Makefile (using NMake), or use MSBuild to call that script when the external lib is not in your working dir. Perhaps the most simple approach is to add that script to a prebuild event, the details depend much on how the rest of your build process is organized.
_webapps.61061
Is there a way to use the text value of cells with a conditional statement such as sumifs so that on one sheet I can have all the expenses# A B C1 R. Tusk Travel 1,717.092 Frank U Travel 634.673 R. Tusk Meal 50.004 Frank U Supplies 1,336.665 R. Tusk Meal 10.006 R. Tusk Meal 55.007 R. Tusk Ent 23,803.978 R. Tusk Pol. Don. 24,483.919 R. Tusk Meal 10.0310 R. Tusk Ent 1,191.6211 Frank U Pol. Don. 40,493.1412 R. Tusk Pol. Don. 10,014.0113 Frank U Travel 100.0013 Frank U Travel 100.00And on the other sheet I can have essentially one formula the following:Politician Meal Travel Pol. Don. Ent SuppliesR. Tusk XXXX.XX XXXX.XX XXXX.XX XXXX.XX XXXX.XXFrank U XXXX.XX XXXX.XX XXXX.XX XXXX.XX XXXX.XX I was thinking=SUMIFS('Sheet1'!C:C,'Sheet1'!B:B,=T(B$1),'Sheet1'!A:A),=T($A2))But that and other slight variations only gave me error, n/a, and #value!Update=SUM(FILTER('Sheet1'!$C:$C,'Sheet1'!$B:$B=B$1,'Sheet1'!$A:$A=$A2))For those playing at home, this worked.
Google Spreadsheets SUMIFS with Text Value of Cells
google spreadsheets
null
_webapps.48658
I was trying to make a new blog at blogger.com with a new email.So I register for a new one not knowing that I was already logged into mine.Now the email I wanted to associate with the new blog is part of my old blog. I need that email name for my new one as its a project with my friends.It's become my primary email. How do I change that or re name it so that I can make the email name available for my new blog?
Changing primary email google
blogger;google account
null
_codereview.84798
I'm kinda new to Java (<1 year) but have some background in C and Python.I've come up with a working solution to Project Euler Problem 4 - Largest Palindrome Product. However, I'm not confident this is Effective Java...All suggestions for improvement are welcome. I'd especially like feedback on the following:Java language usageJava library usageAlgorithm performance/** * Palindrome Integer is a whole number which reads the same both ways. */public class PalindromeInteger { /** * Predicate to determine whether the given number is a palindrome. * @param integer * @return true if palindrome, false otherwise. */ public static boolean isPalindrome(int integer) { String integerStr = String.valueOf(integer); StringBuilder sb = new StringBuilder(); sb.append(integerStr); String integerStrReversed = sb.reverse().toString(); return integerStrReversed.equals(integerStr); } /** * Returns a Set of the palindrome integers which can be made from the product of the given integers. * @param multiplicand * @param multiplier * @return a Set of palindrome integers. */ public static Set getPalindromeProducts(int multiplicand, int multiplier) { Set palindromes = new HashSet(); for (int i = multiplicand; i >= 0; i--) { for (int j = multiplier; j >= 0; j--) { int product = i * j; if (isPalindrome(product)) palindromes.add(product); } } return palindromes; } /** * Returns the largest Palindrome integer possible from the product of the two given integers. * @param multiplicand * @param multipler * @return palindromic integer e.g. 9009 */ public static int getLargestPalindromeProduct(int multiplicand, int multipler) { Set palindromes = getPalindromeProducts(multiplicand, multipler); return (int)Collections.max(palindromes); }}
Project Euler #4 Largest Palindrome Product
java;programming challenge
Your method isPalindrome produces wrong results for negative numbers. (which is not important for Project Euler #4, but still) It is also inefficient to convert all numbers to String. I would only do that when using BigInteger. With int, you can just use a little math:public static boolean isPalindrome(int number) { return number == reverse(number);}public static int reverse(int number) { //negative numbers: reverse the positive and negate it again. if (number < 0) return -reverse(-number); //a 1-digit number is its own reverse if (number < 10) return number; int reversed = 0; while (number > 0) { //take the last digit of number and paste it to reversed. reversed = reversed * 10 + number % 10; //cut off the last digit number /= 10; } return reversed;}You are not using the method getPalindromeProducts(int multiplicand, int multiplier) correctly. You run both loops all the way down to zero.The meaning of the names multiplicant and multiplier isn't clear imo. In a multiplication, both numbers are just factors. One of them is the minimum (100) and the other is the maximum (999). You're looking for numbers between 100 and 999, not between 100 and 0 or between 999 and 0.You also do a lot of the work twice by running both loops all the way. For example, you will get a * b AND b * a. You can skip a lot of iterations by breaking out of the loop early.Another thing to think about is the HashSet. The problem with Java Collections is that you cannot use them with primitive types. It will convert all numbers to Object, which will hurt performance. (You cannot have a HashSet<int> for example)However, in this case, you don't need a HashSet at all. You don't care about duplicates, you just want to find the largest product. It is also not necessary to store all the palindromes you found; you only need the largest one.public static int getLargestPalindromeProduct(int minFactor, int maxFactor) { int largest = 0; for (int a = maxFactor; a >= minFactor; --a) { for (int b = maxFactor; b >= a; --b) {//Note the b >= a, not b >= minFactor int product = a * b; if (product <= largest) break; //We can stop this iteration, because factors will only get smaller. if (isPalindrome(product)) { largest = product; break; } } } return largest;}Then call getLargestPalindromeProduct(100, 999);
_unix.381323
I have a file called file.csv with multiple rows and columns like this:API,20042017-01:00,341701,341701,480692,480692API,20042017-02:00,293058,293058,415459,415459API,20042017-03:00,272692,272692,388942,388942API,20042017-04:00,279117,279115,399361,399361API,20042017-05:00,345947,345945,495306,495306and I want to calculate the percent value by multiplying the ratio of column 4 to column 3 by 100, so I typed in the following command:awk -F, '{ print $1, $2, $3, $4, ($4/$3*100), $5, $6 }' file.csvwhich gives me the required output:API,20042017-01:00,341701,341701,100,480692,480692API,20042017-02:00,293058,293058,100,415459,415459API,20042017-03:00,272692,272692,100,388942,388942API,20042017-04:00,279117,279115,100,399361,399361API,20042017-05:00,345947,345945,100,495306,495306but when there's a non integer in column 3, it gives me a error saying:awk: (FILENAME=file.csv FNR=3) fatal: division by zero attemptedand stops counting the rest of the rows.How could I make it continue?
shell: dividing columns using awk stops if there is a non integer found
shell script;awk
You can ask awk to validate if a field is a number by using ~ /^[0-9]+/.Here's a little shell script that demonstrates this:[root@tiny ~]# cat test.sh#!/bin/bashINPUT=API,20042017-01:00,341701,341701,100,480692,480692API,20042017-02:00,293058,293058,100,415459,415459API,20042017-03:00,272692,272692,100,388942,388942API,20042017-04:00,279117,279115,100,399361,399361API,20042017-04:00,279117,FRED,100,399361,399361API,20042017-05:00,345947,345945,100,495306,495306echo $INPUT | awk -F, '$3 ~ /^[0-9]+/ && $4 ~ /^[0-9]+/ { print $1, $2, $3, $4, ($4/$3*100), $5, $6 }'[root@tiny ~]# ./test.shAPI 20042017-01:00 341701 341701 100 100 480692API 20042017-02:00 293058 293058 100 100 415459API 20042017-03:00 272692 272692 100 100 388942API 20042017-04:00 279117 279115 99.9993 100 399361API 20042017-05:00 345947 345945 99.9994 100 495306[root@tiny ~]#
_unix.257793
I'm writing a shell script that needs to perform certain operations based on the last commit's message of my local branches with a name starting with task. Here's what my script looks like #!/bin/bashgit branch | while read branch_name; do if [[ $branch_name == task* ]]; then git log --format=%s -n 1 ${branch_name} fi doneWhen i run this script I get the following output : fatal: ambiguous argument 'task/foo': unknown revision or path not in the working tree. Use '--' to separate paths from revisions, like this: 'git [...] -- [...]'Which is weird because I have a branch named task/foo (and also because the name is directly read from the output of git branch). I tried adding -- at the end of the git log, as suggested but then I get the following error : fatal: bad revision 'task/foo'When I do the exact same command inside a shell, everything works fine : $ git log --format=%s -n 1 task/foo Initial commit (Readme, license)EditAs suggested, I tried placing my variable between double quotes, like below, but I still have the same result. #!/bin/bashgit branch | while read branch_name; do if [[ $branch_name == task* ]]; then git log --format=%s -n 1 ${branch_name} fi doneI also tried the script suggested by Klaatu, but this also give me the same error. Edit 2Here's the output when I add set -x to my script : + git branch+ read branch_name+ [[ * develop == task* ]]+ read branch_name+ [[ master == task* ]]+ read branch_name+ [[ task/foo == task* ]]+ git log --format=%s -n 1 'task/foo'fatal: ambiguous argument 'task/foo': unknown revision or path not in the working tree.Use '--' to separate paths from revisions, like this:'git <command> [<revision>...] -- [<file>...]'+ read branch_nameUse '--' to separate paths from revisions, like this:'git [...] -- [...]'+ read branch_name
Git unknown revision error when within bash script
shell;shell script;git
null
_webmaster.4473
I have heard about back links but am not sure what they are or how they affect search rankings and search engine optimization.
What is a back link and how does it affect search ranking?
seo;pagerank;backlinks
A back link is a any link on another website that is not your own that points to a page on your website. This is different from an internal links which is when you link one page on your website to another page on your website. They are helpful in SEO because the search engines, particularly Google, sees links as votes. Whenever another website links to yours they are essentially voting for your web page, or a better way to say it is they saying they believe your web page is very helpful or informative on the topic it covers. Backlinks carry weight because they are generally out of control of the receiving website. (As a general rule, the less control a webmaster has over something and the more visible it is to users the more weight it will carry). Yes, you can attempt to make websites just to link back to your own website but there are many problems with this. Not only can you not make enough links to make a difference regardless of any other factors, but the search engines can sniff out networks built for such a purpose and devalue those links completely and/or ban those sites from their search engines. Additionally, not all links are created equal. Links from related web pages are worth more then from unrelated pages. The anchor text in those links are also a factor in the link's value as is the page's ranking for the search terms you wish to rank well for. In Google PageRank is also a factor (although much smaller then many would have you believe). So, going back to my artificial network example, even if you make a network of sites just to link to yours, because they won't have any backlinks of their own and will rank poorly their links to you will be very low value and not helpful at all. Especially if they are off topic. If you try to make sites similar to your own you have two problems: either the sites contain duplicate content and will be ignored by the search engines or you'll be wasting good content on a satellite website when it could be doing your main website good by attracting links where you want them in the first place.The best way to get backlinks, especially quality backlinks, is to have high quality content on your website. These naturally attract links as webmasters prefer to link to good content and not frivolous content. Building up quality backlinks takes time and never goes quickly. Anyone telling you otherwise is not well informed or being dishonest.
_softwareengineering.275443
In an application I developed with C#, I use a webbrowser control, it should navigate to some websites, then I would like to extract some contents from the webpages. I do it by manipulation of DOM and removing some nodes. It can be done automatically or manually with the help of user.Then I have two modes, surfing mode and extraction mode. I think switching between modes and updating related controls and menus and responding to events... has made my program complicated. What is your advice to make it less complicated?Does Separation of Concerns applies to GUI components too?
Does Separation of Concerns applies to GUI components?
design;gui;separation of concerns
Separation of concerns is just as important in UI as anywhere else, if not more so. Anything that doesn't directly involve user interaction does not belong in the UI. It belongs somewhere else.Consider what happens when you create a UI having the usual event hooks:private void Form1_Load(object sender, EventArgs e){ listView1.Items.Add(new ListViewItem(this is a test));}What happens if you put all of your business logic in your form? You wind up with a big ball of mud, that's what. That's why we put business logic in another module, class or DLL.Whether this is what's happening with your application is an open question. As I see it, there's two possible approaches. You can have a single UI with two modes, or two different UI's. If the modes are dramatically different, I usually prefer two different UI's, as you can avoid all of the if statements that way, and your design is generally cleaner. You can refactor common functionality between the two UI's into a separate module, class or DLL.
_unix.317133
I can not solve this problem ...flashplayerdebug: error while loading shared libraries: libXt.so.6: cannot open shared object file: No such file or directoryand yet I have this lib`locate libXt/usr/lib/x86_64-linux-gnu/libXt.a/usr/lib/x86_64-linux-gnu/libXt.so/usr/lib/x86_64-linux-gnu/libXt.so.6/usr/lib/x86_64-linux-gnu/libXt.so.6.0.0/usr/lib/x86_64-linux-gnu/libXtst.a/usr/lib/x86_64-linux-gnu/libXtst.so/usr/lib/x86_64-linux-gnu/libXtst.so.6/usr/lib/x86_64-linux-gnu/libXtst.so.6.1.0`he seems to have read, this is not a path problem, but that the lib is made for systems 32b, and I have a system 64b (but in this case why the folder where it finds that its name is 'x86_64...')
flashplayerdebug: error while loading shared libraries: libXt.so.6:
linux;shared library;adobe flash
null
_cs.57074
Given a set of vectors, lets say that each coordinate is populated from an alphabet (meaning set of symbols, numbers, etc) (particular or shared alphabets are indistinct). Is there any standard procedure for performing the following task ? Look for sets of positions that make the same choice in several vectors.That means: a subset of indices where, when we project to just those indices, there's some value that's taken on by many of the vectors.An example:Input [0,-,0][0,+,+][+,+,+][0,0,0][-,+,+]Output2 coordinates involved ( 2 and 3), appearing in 3 vectors: x2=+ and x3=+1 coordinate involved (1), appearing in 2 vectors: x1=0
Find Correlations in Vectors of symbols
algorithms;reference request;machine learning
null
_unix.309568
For my CheckCodingGuidelines script. I want:#ifndef GAIN_MODULE_H#define GAIN_MODULE_HTo passAnd:#ifndef __GAIN_MODULE_H#define __GAIN_MODULE_HTo fail (echo: Error Rule25 at $line)How do I do that?
Check if correctly spelled
text processing
awk ' /^[[:blank:]]*#[[:blank:]]*(define|ifndef)[[:blank:]]+_/ { print Error Rule25 at FNR }' file.h >&2
_webapps.22280
I removed the navbar on my Blogger blog (blogspot). There are many guides online, but I can not find one that explains how to reduce the empty space left navbar. I think it requires action in the HTML code.
I removed the navbar in blogger blog, there is a way to reduce the space you have left?
blogger
null
_unix.245819
I read the following in Which package managers allow to download binary packages through torrent protocol?:Configure the correct stuff in the repo.conf, and create a dotorrent fetcherHow can I configure paludis to download pbins via the torrent protocol?
How to download pbins with paludis through torrent protocol?
package management;gentoo;bittorrent
null
_unix.337492
I have three partitions in my system. /dev/sda1, /dev/sda2 and /dev/sda3. /dev/sda1 is 50gb for system files for windows/dev/sda2 is for the partition where windows is installed/dev/sda3 is where arch linux and the grub is installedBut when I reboot the system, only the arch linux is showing on the menu. How would I add the windows partition in the grub menu?
Cannot find the partition where I have installed windows after I have installed arch linux and grub
linux;arch linux;windows;grub2;grub
null
_unix.22957
I am trying to use FTP to download several hundred files within a directory. Is there a way to only download specific files with FTP? Ideally, I would like to match specific files using a regular expression. Unfortunately, the directory is massive and it's too large to download the entire directory and then use find or grep locally to manipulate certain files. Is there a simply way to do what I am trying to do on Unix? If not, I plan to just write a script in perl or python. Thanks in advance for the help.
Download specific files with FTP?
ftp
null
_datascience.3733
I have a non-function (not in closed form) that takes in a few parameters (about 20) and returns a real value. A few of these parameters are discrete while others are continuous. Some of these parameters can only be chosen from a finite space of values. Since I don't have the function in closed form, I cannot use any gradient based methods. However, the discrete nature and the boxed constraints on a few of those parameters restrict even the number of derivative free optimization techniques at my disposal. I am wondering what are the options in terms of optimization methods that I can use.
Which Optimization method to use?
optimization
Bayesian optimization is a principled way of sequentially finding the extremum of black-box functions. What's more, there a numerous software packages that make it easy, such as BayesOpt and MOE. Another flexible Bayesian framework that you can use for optimization is Gaussian processes: Global Optimisation with Gaussian Processes
_unix.98282
echo 1234 | sed ' /\n/ !G s/\(.\)\(.*\n\)/&\2\1/ //D s/.// ' I'm unable to comprehend the above sed code.my understanding is:PATTERN SPACE=1234first operation /\n/ !G ---> 1234\n(if \n is not found it is appended at th end) s/\(.\)\(.*\n\)/&\2\1/ ----> 1234\n234\n1 //D ----> \n234\n1(deletes upto newline and commands from the beginning are applied to the existing pattern space)PATTERN SPACE=\n234\n1second operation /\n/ !G ---> skipped since \n234\n1 has newline now s/\(.\)\(.*\n\)/&\2\1/ ----> \n234\n1234\n //D ----> \n234\n1234\nIt seems I'm doing something wrong.
Reverse a line in sed?
sed
There is a loop in this code that get's confusing to see. This bit: s/\(.\)\(.*\n\)/&\2\1/ //DKeeps looping, shifting the characters 234\n1 to 34\n21 until we're left with \n4321, where it then drops out of the loop.The description by catonmat is spot on so I'm including it here: 37. Reverse a line (emulates rev Unix command)..excerptThe first line /\n/ !G appends a newline to the end of the pattern space if there was none.The second line s/\(.\)\(.*\n\)/&\2\1/ is a simple s/// expression which groups the first character as \1 and all the others as \2. Then it replaces the whole matched string with &\2\1, where & is the whole matched text (\1\2). For example, if the input string is 1234 then after the s/// expression, it becomes 1234\n234\n1.The third line is //D. This statement is the key in this one-liner. An empty pattern // matches the last existing regex, so it's exactly the same as: /\(.\)\(.*\n\)/D. The D command deletes from the start of the input till the first newline and then resumes editing with first command in script. It creates a loop. As long as /\(.\)\(.*\n\)/ is satisfied, sed will resume all previous operations. After several loops, the text in the pattern space becomes \n4321. Then /\(.\)\(.*\n\)/ fails and sed goes to the next command.The fourth line s/.// removes the first character in the pattern space which is the newline char. The contents in pattern space becomes 4321 -- reverse of 1234.There you have it, a line has been reversed.
_cs.60770
The VC dimension is usually used in the following way. There is a space of hypotheses. There is an unknown probability distribution. We sample some training-samples from this distribution. We find the hypothesis that scores best on the training-samples. If the VC dimension is sufficiently small and the number of samples is sufficiently large, then this best hypothesis will also perform probably-approximately-well on any set of test-samples drawn from the same distribution. Specifically, if the VC-dimension is $D$ and the number of samples is at least:$$N := \Theta\bigg(\frac{D + \ln{1\over \delta}}{\epsilon}\bigg)$$then, with probability at least $1-\delta$, the test-error will be at most $\epsilon$.I am interested in the following alternative setting. Instead of a probability distribution, we have a ''fixed'' set of samples, determined by an adversary. We pick half of these samples at random, calculate the best hypothesis on this half, and then test it on the other half. MY QUESTION IS: is it possible to use the VC dimension in the second setting? I.e, is there a formula, similar to the one above, that relates the total number of samples in the population, the probability of learning, and the learning error?
The VC dimension when the samples are fixed
learning theory;vc dimension
Suppose were in the realizable model, i.e. we want to learn some $f^*\in\mathcal{H}\subseteq 2^\mathcal{X}$ where $VCdim(\mathcal{H})=d$.Let $M(\epsilon,\delta)$ be the minimal number of samples required to obtain an error of at most $\epsilon$ with probability at least $1-\delta$. Since the bound you mentioned on $M(\epsilon, \delta)$ holds for any distribution $\mathcal{D}$ over the sample space $\mathcal{X}$, we can treat this case as a uniform distribution with finite support $S=\left\{a_1,...,a_n\right\}$ (picked by the adversary). The learner picks a set $T\subseteq S$ of $n/2$ samples (chosen uniformly at random), and chooses any consistent hypothesis $h$ (relative to $T$).There are two issues which prevent us from directly using the known bounds on $err(h)$. The first is that we are only interested in the error on the set $S\setminus T$, i.e. the training and test samples are not independent. This will add an extra $2$ factor to the bounds on $err(h)$, since:$err(h)=\Pr_{x\sim\mathcal{D}}\left(h(x)\neq f^*(x)\right)=\Pr\left(h(x)\neq f^*(x) | x\in T\right)\Pr(x\in T)+\Pr\left(h(x)\neq f^*(x) | x\notin T\right)\Pr(x\notin T)$.In this case we have $\Pr(x\in T)=\Pr(x\notin T)=\frac{1}{2}$, and $\Pr\left(h(x)\neq f^*(x) | x\in T\right)=0$ ($h$ is consistent with $T$). So we get $err(h)=\frac{1}{2}\Pr\left(h(x)\neq f^*(x) | x\notin T\right)$, or equivalently $\Pr\left(h(x)\neq f^*(x) | x\notin T\right)=2err(h)$, where the left hand side is the probability that we wish to bound.The second issue is caused by the fact that we don't allow repetitions while picking $T$ (the usual model treats each training sample as chosen independently from the distribution $\mathcal{D}$). To avoid this issue, the learner could choose $T$ by taking $m$ independent samples form $\mathcal{D}$, such that with high probability we see at least $\frac{|S|}{2}$ samples. This can be easily done by picking $m\approx |S|$, and conditioning on the event that we saw at least half of $S$, we can use the regular bounds on $err(h)$ for sample size $\ge|S|/2$.
_reverseengineering.12893
This might be a newbie question but it really takes too long to search for certain things in IDA, when I close the app and save the database all my searches are gone and that's just frustrating.I'm aware that I can copy and paste them all in text file but I prefer saving them in IDA itself.Any help will be much appreciated.
Is there anyway to save search results in IDA Pro?
ida
null
_unix.121678
I have a SLES-11 machine on which I am not the root where I am building software code that makes extensive use of message queues. Due to some bugs, Now have an error:mq_open: Too many open filesI am using the command ipcs -a but I do not see my message queues. So I can't use ipcrm command.So, right now I cannot use the machine at all. Is there a way to find message queues (opened by me) in the system and close them ? Info:I do not have a /dev/mqueue in my system. I am also not the root user
Find and close/unlink message queues in the system
limit;ulimit;ipc
null
_webmaster.80938
Looking on the robot file of our ,soon to be, website. I want to know what prevent the site to be crawled. Is it this line ? If not, what will it disallow ?Disallow: *?s=
Robot.txt disallow *?s=
web crawlers;robots.txt
Disallow: *?s=Bots following the original robots.txt specification would not be allowed to crawl URLs like these:http://example.com/*?s=http://example.com/*?s=foohttp://example.com/*?s=/So they interpret *, ? and = literally (i.e., these characters have to appear at the beginning of the URL path).But many bots use (their own) extensions to the robots.txt specification, where some characters are reserved, i.e., they get a specific meaning.Google, for example, uses * for pattern matching:To block any sequence of characters, use an asterisk (*).That means the Googlebot is not allowed to crawl URLs like these:http://example.com/?s=http://example.com/?s=foohttp://example.com/foo?s=http://example.com/foo?s=barhttp://example.com/foo/foo/foo?s=barOther bots may have other interpretations.
_unix.356577
I'm wondering is there's a command or utility already built within the terminal that can take a little endian memory address (for e.g. 5F4A358F) and convert it into a hex code (in this case \x8f\x35\x4a\x5f)?
Command for converting little endian memory addresses to hex code?
command line;scripting;hex
null
_webapps.70147
I have a folder on Google Drive full of Google Docs (i.e. the MS Word equivalent). I'd like to download all of these, exporting them to either MS Word or PDF. However, the only way I can find to do this is to open up each document individually and export it as Word. Is there a quicker way?(I have the Google Drive client installed locally - this just provides .gdoc files which are links to the original in a browser).
Can I download a folder hierarchy full of Google Docs?
google drive;bulk download
You can achieve this by choosing the Google docs which ever you would like to download and then click the drop down list of the More button which is available in top of google drive page. Now you can able to find the option Download in that drop-down list. You can get a pop-up after once you click the option Download. In that pop-up you can choose the formats as Ms Word or PDF and click download. It download as a zip file, once completed please extract it.