id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_softwareengineering.329682 | My employer still uses VisualSourceSafe6. Everything is checked-in into the main project directory in VSS. They are not using branching in VSS. Check-in's are supposed to be ready for release to QA and should not break the build (not enforced).I want to use git as my local repository so I can track changes per feature (branch) and have history of my changes before I commit them to VSS. I need this because some of the changes might span more than 3-4 days before they can be checked-in to VSS. NOTE: my understanding for some git concepts is very new and might be offbase.After reading these similar questions:Using Git with Visual Source Safe 6.0 How Best Can I Use Git When My Employer Uses VSS? Combine DVCS with Visual Source SafeFollowing is what I was thinking of doing:C:\VSS\ProjectA where I perform VSS specific actions get-latest-version, chechout, and checkin etc. The solution/project file will have bindings to VSS since other developers will still use VSS and some might use git with VSS like me.C:\MY\ProjectAwhere I will be doing my development work and using git workflows.To setup the folders I did:Get latest version from VSS into C:\VSS\ProjectAC:\VSS\ProjectA>git init and C:\VSS\ProjectA>git add ., this becomes my master branchgit clone C:\VSS\ProjectA C:\MY\ProjectA, this becomes my development cloneQ: If I have VSS bindings in my solution/project file, VisualStudio will try and connect to VSS even from my git cloned folder C:\MY\ProjectA. So I need to remove the VSS bindings after cloning, correct?When working on a feature I need to:get latest version from VSS into C:\VSS\ProjectAQ: do I need to commit the changed file to the master git repository?C:\MY\ProjectA>git fetch and C:\MY\ProjectA>git checkout, Q: correct?do whatever branching, commits, merge, rebase etc in my development repositoryget diff of my development repository and master repository and checkout those files in VSSC:\MY\ProjectA>git push, Q: correct?C:\VSS\ProjectA>git checkout, Q: correct?C:\VSS\ProjectA>git commit, Q: correct?checkin changed files to VSSUPDATE it seems git for windows (VisualStudio2015) does not yet support pushing to non-bare local repositories, is there any workaround? | How can I use local Git with VSS | version control;git;workflows | null |
_cs.63644 | Is this problem NP-complete?I have many restrictions like this and want to find a feasible solution:((a and b) xor (c and d)) = 1with a,b,c,d are arbitrary literals. It looks similar to XOR-2SAT but has additional ANDs inside the clause. | Is SAT-Problem with XOR and AND NP-complete | np complete;satisfiability;2 sat | null |
_unix.63951 | Let's say we have a PID of a process and we know that it was started by init during startup. How do we find the script name that started it?One way is to run grep $PROCESS_NAME /etc/init.d/*, but that solution is neither bulletproof nor very elegant.Another one would be to run service --status-all and there is a good chance that the PID will be returned by one of the services, but that's even less elegant than the previous solutionEDIT:The OS is RedHat/Ubuntu.Let's suppose we have sshd running with PID 2083 like so:UID PID PPID C STIME TTY TIME CMDroot 2083 1 0 2012 ? 00:00:00 /usr/sbin/sshd -DThe parent of it is init and I guess that it was started with the command service sshd start during bootup, but if we have something that cannot be easily guessed, for example a convoluted startup command or because of an obfuscated /etc/init.d/somedeamon script - how do we find the somedeamon script, knowing only the PID? | Which script from /etc/init.d/ started the process? | process;daemon;init | null |
_webapps.30157 | There's this thing just above the box where you can select a friend to chat with in Facebook. I don't really know what its called so I just called it stalker feed (please also enlighten me what its called).Can I control whether I show up or not on that box when I liked something or commented to a post? | How not to show up in the stalker feed in Facebook? | facebook | Its called ticker and it shows you the things you can already see on Facebook, but in real time.And no, you cant control it directly.Who can see stories about my comments and likes in ticker?To control stories about your commenting activity in ticker and news feed, always check who can see the privacy of the posts you're commenting on. Learn more about sharing privacy. If you aren't comfortable with who can see the post, please don't comment on it or like it. If you do, a story about your activity will be eligible to appear on Facebook, including on your timeline (profile), in news feed and in ticker. |
_unix.139437 | So I used SSH to remotely login to another computer on a network. I have many files that I would like to copy over to my local desktop. I am trying to follow this How-to : However, I think one of the problems is that I may not know what goes in place of /home/name/dirI tried using scp scp [email protected]:CPUTimer.h /Users/Spicycurryman/DesktopBut then I got this error: /Users/Spicycurryman/Desktop: No such file or directory | How to copy a file from a remote network to the local desktop | bash;shell;ssh;command line;scp | You don't have to give an absolute path to scp the easiest way to deal with this is to go where you want to put things and use scp [email protected]:CPUTimer.h . (. refers to the current directory), or give a relative path like Desktop. You can also use ~/Desktop to refer to the Desktop directory within your home directory from anywhere.If you have lots of files to copy from one place, you may find rsync more convenient:rsync -avx [email protected]:foo .That will copy the entire foo directory and its contents to the current directory. |
_cs.42947 | I'm a bit confused on how to use homomorphims to prove irregularity or to prove that a language is not context free. This is what I'm currently thinking: Example 1:Let $L = \{ a^{i}b^{j}c^{k} : i = j = k \}$ and$h: \{a, b, c\} \rightarrow \{a, b, \epsilon\}$ be defined as follows:$$h(x) = \begin{cases} \epsilon & x = c\\ x & o.w.\end{cases}$$Then it follows that$h(L) = \{a^ib^j: i=j \} = \{a^{n}b^{n}: n \ge 0 \}$.Now because $\{a^nb^n: n \ge 0 \}$ is known to be irregular, then so is $L$.Example 2:We know that $P = \{0^p : p \text{ is a primes}\}$ is irregular (by the pumping lemma). Defined $h: \{0\} \to \{1\}$ as $h(1)=0$.It follows that $h(P) = ${1^p : p \text{ is a primes}}$ and therefore is irregular.I wrote these as answers to an exercise but I've been told that they are incorrect. I don't understand why? | How to use homomorphisms to prove irregularity | formal languages;regular languages;check my answer | null |
_webapps.18324 | I have this dialog in GV with an option to use Google Talk. But nothing happens in GT. Is this a problem, or is it not possible to make a call with GT? | Can I make a Google Voice phone call using Google Talk? | google voice;google talk | Try opening Gmail in a tab along with Google Voice. Also, make sure you have the plugin installed. |
_cs.53031 | Throughout my education in computer science, I feel like I've heard the terms modulo and modulus used interchangeably. It looks like even Wikipedia claims that modulo is sometimes called 'modulus' (see the first sentence of the page on 'modulo').I've looked into this issue a little and it seems that modulo finds singular use in modular arithmetic (e.g. 19 and 64 are congruent modulo 5). In addition, I've seen the symbol % be referred to as modulo.Meanwhile, modulus appears to have several definitions, including absolute value and constant factor as well as referring to the 5 in modulo 5.Is it ever correct to use these terms interchangeably in the context of computer science? Are they simply different types of words that represent the same idea (such as run and runner)? Are there important differences in other disciplines?Bonus: Etymologically, what gave rise to these two terms? | What is the difference between modulo and modulus? | terminology;modular arithmetic | modulo is an operator. For instance, we might say 19 and 64 are congruent modulo 5.modulus is a noun. It describes the 5 in modulo 5. We might say the modulus is 5.No, the two should not be used interchangeably. It would be incorrect to say 19 and 64 are congruent modulus 5. It would also be incorrect to the modulo is 5.See also https://en.wikipedia.org/wiki/Modular_arithmetic and https://en.wikipedia.org/wiki/Modulo_operation. Both define the word modulus, and as far as I can see they use it correctly. |
_webapps.28481 | I would like to be able to add blog posts to a Facebook group via a service like RSS Graphiti. I know this is possible for Facebook pages, but is this possible for Facebook groups? | Is there a way to automatically post to a Facebook group? | facebook;facebook groups;facebook integration | The list of targets in RSS Graffiti contains both groups and pages that I'm an admin of. (Though I haven't tried whether it actually works.) |
_unix.94243 | Use case: You've got a multi-GB log file for a whole week, and you need to search for something which happened on Saturday using for example grep. Making an educated guess, you assume that starting the search from the middle of the file will more than halve the processing time (since it's definitely not going to have to process the whole of the rest of the file) while not skipping any relevant data. Is this possible? | How to start processing a file at an offset? | shell;files | null |
_cs.67797 | Every time I ask why most people think that P NP, I get a response like because theorem proving is harder than proof checking. From this, I understand that proving theorems is hard. But why is this? In fact, it is known that a theorem, in mathematics, is a statement that has been proved on the basis of previously established statements. So a not proven theorem would not be called a theorem, would it? I mean, a theorem is easy to prove because it is defined to be so and people call it theorem because they know how to prove it, no? If we were talking about conjectures, I would have not asked this question. When I was looking, I found this paper: Cook, Stephen (1971). The complexity of theorem proving procedures. Proceedings of the Third Annual ACM Symposium on Theory of Computing. pp. 151158. But this seems to confuse me furthermore.I am sure I am missing something (maybe some obvious one). Would you please clarify this? | Why theorem proving is hard? | complexity theory;terminology | So a not proven theorem would not be called a theoremNo, it's usually called a proposition, or a conjecture.I mean, a theorem is easy to prove because it is defined to be so and people call it theorem because they know how to prove it, no?Just because you know a proof exists doesn't mean that you can efficiently find that proof.From this, I understand that proving theorems is hardThe thing is, there is no mathematical evidence that it's hard, other than the repeated failures of people to prove that it's easy. But of course, the failures of people to prove that it's hard acts as evidence that it's easy.When people say that proving theorems is harder than checking them, they are speaking from intuition. From a complexity theory standpoint, there is no evidence that proving theorems is harder than verifying them. If there were, we would be able to resolve $P$ vs $NP$. Any guesses one way to the other are just that, guesses.There is, however, an analogy, from computability theory.When people are talking about proving versus checking for $P$ vs $NP$, they usually mean things like SAT or Constructive Propositional Logic, or other such systems with no quantifiers, or restricted quantifiers. But if we extend proofs to include predicate logic, with $\forall$ and $\exists$, then we have a firm result: checking proofs of these is decidable, and generating such proofs is undecidable. This is a basic consequence of the undecidability of the halting problem. |
_softwareengineering.345773 | My team is preparing to add new capabilities to an OpenAPI contract and our implementation of it. There are pre-existing clients. We are planning to take our API from v1.1 to v1.2 while fully respecting semantic versioning.Our team is debating whether we must go to v2.0 instead of v1.2 if we add new possible values to a type definition like this (in yaml):Thing: type: object properties: field: type: string enum: - PreExistingValue1 - PreExistingValue2 - NewValue1 - NewValue2With NewValue1 and NewValue2 being newly introduced possibilities in v1.2. The v1.1 API does not have these two values in the enum.EDIT: Our Thing is only used in the response data.Basically my question is, is it OK to do this with a minor version increase, or must we bump up the major version number to change the API in this way?I'll try not to reveal which side of this argument I'm on and represent the for/against arguments as neutrally as I can:Arguing for only a minor version increase, one team member stated that ultimately, this field is a string, and that isn't changing, so it is OK for this string to take on new values and that is not a threat to backwards compatibility. It is reasonable to expect a client to ignore a string value it does not understand in this field.Arguing for only a minor version increase, one team member stated that the OpenAPI enum is just documentation, that fundamentally we are only declaring a string field in the contract, nothing more.Arguing for a major version increase, one team member stated that because the contract defines it as an enum, the contract in effect carries a guarantee that the string will only have certain values; and with this change that guarantee is now broken. Depending on choice of serialization framework in the client implementation, data using the new values may actually be rejected within framework code automatically.To me, this difference of opinion within the team seems to boil down to the question of how strong the enum concept is in OpenAPI - whether it is to be considered as part of the type definition or, as the one team member said, just documentation.Within the specification, enum refers to this IETF spec which states of enum instances:An instance validates successfully against this keyword if its value is equal to one of the elements in this keyword's array value.But the specification does not say if and only if. It just says if. | Semantic Versioning in OpenAPI with string enum: new values OK? | enum;semantic versioning;openapi | It's my understanding that you have to increment the major version number if your code introduces breaking changes.If Thing is used strictly for input and you're now accepting a couple of new values, then you won't break any existing code.However, if you're returning Thing and I have code likeswitch (myThing) { case PreExistingValue1: doProcess1(myThing); break; case PreExistingValue2: doSomethingElse(); break; default: throw new NotImplementedException();}returning new values will break my code. That's something I'd like to know about. |
_scicomp.2534 | I need to calculate the following integral:$${1\over 2\pi i} \int_C f(E) \, d E$$$$f(E) = {\rm Tr}\,\left(({\bf h} + E)\,{\bf G}(E) \right)$$Where $\bf h$ is a matrix (one particle kinetic and potential energy expressed in a basis), $\bf G$ is a matrix which depends on $E$ (one-particle many-body Green's function) and the contour integral is a left semicircle. The integrand $f(E)$ has poles on the negative real axis and it is expensive to evaluate. What is the most effective way to calculate such integral?Here is my research so far:1) I use Gaussian integration, my integration path is a rectangle. I fixed the left and right side (i.e. width) and played with height (above and below the real axis) such that for the given integration order I get the highest accuracy. For example for order 20, if the height is too large, the accuracy goes down (obviously), but if it is too small, it also goes down (my theory is that it needs more and more points around the poles as height goes to 0). I settled with optimal height 0.5 for my function.2) Then I set the right side of the rectangle at E0, typically E0=0, but it could be E0=-0.2 or something similar.3) I start moving the left side of the rectangle to the left and for each step I do integration order convergence to make sure my integral is fully converged for each rectangle. By increasing the width, I eventually get a converged value in the limit of the infinite left semicircle.The computation is really slow and also not very accurate for large widths. One improvement is to simply partition the long width into elements and use Gaussian integration on each element (just like in FE).Another option would be to integrate a small circle around each pole and sum it up. Problems:a) How to numerically find the poles of the function $f(E)$? It should be robust. The only thing I know is that they are on the negative real axis. For some of them (but not all) I also know a pretty good initial guess. Does there exist a method that works for any analytic function $f(E)$? Or does it depend on the actual form of $f(E)$?b) Once we know the poles, what numerical scheme is the best for integrating the small circle around it? Should I use Gaussian integration on a circle? Or should I use some uniform distribution of the points?Another option might be that once I know the poles thanks to a), there might be some semi-analytic way to get the Residues without the need of the complex integration. But for now I'd be happy to just optimize the contour integration. | How to numerically calculate residues? | numerics;complex analysis | I can offer a suggestion for your first question: If you know your poles are somewhere along the real axis, you could localize them quite efficiently using Rational interpolation/approximation. This amounts to finding polynomials $p(x)$ and $q(x)$ such that$$f(x) \approx \frac{p(x)}{q(x)}$$for $x$ in some interval. The poles of $f(x)$ should then match the roots of $q(x)$.Rational interpolation/approximation can be a tricky thing, but I've recently co-authored a paper on a stable algorithm to compute them using the SVD. The paper contains Matlab code implementing the algorithm, and a more extensive version thereof is available as the function ratinterp in the Chebfun project, of which I am one of the developers. For your second question, this paper may be useful. |
_cs.67362 | I've was studying about network flows and I encountered the special case where vertices also have a capacity. This problem problem can be converted to the conventional one without vertex capacities. This process is for example described here:https://en.wikipedia.org/wiki/Maximum_flow_problem#Maximum_flow_problem_with_vertex_capacitiesThe problem is that I'm not really understanding why this maintains the property flow conversation of the flow function. Could someone explain it to me? In general, could someone explain to me why is the converted flow network without vertex capacities a valid flow network? Why was the the original flow network with vertex capacities a valid flow network?I understood that this maintains the property capacity constraint, since we do not modify the flow values of the edges, assuming that the original flow network with vertex capacities and its flow function are well-formed. | How can a network flow with vertex capacities be equivalent to one without them? | graphs;graph theory;network flow | null |
_scicomp.11121 | I am trying to find the effect on turbulence characteristics when flow passes through a converging section. For this experiment I will use a PIV system to gather data about the flow. However, I could not find any specific literature on flow through symmetric converging channel. (The converging channel I would be using is type of a converging hopper with a circular hole exit.) I have attached a 2d drawing of this Please advise if you know any similar papers relating to this. | Turbulence: Suggest research papers similar to this experiment | fluid dynamics | null |
_webmaster.54301 | I am starting an AdWords campaigns and I will measure conversion rates using the AdWords conversion tracking pixel.Conversion might be account creation or a concrete sale. As it will be a test campaign to have some insights on CTR, CR, etc... on the future, I am likely to try several configurations:Two different ads with different landing URL and messages: one with a focus on the product / the other will contains a discount embedded in the URL.4 different groups or themes of keywords.I guess I have to build 4 ads groups based on the keywords2 ads with the different messagesassign the two ads to each ads groupsfollow the campaign precisely in the ads tabs where I can see the effectiveness of each Ads per Ads Groups (for a total of 8 lines of reporting)Also, what are the key performance indicators that I can have from an AdWords campaign to measure global effectiveness?measure of return on investment from concrete sales (tracking pixel with e-commerce tag on confirmation page)measure o return on investment from leads acquisition (tracking pixel on account creation)measure of traffic increase with the campaign | How to structure my AdWords campaign for testing and different groups of keywords? | google;google analytics;google adwords | I would use a different AdGroup for each landing page or each theme, just as you suggest. Google's AdGroup documentation says:We recommend that you create a separate ad group for each theme such as for each product you offer (like wedding catering and party catering), selling points (like free consultation and gourmet menus), or ways to describe your business (like caterer and on-site food service). The ads and keywords in each ad group should directly relate to that group's theme.As far as measuring goes, assign a dollar value to everything: Track concrete sales and assign the profit dollar value from that sale (ignoring the cost of AdWords)Figure out the value of a lead acquisition. Assign AdWords the value that you would expect to pay for an acquisition from other channels.With these figures in hand, compare how much you are spending to how much value you are getting. Adjust your bids such that you are not bidding above this value. In my experience, you do best when you bit at 70% to 90% of what you expect take make. So for example, if you can make $0.50 per visitor from AdWords, then a bid of $0.38 would be reasonable.I tend not to assign much value to increased traffic itself. If two bids will yield the same traffic but one has higher volume, I will tend to use the higher volume as the tie breaker. |
_cs.42594 | I'm trying to implement a Inventory Routing Problem with Branch-and-Cut. But I'm facing with an issue regarding subtour elimination. (http://www.danflash.com/files/irp.pdf)The paper describes the constraint like this:$$\sum_{i \in S} \sum_{j \in S, j<i} y^t_{ij} \le \sum_{i \in S} z_{it} -z_{kt} \quad S \subseteq M \quad t \in T \quad \text{for some} \ k \in S$$And some page further I've found this: $k=arg max_j\{z_{jt}\}$ but no idea how to interpret this. Where $y^t_{ij}$ is $1$ when the edge is used from $i$ to $j$ at time $t$. And $z_{it}$ is $1$ when vertex $i$ is visited at time $t$.What is the exact definition of $S$? The set of all subtours or one specific subtour? Let say $M = \{1, 2, ...,7\}$ and $M' = \{0, 1, ..., 7\}$ ($M'$ with supplier/depot).And the solution I get contains the following subtours: $0,1,3,0$ and $2,4,5,2$ and $6,7,6$Know how would a pseudo code look like to implement this? And what is $k$? My current solution look like this (implemented in C# with Gurobi solver). But I'm not sure if this should be implemented as a lazy constraint in the callback or adding the constraint after model.Optimize() if a subtour exists and call model.Optimize() again.I did an implementation but I guess it's not worth to post it before I really understand the equation. | Inventory Routing - Subtour Elimination | optimization;linear programming;traveling salesman | $S$ contains every subtour except the tour with the depot. And for each subtour a constraint has to be added.The meaning of $k=argmax_j\{z_{jt}\}$ has been answered in https://math.stackexchange.com/questions/1290142/explanation-of-textrmargmax-jz-jt-and-how-to-implement-it/1290178#1290178I solved this with a callback as soon as a subtour is found. |
_unix.224551 | I made this script to close a process, but I can't compare the awk result (var1) with an Integer: var1 -gt 5000.My script:#!/bin/bashvar1= free -m |awk 'NR == 2'| awk '{print $3}'var2= ps aux | grep '/opt/skype/skype' | grep -v grep | awk '{print $2}'while true;do if [ $var1 -gt 5000 ]; then echo La memoria se ha excedido cerrando porcesos kill -9 $var2 break else echo La memoria aun es estable $var1 fidoneCould it be a casting problem in bash? | Bash: kill process in function of the memory used | bash;shell script | You can cast variables in bash and ksh (use declare -i var or typeset -i var for interger), but I don't think that is your problem.The following will set var1 to nothing while then running the command as normal.var1= free -m |awk 'NR == 2'| awk '{print $3}'If you want the output of free and awk to be set to var1 then the above should read:var1=$( free -m |awk 'NR == 2'| awk '{print $3}' ) |
_webmaster.56438 | On the 26th of November we put Google Custom Search on our site. The day after and all days following traffic dropped off noticeably. This could just be pure coincidence, but it seems odd to have affected the traffic for a whole month.Does anyone know whether there is a known affect from putting Google Custom Search within your site? | Does putting Google Custom Search within your site affect traffic negatively? | seo;google;google search;google custom search | Does anyone know whether there is a known affect from putting a Google search within your site?No. There is no evidence to say Google will penalize a website if it has Google Custom Search on it. The ranking drop might have happened due to other reasons. You have to check all the recent OFF page activities of your website. |
_scicomp.1489 | I am looking for preconditioners which don't assume anything about the matrix or its origins.I basically want to be able to type in the following in MATLAB and have quick solving time:a = rand(5000,5000);b = rand(5000,1);precond_a= my_precond_algorithm(a);qmr(a,b,1e-8,100,precond_a)Needless to say, $a$ is dense.I have looked into:LU works well. But that's no surprise.I am still to find a good algorithm for ILU for dense matrices but I reckon that should work relatively well.Sparse Inverse Approximators (Benzi et. al.) . A paper by Prakash and Mittra discusses the use of Multifrontal Preconds for solving dense Maxwell Equations discretization.Other than LU, I am still a little concerned about the viability of using them as effective preconditioners for large dense matrices. Any resources/comments would be much appreciated! | On Vanilla Preconditioners for solving dense $Ax=b$ iteratively | preconditioning;iterative method | It is critical to know more about the structure. It matters whether the random entries are uniformly or normally distributed and whether there is a shift or not. If there is no structure at all, then you cannot asymptotically beat a direct solve. Some comments on your proposed approachesIncomplete LU is complete LU when applied to a dense matrix. You could consider some thresholding, but it's not likely to work, especially not with a uniform distribution.The inverse is not sparse or have useful decay properties, so a sparse approximate inverse would not be expected to perform well.Integral formulations of Maxwell's equations have very special structure. That paper uses thresholding to create a sparse system. Whether that is beneficial or not (and whether the sparsified matrix is significantly easier to solve with) depends strongly on any special structure in the problem. |
_unix.64904 | I am needing to see the status of some services on some of our RHEL 5.8 hosts on which I am not an admin. Much to my surprise, I am not able to get any info how to do it (such as chkconfig or systemctl on Fedora) from Google. Neither chkconfig nor systemctl are accessible to me, not sure if it is because of permissions or they are just not available on the system but there are no man pages for either.Why is it that there is such a mysterious lack of service management documentation online for RHEL 5.8 and which commands can I use for simple service listings? | Peculiar lack of RHEL 5.8 service management documentation | rhel;services | null |
_codereview.15191 | For logging purposes, I need to output a double[,] to the log file. So I need to represent the array as a string.The following code gets the job done using basic C# 1 features, but I was wondering if there is a more elegant solution using Linq:private static string OneRowPerLine(double[,] numbers){ var ret = new StringBuilder(); for(var i=numbers.GetLowerBound(0);i<=numbers.GetUpperBound(0);i++) { for (var j = numbers.GetLowerBound(1); j <= numbers.GetUpperBound(1); j++) { if(j>numbers.GetLowerBound(1)) { ret.Append(,); } ret.Append(numbers[i, j]); } ret.Append(Environment.NewLine); } return ret.ToString();} | Is there a better way to convert two-dimentional array to string? | c#;linq | First off, I think there may be bugs in your code. Specifically in the dimension parameters of some of the GetLowerBound() parameters. Based on a quick glance, it should be:private static string OneRowPerLine(double[,] numbers){ var ret = new StringBuilder(); for(var i=numbers.GetLowerBound(0);i<=numbers.GetUpperBound(0);i++) { for (var j = numbers.GetLowerBound(1); j <= numbers.GetUpperBound(1); j++) { if(j>numbers.GetLowerBound(1)) { ret.Append(,); } ret.Append(numbers[i, j]); } ret.Append(Environment.NewLine); } return ret.ToString();}I'll update this answer in a moment with some enhancements, but wanted to get this bit out of the way.EDIT: here's a pair of methods which will do it a little more generically and without LINQ. It does employ generics (<T>) and extension methods (this), one of which is an iterator (yield return): private static string OneRowPerLine<T>(this T[,] numbers) { return string.Join(Environment.NewLine, numbers.FormatOneRow()); } private static IEnumerable<string> FormatOneRow<T>(this T[,] numbers) { for (var i = numbers.GetLowerBound(0); i <= numbers.GetUpperBound(0); i++) { var row = new T[numbers.GetLength(1)]; for (var j = numbers.GetLowerBound(1); j <= numbers.GetUpperBound(1); j++) { row[j] = numbers[i, j]; } yield return string.Join(,, row); } }call like this: double[,] stuff = {{1,2}, {3,4}, {5,6}}; Console.WriteLine(stuff.OneRowPerLine()); |
_reverseengineering.8260 | I've been trying to get antiResHacker.exe as mentioned in this question: How to prevent use of Resource editorsHowever, the codebase for ollytlscatch (https://code.google.com/p/ollytlscatch/) seems to be inaccessible. Is there a canonical location for this set of tools or are they no longer in public circulation? | Where is the code for ollytlscatch? | ollydbg;debuggers;anti debugging;digital forensics | The source code for TLSCatch can be downloaded from:https://myollyplugins.googlecode.com/files/TLSCatch.rarAnd the binary for it can be downloaded from these two locations:https://myollyplugins.googlecode.com/files/TLSCatch.dllhttp://www.woodmann.com/collaborative/tools/images/Bin_ollytlscatch_2010-11-3_19.7_TlsCatch.zipFurthermore, you can download sample programs to test TLSCatch from:https://web.archive.org/web/*/http://ollytlscatch.googlecode.com/files/* |
_unix.139493 | I'd like to use a truetype font in xterm/uxterm (version 278) but I get problems with unicode symbols ( for example displays fine, so I guess it's not a disabled utf8 or a locale issue):$ echo -e \xE2\x98\xA0gives me a square instead of with following config:UXTerm*faceName: Liberation MonoUXTerm*faceSize: 9XTerm*faceName: Liberation MonoXTerm*faceSize: 9When I disable truetype fonts using the ctrl right click menu, the symbol displays fine using the default fonts which isn't nice at all. I tried uxrvt and got the same problem when I don't have enough letter spacing, but it works fine when I increase it. However, uxrvt gave me a lot of other problems, just like all the other terminal emulators I tried. Does anybody have an idea? | How can I make unicode symbols and truetype fonts work in xterm/uxterm? | fonts;xterm;unicode;ttf | The Liberation font doesn't seem to have this symbol. But using XTerm*faceName: DejaVu Sans Mono (which is also a truetype font) allows to be displayed.EDIT: Do not use LibreOffice or OpenOffice to determine whether a glyph is supported in a font, as it silently falls back to another font: OpenOffice bug 45128. |
_softwareengineering.269499 | I'm developing a new templating language for PHP, and one of the features is an object-oriented approach to nested child templates. For example, I can declare an object of type HtmlBuilder like this:$template = <div> <h1>{{field1}}</h1> <p>{{field2}}</p> </div>;$content = [ field1 => value1, field2 => value2];$hb = new HtmlBuilder($content, $template);echo $hb->render();In this case, HtmlBuilder does a simple find-and-replace on the fields. But, I could also nest one HtmlBuilder (or one of its more specialized subtypes) inside of another:// Child template$template1 = <p>{{field2}}</p> <p>{{field4}}</p> ;$content1 = [ field4 => something else];$hb1 = new HtmlBuilder($content1, $template1);// Parent template$template2 = <div> <h1>{{field1}}</h1> {{field3}} </div>;$content2 = [ field1 => value1, field2 => value2, field3 => $hb1];$hb2 = new HtmlBuilder($content2, $template2);echo $hb2->render();In this case, when $hb2 is rendered, $hb1 will be automatically rendered in the field3 placeholder.My question is, does it make sense to design this system such that the value of field2 is automatically passed in from the parent template to the child template (while allowing it to be overridden in the child)? Or, should I require that it be explicitly passed in $content1? | Scoping template variables in has-a (compositional) relationships | design;php;templates;composition;scope | Implicit dependencies are bad, especially if your template engine will not complain about missing variables. I believe that it would be beneficial for each template fragment to know which variables it needs, and to refuse to be rendered or instantiated with wrong arguments.Here is an example where the lack of scoping will introduce difficulties:$academic_staff_template = <div> <h4>{{ title }} {{ name }}</h4> {{ bio }} </div>;$lecturer = new HtmlBuilder([], $academic_staff_template);$lecture_template = <html> <head> <title>{{ title }}</title> </head> <body> <h1>Lecture {{ title }}</h1> {{ description }} {{ lecturer }} </body> </html>;$vars = [ title => Archaeology 101, description => ..., lecturer => $lecturer, name => 'Henry Walton Indiana Jones, Jr.', title => Dr., bio => ...,];$lecture = new HtmlBuilder($vars, $lexture_template);Both template use a title variable, but use the same name to mean something completely different. Your current design would produce this rendered output:<html> <head> <title>Dr.</title> </head> <body> <h1>Lecture Dr.</h1> ... <div> <h4>Henry Walton Indiana Jones, Jr.</h4> ... </div> </body></html>Sometimes, it is extremely useful to include another template without entering a new variable scope. For example, {% include snippet/footer %} could be a useful directive to load a snippet. But if we try to create encapsulated, loosely coupled templates, that's running straight into namespace clashes and all kinds of issues.Here's an idea: When you parse a template, you take note of all variables that are required. Such a parsed template can be rendered in one of two ways:Via the API: $result = $engine->parse($source)->render([var1 => value1]). The render method will throw an exception if not all necessary variables are provided.Inside the template language: If block is bound to a parsed template object, then syntax like {{ block var1: value var2: someVariable }} could render the template. No variables except those passed explicitly would be available inside the block. If the given arguments don't match the arguments required by the block, an error would be thrown.Since some data naturally belongs together, it would be great to offer access to arrays within your template language. Then we could pass a single dictionary with info about the lecturer to the academic staff template. Here is how I'd design that interface:$lecturer_template = $engine->parse( <div> <h4>{{ person.title }} {{ person.name }}</h4> {{ person.bio }} </div>);$page_template = $engine->parse( <html> <head> <title>{{ course.title }}</title> </head> <body> <h1>Lecture {{ course.title }}</h1> {{ course.description }} {{ lecturer person: course.lecturer }} </body> </html>);$course = [ title => Archaeology 101, description => ..., lecturer => [ name => Henry Walton \Indiana\ Jones, Jr., title => Dr., bio => ..., ],];$result = $page_template->render([course => $course, lecturer => $lecturer_template]); |
_webapps.25161 | When I search for something on the Trello Development board, why does the search box return no results?It seems like the search function only returns matches to members and items from my own boards that match the search query.So how do I search the Trello Development board, or within any other public boards? | Search on Trello does not return any results when viewing public boards | trello | null |
_cs.76225 | Suppose we have two context-free Languages $L_{1}$ and $L_{2}$, and we form a new language $L_{3}=L_{1} \circ L_{2} = \{\alpha\beta | \alpha \in L_{1},\beta \in L_{2},|\alpha|=|\beta|\}$. Is it possible that $L_{3}$ is not context-free? | Operation on two CFLs which results in a non-CFL | context free | null |
_unix.39776 | I tried to compile a Hello world example in java and got a gcc error. As far as I understand it, gcc is trying to compile my java class (and for some reason failing to find the main method, but that's beside the point). I have openSUSE 12.1 64 bit and JDK 1.7 (installed from Oracle's rpm). I have /usr/java/jdk1.7.0_04/bin/:/usr/java/jdk1.7.0_04/ in my $PATH. When I try to compile a java file, I get: rumtscho@bradbury:/tmp> javac Hello.java/usr/lib64/gcc/x86_64-suse-linux/4.6/../../../../lib64/crt1.o: In function `_start':/home/abuild/rpmbuild/BUILD/glibc-2.14.1/csu/../sysdeps/x86_64/elf/start.S:109: undefined reference to `main'Why is this happening and how can I correct the problem? My complete $PATH is: rumtscho@bradbury:/tmp> echo $PATH/home/rumtscho/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/usr/lib/mit/bin:.:/home/rumtscho/bin:/home/rumtscho/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/usr/lib/mit/bin:/home/rumtscho/android-sdk-linux/tools:/home/rumtscho/android-sdk-linux/platform-tools:/usr/java/jdk1.7.0_04/bin/:/usr/java/jdk1.7.0_04/:/home/rumtscho/bin:/home/rumtscho/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/usr/lib/mit/bin:/home/rumtscho/android-sdk-linux/tools:/home/rumtscho/android-sdk-linux/platform-tools:/usr/java/jdk1.7.0_04/bin/:/usr/java/jdk1.7.0_04/ | What is wrong with my JDK installation? | opensuse;path;java | Commands are looked up in $PATH in the order in which the directories are listed. In your case, it is likely from your description that there is no /home/rumtscho/bin/javac, no /usr/local/bin/javac, but a /usr/bin/javac that is the GCC Java compiler (or a symbolic link to it).SuSE has an alternatives mechanism to handle programs that have multiple implementations. According to the SuSE documentation on installing Java, SuSE's Java packages use this mechanism. If the Oracle package respects this interface, then runupdate-alternatives --config javacto select your favorite Java compiler (you should do the same with java to select a matching runtime environment).If the Oracle binary is not mentioned in the list, you can manually switch to it:ln -snf /usr/java/jdk1.7.0_04/bin/{java,javac} /etc/alternatives/Alternatively (but this is not recommended if the alternatives method works), you can create a symbolic link to your prefered javac in your ~/bin directory (per-user setting) or in /usr/local/bin (system-wide setting).ln -s ../../java/jdk1.7.0_04/bin/javac /usr/local/binAnother way would be to reorder your PATH to have the Oracle JDK directory first. In your ~/.profile, make sure to add /usr/java/jdk1.7.0_04/bin at the beginning of your PATH. You can take the opportunity to remove it if it was already in the $PATH, to avoid duplicate entries (which are harmless except for a very slight slowdown when looking for a command at the end of $PATH or looking up a non-existent command name).prepend_to_path () { PATH=:$PATH: case $PATH in *:$1:*) PATH=${PATH%%:$1:*}:${PATH#*:$1:};; esac PATH=$1${PATH%:}}prepend_to_path /usr/java/jdk1.7.0_04/bin |
_cstheory.10008 | In a general for loop of the form:for (i = 0, i <= n, i++) { for (j = i, j <= n, j++) ... for (k = i, k <= n, k++) ...}What form do the inequalities representing the iteration space take? Or what convex polyhedron represents this?BackgroundI am looking at the Dragon Book's chapter on parallelisation. This talks in detail of nested loops of the form:for (i = 0, i <= n, i++) { for (j = i, j <= n, j++) ...}but not of the form described at the top.The iteration space of d-deep nested loops can be represented as:$$ \{ i \in \mathbb{Z}^d \mid Bi + b \geq 0 \} $$where B is a $d \times d $ integer matrix and b is a vector of length $d$My question is basically do I have to do anything different when a loop contains multiple inner loops not nested within each other? | How is the iteration space of a nested for-loop containing two sequential nested loops represented? | dc.parallel comp;compilers | null |
_unix.16101 | Currently, I have the following in my .zshrc:bindkey '^[[A' up-line-or-searchbindkey '^[[B' down-line-or-searchHowever, this only seems to match the content of my current input before a space character occurs. For example, sudo ls / will match every line in my history that begins with sudo, while I would like it to only match lines that match my entire input. (i.e. sudo ls /etc would match, but not sudo cat /var/log/messages)What do I need to change in order to gain the desired behavior?Here is my entire .zshrc in case it is relevant: https://gist.github.com/919566 | ZSH: search history on up and down keys? | zsh;command history;line editor | This is the documented behavior:down-line-or-search Move down a line in the buffer, or if already at the bottom line, search forward in the history for a line beginning with the first word in the buffer. There doesn't seem to be an existing widget that does exactly what you want, so you'll have to make your own. Here's how to define a widget that behaves like up-line-or-search, but using the beginning of the line (up to the cursor) rather than the first word as search string. Not really tested, especially not on multi-line input.up-line-or-search-prefix () { local CURSOR_before_search=$CURSOR zle up-line-or-search $LBUFFER CURSOR=$CURSOR_before_search}zle -N up-line-or-search-prefixAn alternate approach is to use history-beginning-search-backward, but only call it if the cursor is on the first line. Untested.up-line-or-history-beginning-search () { if [[ -n $PREBUFFER ]]; then zle up-line-or-history else zle history-beginning-search-backward fi}zle -N up-line-or-history-beginning-search |
_ai.2367 | Let's say I have a string America and I want to convert it into a number to feed into a machine learning algorithm. If I use two digits for each letter, e.g. A = 01, B = 02 and so on, then the word America will be converted to 01XXXXXXXXXX01 (1011). This is a very high number for a long int, and many words longer than America are expected. How can I deal with this problem?Suggest an algorithm for efficient and meaningful conversions. | How to convert string to number and number to string efficiently? | machine learning | null |
_unix.161926 | $ sort -t $'\t' -k 1rn,1 -k 2,2rn -k 3f,4 listaprezzi2050 900 bananas 51905 700 grapes 17250 4000 oranges 10230 9200 figs 4220 5000 lemons 10200 8000 pears 8I want to sort 1st column of listaprezzi numerically in reverse (option rn), 2nd also rn, and third alphabetically (f). What is the correct command?I've tried many ways but having no success. | How to sort columns independently? | text processing;sort;columns | If I correctly understand your question you want to rearrange your data, i.e. independently sort (up or down) different fields of the same row. You cannot do that with bare sort, you need to use additional tools, for example with the help of awk and paste you can write the following:$ paste <(awk '{print $1}' listaprezzi | sort -nr) <(awk '{print $2}' \ listaprezzi | sort -nr) <(awk '{print $3}' listaprezzi | sort) <(awk \ '{print $4}' listaprezzi)And the result is2050 9200 bananas 51905 8000 figs 17250 5000 grapes 10230 4000 lemons 4220 900 oranges 10200 700 pears 8 |
_softwareengineering.229748 | We are currently working on a project that heavily relies on a database.Among many tables the main focus is on table data which is linked to another table data_type as many-to-one, which is then linked to table data_operation as one-to-many.The last table defines specific set of operations that has to be processed for each row in table data based on specific data type. The operation is processed against specific fields in table data and partially data from other tables, not mentioned in this example. The actual operation is mostly a complex calculation or specific formula. The result of a specific operation will be stored in yet another table.So in general we have:Projection for table data is approximately one million rows per year, while other tables should not change drastically on a yearly basis, but it will initially hold a few thousand rows, that is, each data type will define roughly 10-15 operations.Each operation should be reversible (revert changes).Processing speed is a very important factor.The application will most likely process 2500 new table data rows per day.My question is concerning the best approach to implement operations.Do you think it is wiser to move business logic and rules to a database (procedures, triggers for each operation) or implement and process each operation in the application/business layer? What would be the ideal generic structure?Also I am open for other approaches as well. | Implementing bussiness logic with a large number of business rules and processes | database design;optimization;business logic;business rules;programming logic | I'm not sure why euphoric didn't post his comment as an answer but he's correct. The same data might show up in many use cases and that will impact your rules. You should design your business classes for each use case based in the expected behavior. Then you can look at what data you have and figure out how to store it.For example you might be able to save a partial quote. You may require more data though before the system allows a quote to be sent to a customer. Yet different rules for the quote to be converted to an order, etc. |
_codereview.55169 | I am a newbie and tried to find the laziest way to do a file upload using EmberJS, jQuery and formdata (IE10+). The code might look stupid, but it worked.Can you please take a look and give some suggestions? Am I doing it wrong?<script type=text/x-handlebars data-template-name=posts><form role=form enctype=multipart/form-data method=post id=fileinfo {{action 'createPost' on='submit'}}> {{input type=text value=newPost id=newPost placeholder=Post class=form-control}} {{input type=file id=inputFile class=form-control name=file}} <button type=submit class=btn btn-default >Submit</button></form></script>App.PostsController = Ember.ArrayController.extend({actions: { createPost: function(){ var fd = new FormData(document.getElementById(fileinfo)); fd.append(postContent, this.get('newPost')); this.set('newPost', ''); //reset text field $('#inputFile').val(''); //reset fileinput field Ember.$.ajax({ url: http://localhost:3000/posts, type: POST, data: fd, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType }); } } }); | Ember.js file upload code | javascript;jquery;html;ajax;ember.js | null |
_codereview.45801 | Could someone help me on how to eliminate some nested blocks or improve this code? I am concerned this will slow down my site dramatically.function dispalyEvent($weekNr, $week, $year){ echo <p>; $gendate = new DateTime(); $gendate->setISODate($year,$week,$weekNr); $event_query = mysql_query(SELECT * FROM calendar ORDER BY starttime); //Go through all event in the database while($event = mysql_fetch_array($event_query)) { //Create a range for starting date and ending date $date1 = new DateTime($event['startyear'].$event['startmonth'].$event['startdate']); $date2 = new DateTime($event['endyear'].$event['endmonth'].$event['enddate']); $date2->modify('+1 day'); $period = new DatePeriod($date1, new DateInterval('P1D'), $date2); $title = $event['title']; $name = $event['name']; $recur_query = mysql_query(SELECT * FROM recur WHERE title = '$title' AND name = '$name'); $recur = mysql_fetch_array($recur_query); $recurring = $recur['type']; //Find day of starting recurring event and ending day if (!$recurring == None){ $starttime = explode(/,$recur['startdate']); $startdate = new DateTime(); $startdate->setDate($starttime[2], $starttime[0], $starttime[0]); $endtime = explode(/,$recur['enddate']); $enddate = new DateTime(); $enddate->setDate($endtime[2], $endtime[0], $endtime[0]); } else { $startdate = new DateTime(); $enddate = new DateTime(); } //Put the dates in integer to find if it is out of range $displaydate = intval($gendate->format(Ymd)); $startdate = intval($startdate->format(Ymd)); $enddate = intval($enddate->format(Ymd)); settype($displaydate, integer); settype($startdate, integer); settype($enddate, integer); //Go through each date in the range foreach ($period as $savedDate) { //Check if the Item is Approved if ($event['Approved'] == Approved){ switch($recurring){ Case 'None': //If the date in the range is the same as the displaydate if ($gendate->format(Y-m-d) == $savedDate->format('Y-m-d')){ //Create event renderEvent($event['ad'], $event['starttime'], $event['title'], $event['endtime'], $event['location'], $event['address'], $event['price'], $event['description']); } break 1; Case 'Daily': //Check margin between start and end date of recurring event if ($displaydate > $startdate and !$displaydate < $enddate){ //Check if the day number is the same if ($recur['day']-1 == $gendate->format(w)){ //Create event renderEvent($event['ad'], $event['starttime'], $event['title'], $event['endtime'], $event['location'], $event['address'], $event['price'], $event['description']); } } break 1; Case 'Weekly': //Check margin between start and end date of recurring event if ($displaydate > $startdate and !$displaydate < $enddate){ //Find the amount of weeks between two dates $weekRange = datediffInWeeks($recur['startdate'], $recur['enddate']); //Round down to the possible amount to display $weeks = ceil($weekRange / $recur['day']); //Returns the week cuurent week to display $currentWeek = $gendate->format(W); //Loop for every #(1, 2, 3, 4) of weeks for ($n=0; $n<$weeks; $n++) { //Display event if weeks are the same if ($n == $currentWeek) { //Put days in array $days = explode(,,$recur['weekday']); //If number day of the week is the same display event foreach ($days as $day) { //Check if the day number is the same if ($day == $gendate->format(w)) { //Create event renderEvent($event['ad'], $event['starttime'], $event['title'], $event['endtime'], $event['location'], $event['address'], $event['price'], $event['description']); } } } } } break 1; } } } } echo </p>;} | I have a huge function filled with nested blocks | php;beginner | Ok, the following review may seem blunt or harsh, but please, try to keep in mind that this is in order to help. I'm not trying to hurt or mock anyone, but in order for code-review to be as effective as it ought to be, I'll have to be brutal.If you haven't read it already, the help-section asks you post working code. bug-riddled code isn't subject to review yet, it has to be debugged first.It is possible you aren't aware of it, and that you may think your code works, when really it doesn't. Well, not as you expect it to, at least. I know it feels banal and tedious, closely looking at the operator precedence table doesn't do any harm. Quite the opposite, in fact. You'll soon find out why Both David Harkness and myself mention potenial bugs or unexpected behaviour with expressions like:if (!$recurring == None)//andif ($displaydate > $startdate and !$displaydate < $enddate)And as a last point in this foreword to what is already a hefty answer, I would like to strongly suggest you change your php.ini settings for the error_reporting and set display_errors to true, one, or stdout, depending on your PHP version.The error_reporting's default value is likely to be E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED, while debugging, it's best to set it to E_ALL | E_STRICT, or call error_reporting(-1); in your script.As I have done before, I'll walk through your code line by line, offering advice and the reasoning behind my criticism. At the end, I'll add an example of code you could end up with if you decide to take my recommendations to heart.Update: I did not add a code example as there are simply too many unknowns to deal with, and that any example would basically end up being a total re-write of your code, which isn't my job, and is of little educational use to you. Instead, just to make it 100% clear, however blunt or harsh this answer may seem here's a meta-post on why I consider it necessary for code-review to be toughNow, without further ado, let's get too it:function dispalyEvent($weekNr, $week, $year){Yes, I have some criticisms about the very first line of code you posted already. Ok, a function displayEvent, that expects 3 arguments. All three have to do with time. But if you need variables that tell you something about time, why not ask of the user (caller) to pass a DateTime class from the off?function displayEvent(DateTime $date){Now this tells the user of your code that he's expected to pass a DateTime instance as an argument. It reduces the number of arguments from 3 to 1, and allows for type-hints. As we'll see in a second, this also saves you the bother of creating the DateTime instances inside the function. The advantage of that is that, if the caller already has a DateTime instance, he can simply pass that object, and not call methods to get the year, week and weekNr values, which are only being used to re-construct the same DateTime instance all over.Onwards: echo <p>;Don't echo in a function. A function returns. The caller of your function may then choose to echo the return value, or may store it somewhere else. Having a function echo something puts the user of your code in a tight spot: calling this function means he can't set the headers, can't use this function to retrieve data and present it in a way he wants to. Just create a variable $outString = '';, and return that at the end. $gendate = new DateTime(); $gendate->setISODate($year,$week,$weekNr);As I said before: this code can be made redundant simply by changing the function's signature to expect a DateTime instance from the off $event_query = mysql_query(SELECT * FROM calendar ORDER BY starttime); //Go through all event in the database while($event = mysql_fetch_array($event_query)) {Please, please, please stop using the deprecated mysql_* extension. Switch to PDO or mysqli_* instead. Henceforth I'll be using PDO.And as a rule of thumb, or even personal mantra: Avoid SELECT * queries whenever you can. Select what you need, and how you need it. You haven't done that last bit at all, judging by the next snippet of code: //Create a range for starting date and ending date $date1 = new DateTime($event['startyear'].$event['startmonth'].$event['startdate']); $date2 = new DateTime($event['endyear'].$event['endmonth'].$event['enddate']); $date2->modify('+1 day');Why not select these dates like so:SELECT CONCAT_WS('-', startyear, startmonth, startdate) AS date1That way, you'll be able to write:$date1 = new DateTime($event['date1']);That's just, I think you'll agree, a hell of a lot cleaner. Anyway, back to the code: $period = new DatePeriod($date1, new DateInterval('P1D'), $date2); $title = $event['title']; $name = $event['name'];Why bother assigning individual variables, you have an associative array, what's wrong with that? An assoc array is a data structure that holds together all related data anyway. This data clearly belongs together, why not keep it together in that array?We'll get to the DatePeriod business in a moment, for now, let's carry on:$recur_query = mysql_query(SELECT * FROM recur WHERE title = '$title' AND name = '$name');$recur = mysql_fetch_array($recur_query);$recurring = $recur['type'];//Find day of starting recurring event and ending day if (!$recurring == None){ $starttime = explode(/,$recur['startdate']); $startdate = new DateTime(); $startdate->setDate($starttime[2], $starttime[0], $starttime[0]); $endtime = explode(/,$recur['enddate']); $enddate = new DateTime(); $enddate->setDate($endtime[2], $endtime[0], $endtime[0]);}else { $startdate = new DateTime(); $enddate = new DateTime();}Ok, you may have noticed I fixed the indentation. Seriously, indentation is important. For your sake and ours. Stay consistent and try to adhere to the standard as much as you can.Anyway: This code basically queries the same DB for, pretty much, the same data over and over again. Of course, the where clause is different every time, but what you're doing is sending a string to MySQL, who then parses and compiles the query and then fetches the data.A prepared statement can be sent to the DB once, to be compiled, optimized (and in many cases, a lot of the data is even pre-fetched), and you can then send the values that are to be placed in the WHERE clause whenever you need that query to be executed. This saves the DB server a lot of work, saves time and is more secure. You're just stringing $name and $title in the query, for example. Completely oblivious to the fact that There could be a name like O'Connor assigned to $name. Resulting in the Query:SELECT * FROM recur WHERE title = 'foobar' AND name = 'O'Connor'Which will cause problems. And what if Bobby Tables pays a visit?On the DateTime things, I can only say: Why explode? Why not simply write:$recur['startdate'] = new DateTime($recur['startdate']);DateTime does a great job at guessing the format, but if you wish not to rely on this, you can always choose to specify the format yourself:$recur['startdate'] = DateTime::createFromFormat( 'd/m/Y', $recur['startdate']);Anyway, let's continue://Put the dates in integer to find if it is out of range$displaydate = intval($gendate->format(Ymd));$startdate = intval($startdate->format(Ymd));$enddate = intval($enddate->format(Ymd));settype($displaydate, integer);settype($startdate, integer);settype($enddate, integer);DRY, Don't Repeat Yourself. You are calling the intval function. Look at the return type:int intval ( mixed $var [, int $base = 10 ] )// \---> returns an INTWhy, then are you calling settype? It's pretty safe to say you're calling settype on an int already. Even if you're not, why not cast? A cast saves the overhead of a function call:$displaydate = (int) $gendate->format(Ymd);That's all there is too it, and you've saved yourself the bother of 2 function calls.Moving on://Go through each date in the rangeforeach ($period as $savedDate) { //Check if the Item is Approved if ($event['Approved'] == Approved){ switch($recurring){Ok, think about what you're doing here. For each date in the DatePeriod, you're evaluating, basically, what the results of the initial query told you. Why do you need to check those more than once? You know the $event['Approved'] and $recurring values aren't going to change. Determine which case is going to be true beforehand. Then you can significantly shorten the loop body.You're only processing those events that have been approved! Why not add that to the WHERE clause in your query????SELECT * FROM calendar WHERE Approved = 'Approved' ORDER BY starttime;That way, you don't have to check the value of $event['Approved'] to begin with. Also: break; is the same as writing break 1;. The latter just looks weird here. Anyway, consider writing separate functions for various event-types: renderNonRecurring, renderDailyEvent and (but there's a lot to be said about this case still) renderWeeklyEvent.You can then write something as simple as:foreach ($period as $savedDate){ switch ($recurring) { case 'None': if ($gendate == $savedDate) {//DateTime instances can be compared like so, no format needed renderNonRecurringEvent($event); } break; }}Notice how I don't pass every individual key of the array to the render function, but instead just pass all of the event-related data. Doesn't that make sense to you?Of course, looking at this function's tendency to echo, I take it your render* functions echo, too. Just have them return the output string and concatenate it to the $outString I mentioned in the beginning of my answer:$outString .= renderEvent($event);Now, for the big one:Case 'Weekly': //Check margin between start and end date of recurring event if ($displaydate > $startdate and !$displaydate < $enddate){Operator precedence... this condition is just terribly unreliable. and has a low precedence. Use &&. Always. Unless you know what you're doing.Also think about what you're trying to check when you write!$displaydate < $enddateAre you saying(!$displaydate) < $enddate//if inverse boolean value of $displaydate < $enddate//ie: if $displaydate truthy, then this would evalute to:// if (!true) < $enddate -> false < $enddate --> 0 < $enddateOr are you trying to check for:$displaydate >= $enddate //makes a lot more sense, no?For some reason, you've created a function to get the diff in weeks. What is odd is that you insist on passing the date string to this function, when you've already constructed a DateTime instance for these dates. At least pass that to the function, because I'm prepared to take a punt that this datediffInWeeks function creates those same instances all over. But to be honest, I'd just not bother, and write this in-line, there's not a lot too it anyway. Here's the code you have: //Find the amount of weeks between two dates $weekRange = datediffInWeeks($recur['startdate'], $recur['enddate']); //Round down to the possible amount to display $weeks = ceil($weekRange / $recur['day']);And this is what I'd write:$weekRange = $recur['startdate']->diff($recur['enddate']);$weeks = range(0, ceil($weekRange->d/7));//d property is number of days, as int//to get range of number of weeks:$weeks = range( (int)$recur['startdate']->format('W'),//start from current week $recur['startdate']->format('W') + ceil($weekRange->d/7));Now once you have that, there is no point in looping over the array, is there? a simple in_array call, or even if (min($weeks) <= $gendate->format(W) && max($weeks) >= $gendate->format(W)) would do the trick.The same logic applies to the days business. That way, you can do away with all those nested loops, because that's just an unholy, slow, messy and unmaintainable mess.PDO: Reusing prepared statements:Here's an example of how I'd query the data using PDO, re-using prepared statements://outside the loop, call prepare$stmt = $pdo->prepare('SELECT * FROM recur WHERE title = :title AND name = :name');//note no quotes, just :title and :name$events = $pdo->query('SELECT * FROM calendar WHERE Allowed = Allowed ORDER BY starttime ASC');//order by <field> ASC/DESCwhile ($event = $events->fetch(PDO::FETCH_ASSOC)){//inside call execute as much as you want $stmt->execute( array( ':name' => $event['name'], ':title' => $event['title'] ) ); $recur = $stmt->fetch(PDO::FETCH_ASSOC);}General recommendationsRefactor this code ASAP. Learn about more modern MySQL extensions, PDO or mysqli_*. Both are more powerful than mysql_*, but mysqli_* is the most powerful of the lot. However, its API is messy (alowing both OO and procedural style programming), and has a lot more pitfalls owing to its complexity.I haven't touched on this in my answer, but never assume all is going well. Check what functions return. They could return false, 0 or null, or they could throw an Exception, to let you know all is not well. Don't ignore those situations, deal with them.Write a couple of one-liners down as guide lines, for example:Prepare queries that use variables in the WHERE clause, by using prepared statementsIf you have to scroll to read through a function, you're doing too much in one function. Split the logic over several functions.DRYOnly SELECT what you needFunctions don't echo, they return. Think of them as books. They contain information, you read it, and can then relay that information to others. A book doesn't read itself out loud to other people. That's not its function.errors happen. That's a fact. Check the return values of functions (false, 0, null or wrap them in a try-catch block). Check the manual, to see what each function returns in case something goes wrong.Learn about prepared statements and injection. This implies changing the MySQL extension you use, this page helps you with thatDebugging implies seeing the bugs. Therefore E_STRICT | E_ALL + display_errors are a must. |
_cogsci.5959 | Following a question on UX.Stackexchange about whether or not to use an analog or digital clock on a website from a user-interface perspective it occurs to me that there is probably a psychological difference between using one or the other.My hypothesis is that it takes longer to know the time when reading digital instead of analog because as children we are taught to understand time via analog clocks (5 past, half past, quarter to etc) so when confronted with a digital clock we have to do some internal calculations to convert from digital numbers into a mental analog clock before we actually understand what the time is. (07:47, ok so if 07:45 is quarter-to that means it's now half-way between quarter-to and ten-to eight...).However I'm aware this may just be my own internal process I'm citing rather than being how people in general use clocks so I'm interested to know if my hypothesis is actually supported / disproved. | Does it take more cognitive effort to tell the time when reading a digital clock instead of analog? | time | null |
_reverseengineering.14712 | I'm analyzing load commands section of executable Mach-O file in iOS 9.3.3, Twitter app is used for ilustration.# otool -hV Twitter Twitter:Mach header magic cputype cpusubtype caps filetype ncmds sizeofcmds flagsMH_MAGIC_64 16777228 0 0x00 EXECUTE 49 4208 NOUNDEFS DYLDLINK TWOLEVEL PIEI've read that every executable contains LC_UNIXTHREAD command which is responsible for starting the binary's main thread. However, there's no such command in examined file.# otool -l Twitter | grep LC_ cmd LC_SEGMENT_64 cmd LC_SEGMENT_64 cmd LC_SEGMENT_64 cmd LC_SEGMENT_64 cmd LC_SYMTAB cmd LC_DYSYMTAB cmd LC_LOAD_DYLINKER cmd LC_UUID cmd LC_LOAD_DYLIB cmd LC_LOAD_DYLIB cmd LC_LOAD_DYLIB [...repetition omitted...] cmd LC_RPATH cmd LC_RPATH cmd LC_CODE_SIGNATUREI cannot understand why it's not there. Does it have anything in common with the fact that this app runs with mobile user privileges or that it's proprietary app of the third party? I found this LC command e.g. for /bin/ls, but not for any of tested proprietary apps. | No LC_UNIXTHREAD segment in iOS application Mach-O | ios;mach o | Since a few versions ago, LC_UNIXTHREAD has been deprecated in favor of the new command, LC_MAIN.#define LC_MAIN (0x28|LC_REQ_DYLD) /* replacement for LC_UNIXTHREAD */struct entry_point_command { uint32_t cmd; /* LC_MAIN only used in MH_EXECUTE filetypes */ uint32_t cmdsize; /* 24 */ uint64_t entryoff; /* file (__TEXT) offset of main() */ uint64_t stacksize;/* if not zero, initial stack size */};Possibly your otool is a little old and does not support it. |
_softwareengineering.200583 | I am learning Android programming and right now and i'm reading about fragments. I understand what fragments are, but either the tutorial is missing some steps or i'm missing something. So my question is when developing an Android UI, what are the benefits, if any, to using fragments as apposed to single page layouts? Are fragments more common than single page layouts or is it more based on the situation. Also, if fragments are more common, do you try to structure most situations so that fragments work? | Benefits to using fragments in Android projects | android;android development | Fragments aren't terribly useful on a phone. They were added to the API when people started wanting easier ways to take advantage of the extra real estate on a tablet.Think of an app with a list down the left side. When you select an item on the list, it launches a new activity using the remainder of the screen space, and you want to be able to swipe to cycle between previously selected activities.Without fragments, you require a class to manage the entire screen, keep a stack of which activities have been selected, keep track of which one is current, and manage all of their life cycles. If you use the same app on a phone, where the activity takes the entire screen, you don't need the manager class. With fragments, all the life cycle stuff is handled for you, essentially moving your manager class into the operating system. That makes tablet development easier and more standardized, and also makes sharing code between phones and tablets easier. |
_softwareengineering.176515 | What is the most concise (yet descriptive) way of naming a subclass that only add a specific minor thing to the parent? I encountered this case a lot in WPF, where sometime I have to add a small functionality to an out-of-the-box control for specific cases.Example: TreeView doesn't change the SelectedItem on right-click, but I have to make one that does in my application. Some possible names are TreeViewThatChangesSelectedItemOnRightClick (way too wordy andmaybe difficult to read because there is so many words concantenatedtogether)TreeView_SelectedItemChangesOnRightClick (slightlymore readable, but still too wordy and the underscore also breaks the normalconvention for class names)TreeViewThatChangesSIOnRC (non-obviousacronym), ExtendedTreeView (more concise, but doesn't describe whatit is doing. Besides, I already found a class called this in thelibrary, that I don't want to use/modify in my application).LouisTreeView, MyTreeView, etc. (doesn't describe what it is doing).It seems that I can't find a name which sounds right. What do you do in situation like this? | How to name an subclass that add a minor, detailed thing? | .net;coding style;naming;wpf;class design | If your application is supposed to use both the original, non-right-sensitive version and your own improved version, then the name absolutely has to express what the derived class does. Otherwise everyone navigating the code base will go nuts understanding what the difference is and where it applies or not. Something like RightSensitiveTreeView is probably your best bet, even though it is already clumsy and will become much more clumsy if you ever need to express more than one extended behaviour.But if you use the extended version exclusively, there is little harm in using a euphonious, even proud name like LouisTreeView - it will stay accurate even if you add more enhancements later, since those presumably will also be used everywhere. The only thing you should not do is reuse the original name exactly and disambiguate by putting it into a different package path. That is just asking for confusion.(Disclaimer: proverbially, there are only two really hard things in computer science - cache invalidation and naming things. This is my opinion, but people will probably come forward with very different views.) |
_unix.210653 | I am attempting concatenate file names to use in a ftp mdelete command. Each file name needs to be separated by a space in order for the mdelete command to work. The $i variable is in a loop and I am attempting to assign the file name located into $i to $FILESTODELETE in addtion to the file names already in $FILESTODELETE for i in `ls` do $FILESTODELETE = $FILESTODELETE $i ..... END...... mdelete $FILESTODELETE | concatenating file names in a variable | shell script;ksh;variable | set -- *filenames=$*As long as you haven't modified your environment's value for $IFS, the above is all you need to get all of the names of not-dot files in the current directory into a single string as divided by spaces and sorted by locale in any POSIX shell. If you have modified $IFS, then whatever its first character is will sub for the single space divider just mentioned instead.Note, though, that the above is no guarantee that said filenames don't also contain spaces, or newlines, or basically any character but NUL or / - those probably aren't in the filenames. |
_datascience.11063 | I have a dataset of reviews and I want to extract the features along with their opinion words in the reviews.Is it possible to extract features from my data using any Vector Space Model?(TF-IDF, Word2Vec, etc.)Edit for sample data:Teacher, Subject, FeedbackDr. Tayal,Discrete Mathematics,He has very good subject knowledge. He didn't take all the lectures. He teaches and explains concepts very well.Ms Vibha,OOPS,Subject knowledge is poor, but she is regular with classes. She is unnecassrily strict and does not teach the subject nicely. | Feature Extraction and Vector Space Model | feature extraction;word2vec | null |
_softwareengineering.135697 | I'm doing a course in college, where one of the labs is to perform buffer overflow exploits on code they give us. This ranges from simple exploits like changing the return address for a function on a stack to return to a different function, all the way up to code that changes a programs register/memory state but then returns to the function that you called, meaning that the function you called is completely oblivious to the exploit.I did some research into this, and these kinds of exploits are used pretty much everywhere even now, in things like running homebrew on the Wii, and the untethered jailbreak for iOS 4.3.1My question is why is this problem so difficult to fix? It's obvious this is one major exploit used to hack hundreds of things, but seems like it would be pretty easy to fix by simply truncating any input past the allowed length, and simply sanitizing all input that you take.EDIT: Another perspective that I'd like answers to consider - why do the creators of C not fix these issues by reimplementing the libraries? | Why is it so difficult to make C less prone to buffer overflows? | c;vulnerabilities;buffers | They did fix the libraries.Any modern C standard library contains safer variants of strcpy, strcat, sprintf, and so on.On C99 systems - which is most Unixes - you will find these with names like strncat and snprintf, the n indicating that it takes an argument that's the size of a buffer or a maximum number of elements to copy.These functions can be used to handle many operations more securely, but in retrospect their usability is not great. For example some snprintf implementations don't guarantee the buffer is null-terminated. strncat takes a number of elements to copy, but many people mistakenly pass the size of the dest buffer.On Windows, one often finds the strcat_s, sprintf_s, the _s suffix indicating safe. These too have found their way into the C standard library in C11, and provide more control over what happens in the event of an overflow (truncation vs. assert for example).Many vendors provide even more non-standard alternatives like asprintf in the GNU libc, which will allocate a buffer of the appropriate size automatically.The idea that you can just fix C is a misunderstanding. Fixing C is not the problem - and has already been done. The problem is fixing decades of C code written by ignorant, tired, or hurried programmers, or code that has been ported from contexts where security didn't matter to contexts where security does. No changes to the standard library can fix this code, although migration to newer compilers and standard libraries can often help identify the problems automatically. |
_unix.185864 | Just as above, I increased the RAM (it's a VM), but that doesn't give me a safety net.I was under the impression by default it should respawn, but that doesn't seem to be the case.*Ubuntu 10.04Any suggestions? | Respawn MySQL on Ubuntu? Server ran out of memory, killed MySQL & Apache, MySQL didn't respawn | ubuntu;mysql;upstart | null |
_unix.67376 | I install slime through ELPA. Here is what my .emacs file looks like:(setq inferior-lisp-program sbcl --noinform)(add-to-list 'load-path ~/slime/) (require 'slime)(slime-setup)(setq package-archives '((gnu . http://elpa.gnu.org/packages/) (marmalade . http://marmalade-repo.org/packages/) (melpa . http://melpa.milkbox.net/packages/)))I get the following error when I start emacs:Warning (initialization): An error occurred while loading `/home/name/.emacs':File error: Cannot open load file, slimeTo ensure normal operation, you should investigate and remove the cause of the error in your initialization file. Start Emacs with the `--debug-init' option to view a complete error backtrace.When I debug: Debugger entered--Lisp error: (file-error Cannot open load file slime) require(slime) eval-buffer(#<buffer *load*> nil /home/name/.emacs nil t) ; Reading at buffer position 91 load-with-code-conversion(/home/name/.emacs /home/name/.emacs t t) load(~/.emacs t t) #[0 \205\262When I visit ~/.emacs.d/elpa/slime-20130308.1112, slime.el is clearly there. Other people online seem to be having issues too. If I cannot get it to work with emacs24, how can I setup a slime environment for common lisp? | problems using slime on emacs24 | emacs;configuration;lisp | I installed emacs 24 using the Debian amd64 package from Damien Cassou's ppa. I had some problems with slime (I don't recall if they were the same as those above). I fixed it by reinstalling quicklisp (http://www.quicklisp.org/), then using it to install slime:(ql:quickload :quicklisp-slime-helper)It works fine with sbcl for me (on two machines). I just looked at my .emacs; I have nothing added to my load-path, just(load (expand-file-name ~/quicklisp/slime-helper.el))(setq inferior-lisp-program sbcl)(require 'slime)(slime-setup '(slime-fancy)) |
_softwareengineering.164696 | I've noticed that July 26th (my birthday) is used really often in various PHP examples related to preventing http caching using Expires header, like:https://stackoverflow.com/questions/12398714/cache-issue-with-private-networking-streamhttps://stackoverflow.com/questions/2833305/how-to-expire-page-in-php-when-user-logouthttp://expressionengine.com/archived_forums/viewthread/81945/What's special in that date? | What's special in July 26th and why is it used in examples for Expires header so often? | php;headers | Probably somebody did that as an example of a cache expires a long time ago and then everybody copied it. Interestingly it's often expressed as Mon, 26 July 1997, but the actual date occurred on a Saturday. It's not that interesting in terms of UTC seconds (seconds since 1970) since it is 869893200. Maybe it's just an example of CTRL-C/CTRL-V coding? |
_webmaster.52401 | I have seen many websites using slugs in their URL to boost SEO such as this:http://example.com/article/1543/how-to-boost-seo/I was thinking if I could do something like this instead:http://example.com/article/1543#how-to-boost-seoand specify it as the canonical URL. This article from Google says, It's a hint that we honor strongly. Does that include the fragment identifier, or would it be discarded? | How does Google treat hash fragment inside a canonical URL | seo;canonical url;hash | Fragment identifiers are traditionally used to identify a portion of document for client-side applications. As stated in the specification Google adopted:Traditionally, hash fragments (that is, everything after # in the URL) have been used to indicate one portion of a static HTML document. ...hash fragments are not part of HTTP requests (and as a result they are not sent to the server)Consequently as this covers, the Googlebot ignores hash fragments by default. Therefore for this URL:http://example.com/article/1543#how-to-boost-seoGooglebot should just look at the resource returned by the server: http://example.com/article/1543 while ignoring the hash fragment: how-to-boost-seo.So essentially the resource for the above URL is the canonical URL after normalization (i.e., removing the fragment).The purpose of using a slug is to identify a page as a human-readable keyword. Using a fragment confuses this purpose and obscures its readability:/how-to-boost-seo is a lot more readable than: /1543#how-to-boost-seoSo in short, using a fragment as a slug would not seem beneficial to users or search engines. |
_webapps.8936 | Say I get an email with 30 eddresses in the To: field (or CC, etc) is it possible to create a new mailing group from all these people in any webmail app?I'm sort of primarily looking for this in hotmail and gmail, but I can't find anything. | Possible to create mailing group from multiple email addresses in a message I received? | email | null |
_cs.6514 | Looking for some tutorials / references that discuss Breadth First Search that takes into consideration the cost of paths, but could not find much information.Could someone refer a tutorial? | Breadth First Search with cost | algorithms;reference request;graphs;search algorithms | From a general point of view: there are tons, but I do sincerely recommend you the latest volume on Heuristic Search: Heuristic Search: Theory and Applications by Stefan Edelkamp and Stefan Schroedl. From a specific point of view: in spite of the graph being directed or not, breadth-first search taking costs into accountIf no heuristics are available, then it amounts to either Dijkstra or Uniform Cost Search. An excellent discussion between these two algorithms is presented in Felner, Ariel, Dijkstra's Algorithm versus Uniform Cost Search or a Case Against Dijkstra's Algorithm, Symposium on Combinatorial Search, Barcelona (Spain), 2011.If heuristics are available Then there are also a number of interesting alternatives: A$^*$ is the usual one but RBFS also expands the same nodes in the same order with a linear consumption of memory. For these, I do strongly recommend the book by Stefan Edelkamp and Stefan Schroedl.Hope this helps, |
_webmaster.72365 | A while back I installed the Google Analytics app for iOS, this one ==> https://itunes.apple.com/gb/app/id881599038?mt=8I noticed that it showed a different number of Unique Visitors compared to total number of Users in the web-interface of Google Analytics at google.com/analyticsThe difference is 61%... the app shows 61% MORE Unique visitors compared to the web version of Google Analytics.How is this different? Or why?Am I the only one experiencing this? | Google Analytics iOS app showing different data (61% different) | google analytics | null |
_vi.12897 | Nvim (v0.2.1-535-g8370373) has started misbehaving on my Red Hat Enterprise Linux 7 box. It works fine via Putty, but from bash I get an odd character (001b in a litle box; perhaps this is the unicode escape character?) followed by a few other wrong characters when I type : or i (for example). When I hit escape they go away but they obscure what I'm typing. This occurs with vim -Nu NONE or vim -Nu NORC.For example, if the first line of text is 1234567890 and I go to the first column and press i it changes to:xx6 q67890(where xx is the 001b character).Vim is fine on the same box. Nvim used to be fine until I updated it via compiling source. Reverting back to the previous version doesn't fix it, suggesting it's environmental. Experimenting a little reveals that this problem goes away if I set the environment variable xterm to nothing. Usually, though, it's set to xterm-256color so that Nvim's colours are displayed correctly. | Escape character appearing in Neovim when Xterm set to 256-color | neovim | null |
_codereview.47903 | The goal here is to create a Top Level Menu that automatically pulls child pages without the need to manually add them to said menu. I didn't know any other way to accomplish this without a walker, of which I'm not very familiar with. I was playing around with it and was able to get the submenus to work with this. The submenu gets added at the bottom of start_el/** The Walker **/class fitz_and_the_tantrums extends Walker_Nav_Menu { // add main/sub classes to li's and links function start_el( &$output, $item, $depth, $args ) { global $wp_query; $indent = ( $depth > 0 ? str_repeat( \t, $depth ) : '' ); // code indent // passed classes $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); // build html $output .= $indent . '<li id=nav-menu-item-'. $item->ID . ' class=' . $class_names . '>'; // link attributes $attributes = ! empty( $item->attr_title ) ? ' title=' . esc_attr( $item->attr_title ) .'' : ''; $attributes .= ! empty( $item->target ) ? ' target=' . esc_attr( $item->target ) .'' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel=' . esc_attr( $item->xfn ) .'' : ''; $attributes .= ! empty( $item->url ) ? ' href=' . esc_attr( $item->url ) .'' : ''; $attributes .= ' class=menu-link ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . ''; $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s', $args->before, $attributes, $args->link_before, apply_filters( 'the_title', $item->title, $item->ID ), $args->link_after, $args->after ); // build html $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); if(nav_hasChildren($item->object_id)){ $output .= '<ul class=submenu>'; ob_start(); wp_list_pages( array( 'child_of' => $item->object_id, 'depth' => 1, 'title_li' => '' ) ); $output .= ob_get_clean(); $output .= '</ul>'; } }}/** Check if item has Children **/function nav_hasChildren($pid) { $children = get_pages('child_of='.$pid); if($children) return true; else return false;}Is there a way to minimize the needed code, or do I absolutely need to set everything so that the Walker can function properly? | Automatic submenu | php;wordpress | null |
_cs.6655 | Suppose a build max-heap operation runs bubble down over a heap. How does its amortized cost equal $O(n)$? | How can I prove that a build max heap's amortized cost is $O(n)$? | data structures;runtime analysis;heaps | I assume that the operation build just turns an array into a heap by repairing the heap-property for every subtree bottom-up (let the operation for a single repair step called heapify).It is not so hard to see, that heapify takes $O(h)$ steps, where $h$ is the height of the subtree to repair. We set $k=\lfloor \log n \rfloor $ as the height of heap. Notice that we have no more then $2^{(k-h)}$ subtrees of height $h$. So we can simply add up the costs as follows (we slightly abuse the big-O notation):$$ \sum_{h=1}^k O(h) 2^{k-h} = 2^k \sum_{h=1}^k O(h)/2^{h}. $$Since $\sum_{h=1}^\infty O(h)/2^{h}$ converges, we can upper bound the sum $\sum_{h=1}^k O(h)/2^{h}$ by a constant $C$. Thus we have that the running time for built is less than $C\cdot 2^k\le C \cdot n = O(n)$. |
_webmaster.87996 | Basically, I have two sites, each for separate language:example.com (for EN readers)example.pl (for pl_PL readers)Data on these sites is not exactly the same, so I cannot link one subpage from language 1 to another in language 2 (example.pl/article1.html example.com/article2.html) as there can be no relation at all (different content, different targets, but the same company). Let's say we target two regions with our sites.We want to have link in the header to point to the homepage of opposite language site. On example.com we want to have link to example.pl and vice versa. What is the best approach to not affect SEO?Curently, we just pointed it like <a href=http://example.com>xxx</a> and Google shouts at as that that we have many points from one site to another - we have a lot of subpages on both sites. | Multilingual site, links to homepage | seo;multilingual;homepage;hyperlink | null |
_unix.238073 | I'm trying to write a simple script to take a previous command that was (accidentally) written in a non-English layout, convert everything into correct symbols and run it. I'm using Bash 4.3.11.My current code looks like this (I'm not a programmer, just trying to learn this for general usability):echo !! | sed -e y/first-set-of-symbols/second-set-of-symbols/ | bashThe problem is, when I run the script from a file, I get this: bash: line 1: !!: command not found, but when I just copy paste the whole command, it does what it's expected to do; if I change the echo part to something like echo test-command in the script file, that works when I run the script, too.Could someone please help me understand why !! isn't working from a script here? Is it supposed to?I am also open to any suggestions on how to do what I'm trying to do in a better / more efficient / more elegant way.(I'm not using tr, because, apparently, it doesn't work with Unicode, or so they sayat least it doesn't work for me at all.) | Can't get echo !! to work in bash from a saved script | bash;command history | null |
_cogsci.127 | I've caught myself writing (typing) possible instead of possibly a few times over the past few days, while I do intend to write possibly. Only upon rereading the sentence I notice my mistake.It is not a typo. I am able to touch-type on a qwerty layout on which 'e' and 'y' are both written using a different hand, and different fingers. The keys are two keys apart from each other.A simple google search for psychology writing wrong words didn't show up any immediate relevant results. I did read about a Freudian Slip, but it seems highly unlikely I would make such a mistake due to an unconscious ('dynamically repressed'), subdued, wish, conflict, or train of thought.Is there any psychological phenomenon explaining why I would make such an error? | Why do you sometimes write down one word while actually intending to write another? | cognitive psychology;language | null |
_softwareengineering.82709 | I have been asked to help estimate the time it would take to develop a web application. I will not be involved in the actual programming, but I am participating as an experienced programmer. The actual work will probably be handed over to a consulting company, but the client (a university department) wants to have an estimate to have an idea of how much time and money will be needed.We will try to break down the features to implement and then try to create some kind of grand total estimate (even though Joel Spolsky says this will not work), but I thought that these kinds of web applications have been done hundreds of times and that there must be lots of experience to draw from on one or another of the stackexchange sites.Is it possible to answer this question:How many hours/weeks does it generally take for an experienced programmer, using their language and framework of choice (be it Java, Ruby on Rails, or some other fairly big technology), to create a web application, given that:It is fairly standard, meaning that there is a database, an administration interface and a presentation layer for the general public.It is written from scratch, but there are old systems to draw experiences from.The administrators (think they) know fairly well what they want.I know this is very vague, but I am looking for your experiences:(made up examples follow)We have bought these kinds of systems several times, and they generally take twenty staff-months to complete.Using Python and Django, I'd say most web apps are up and running in 6 staff-months, top.Edit:Some clarification:I my question most information about this project is missing. The client has written a detailed specification draft on the system and there is also a requirement analysis based on user feedback on the old system. I want to state, again, that I am looking for your experiences (see my example answers), not a quote for this system.Thanks for all the insightful answers, though! | Statistics on time estimates for web application | estimation;freelancing;time estimation | This is almost impossible to get an accurate cost on. Outsourcing makes this even more difficult. Just because it's fairly standard doesn't make the task of quoting any easier. For example: you mentioned there is an Administration Interface. This can be as simple as a login and password for each user or complex with users who have multiple roles and a superuser that can oversee all admin tasks. If this becomes a role based admin then the coding time has just increased exponentially.If you are outsourcing to a foreign country I'd pad the total time and cost by 20% to account for interpretation of questions and answers between customer and coder.As a ballpark for database driven admins we would estimate 4 hours for each base table. This allowed for table creation, insert routines, update routines, delete routines and the associated admin web pages. This also included a simple listing display page and a detail display page. If search filter queries were required then we'd add 2 more hours for that table.We did have a lot of code we could borrow from. We also wrote some utility stored procs that helped us speed up the coding by spitting out source code. It wasn't perfect code but it saved us many hours of raw coding. We also would undercut the price if this was a widget we could turn around and resell to other clients. It doesn't sound like you can resell this to anyone else so the price they pay should be a premium.Is there a similar Commercial Off The Shelf (COTS) system already built that you can buy?Have you even entertained the Build or Buy question?Custom software is expensive. As long as you make the customer aware of this fact up front and they still want a custom solution, they will pay the premium price. Every time you say, Oh yeah, we can do that and don't say it will cost more, the customer will expect it for free. |
_codereview.29434 | I am trying to solve the Longest Palindromic Substring problem on LeetCode, and I have come up with a DP solution pasted below:public class Solution { String string; boolean[][] visited; String[][] results; private boolean isPalindrome(String s){ String test = new StringBuilder(s).reverse().toString(); if(test.equals(s)) return true; else return false; } private String maxLengthString(String... args){ String result = new String(); for(String arg:args){ if(arg.length() > result.length()) result = arg; } return result; } private String findLongestPalindrome(int start,int end){ if(start >= end) return new String(); else if(start >= string.length() || start < 0) return new String(); else if(end <= 0 || end > string.length()) return new String(); else{ if(visited[start][end-1] == true) return results[start][end-1]; String result = new String(); if(this.isPalindrome(string.substring(start,end))) result = maxLengthString(string.substring(start,end), findLongestPalindrome(start+1,end), findLongestPalindrome(start,end-1)); else result = maxLengthString(findLongestPalindrome(start+1,end), findLongestPalindrome(start,end-1)); visited[start][end-1] = true; results[start][end-1] = result; return result; } } public String longestPalindrome(String s) { // Start typing your Java solution below // DO NOT write main() function string = s; visited = new boolean[s.length()][s.length()]; results = new String[s.length()][s.length()]; return findLongestPalindrome(0,s.length()); }}The algorithm is quite straightforward, but the online judge complains about it not being efficient enough. I am just wondering if this algorithm is slow by nature (in which case I have to find another algorithm) or if it's something about my implementation. | Longest Palindromic Substring challenge solution is inefficient | java;algorithm;strings;programming challenge;palindrome | null |
_computerscience.4964 | gl.drawArrays()/gl.drawElements() initiates a drawing and returns immediately.There is also (non-recommended) gl.finish() that (theoretically) blocks execution until rendering is complete.Is there a way to receive event when rendering is complete, or other ways to track status of rendering, without blocking execution of the main thread? If there are, how well they work with Offscreen rendering (to a buffer)? | How to know when rendering is complete in WebGL? | rendering;webgl | You can utilize ARB_sync or in other words sync objects which have been core since 3.2.From the point-of-view of OpenGL then right after issuing a specific command (you want to know whether has finished), you'd insert a fence.Say you want to check if a glDrawArrays() call has been executed.glDrawArrays(...);GLsync sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);Note that if glFenceSync() fails it will return 0.You can now check whether it has finished by doing:GLint signaled = 0;glGetSynciv(sync, GL_SYNC_STATUS, 1, NULL, &signaled);if (signaled == GL_SIGNALED) // Doneelse // Not doneYou can then of course repeatably call glGetSynciv() and check when you receive GL_SIGNALED.If you want to completely block until it's done then you can do:GLenum status = glClientWaitSync(sync, 0, 0);if (status == GL_CONDITION_SATISFIED) // DoneIt blocks and waits for up to timeout nanoseconds (the last parameter).Remember to delete the sync object again:glDeleteSync(sync);When it comes to WebGL. Then note that sync objects are not supported in WebGL 1.0. They are however in WebGL 2.0 in the form of WebGLSync.The equivalent to the above code in WebGL 2.0 would be the following:var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);var signaled = gl.getSyncParameter(sync, gl.SYNC_STATUS);if (signaled == gl.SIGNALED) // Doneelse // Not donevar status = gl.clientWaitSync(sync, 0, 0);if (status == gl.CONDITION_SATISFIED) // Donegl.deleteSync(sync); |
_unix.203479 | Got a cronjob that downloads things regularly:if ! su scpuser -c scp ... > /dev/null 2>&1 || ! [ -f $scptarget ]; then; error did not download stuff$scptarget is where the thing gets download to and it's on a different volume than the script that is running (but not a different state, same hard drive I think)Every time it errors out we go in and look and the file is there. Is there a chance that the part that checks for the file's existence would succeed if it just chilled out a little bit? Alternatively, could SCP be tossing errors even when it succeeded? (I wish the guy who wrote this in the first place would have logged what the actual error was, I'm just kind of grasping at straws)If so, I don't want to add an arbitrary sleep to this script, is there something classier that real bash programmers do? | Is it possible to have a lag between scp and checking for new file | bash;files;scp | null |
_softwareengineering.178262 | What reasons to companies have for open-sourcing libraries and applications?Doing this may allow a developer to better understand the code, but could doing this allow people to find and exploit vulnerabilities in the library or application? | Why Open-Source Code? | open source | null |
_unix.313771 | I want to set up a /home where users have their own private folder and in addition share a different group folder with other users.The goal is that users have their own small-sized folder for private files and the bulk of data is shared in the group folderLet's say user quotas are set at 100GB and group quota at 1TB. We have a group 'G' consisting of users 'A', 'B' and 'C'I wonder what happens if user A makes a file in the group G folder. For clarity the file permission in this example are userA:groupG.For these files are they added to the user quota, the group quota or both?And if they are counted to both quotas how can I change it so that files created at the group level are not added to the user quota?I think I address a very basic point but I haven't found an answer to it online. Sorry if I missed it somehow.Any explanations will be gladly appreciated.Cheers | How are Linux user/group quotas counted if a file is owned by both the user and the group? | linux;users;group;quota | null |
_cogsci.16614 | In Determinants of Emotion Duration and Underlying Psychological and Neural Mechanisms by Verduyn et al, the authors discuss various dispositions that account for how long an emotional effect lasts:ResilienceDepression levelExtraversion and neuroticismExtraversion and neuroticism are two components of the OCEAN model of personality. How were these two attributes determined to be most important when it comes to dealing with emotions? What is the relation between personality and disposition? | Relation between disposition personality in emotional response | cognitive psychology;emotion;personality | Those two personality factors can be considered as a component of disposition. Two publications established that extraversion and neuroticism as being the most correlated with emotional processing.In Adding Liebe und Arbeit: The Full Five-Factor Model and Well-Being from McCrae et al (1991), the authors correlated three measure of weel-being with 429 adult men and women.Consistent with previous rescarch, neuroticism was negatively, and extraversion was positively, related to well-being. Both agreeableness and conscientiousness were also significant independent predictorsIn The happy personality: a meta-analysis of 137 personality traits and subjective well-being by DeNeve et al (1998) examine 137 personality constructs across 9 literature search strategies to find determine the effect on positive and negative affect.The traits most closely associated with SWB were repressive-defensiveness, trust, emotional stability, locus of control-chance, desire for control, hardiness, positive affectivity, private collective self-esteem, and tension. When personality traits were grouped according to the Big Five factors, Neuroticism was the strongest predictor of life satisfaction, happiness, and negative affect. Positive affect was predicted equally well by Extraversion and Agreeableness. |
_softwareengineering.36034 | Everybody knows that people that have prejudices against certain programming languages. Especially PHP seems to suffer from problems of its past and some other things (like loose types) and is often called a non-serious programming language that should not be used for professional applications.In that special case PHP: How do you argue using PHP as your chosen programming language for web applications? What are the benefits, where is PHP better than ColdFusion, Java, etc.? | What are the benefits of PHP? | php | Josh K has pointed out some pretty good points, so I wont reiterate that. Instead I'll add some more.It's interpreted. Just FTP/SSH into your account, change the stuff needs to be changed and presto! No need to compile, to deploy, to restart the server.Of course this is something that is compelling for people working in non formalised development environment, with no version control, automated tests, automated builds etc.It is in fact easySeriously. At least for the real beginner it's really easy. So easy that when my cousin expressed an interest in learning how to program, I bought him a Python book instead. PHP's conventions might teach you some bad habits.It is capableI have a life long, mutual feud with C/C++ languages. Somehow we don't like each other. While at university, when I had to do projects involving computations, I would choose PHP over C++ and in each case I could achieve what I intended. Maybe the program execution was in fact slower than if it was written in C++, but it was not a factor in this case.Anyway: neural networks, genetic algorithms, fuzzy logic... I did all of these on PHP. Yes... people had been telling me I was weird. |
_codereview.105480 | I'm using this technique for highlighting current links (e.g. how the Questions link is highlighted on this very page you're looking at). I changed the code a little bit and came up with this extension method: public static MvcHtmlString MenuLink( this HtmlHelper helper, string content, string action, string controller) { var routeData = helper.ViewContext.RouteData.Values; var currentController = routeData[controller]; var currentAction = routeData[action]; var builder = new TagBuilder(li) { InnerHtml = content }; if (String.Equals(action, currentAction as string, StringComparison.OrdinalIgnoreCase) && String.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase)) { builder.AddCssClass(active); return MvcHtmlString.Create(builder.ToString()); } return MvcHtmlString.Create(builder.ToString()); }It works fine, But thats some ugly code. I use the extension method this way:@Html.MenuLink(<a href= + @Url.Action(MainPage, Ticket) + ><i class='fa fa-fw fa-home'></i>Ticket Page</a>, MainPage, Ticket)As you can see, part of that isn't strongly typed.Do you have any ideas to improve the extension method? | Highlight Current Link | c#;asp.net mvc | One thing that I see that I would change is the if statement if (String.Equals(action, currentAction as string, StringComparison.OrdinalIgnoreCase) && String.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase)) { builder.AddCssClass(active); return MvcHtmlString.Create(builder.ToString()); }I personally don't like having a conditional that spans over multiple lines, so the first thing that I would do is to take the boolean conditions and make them into boolean variables and then use them inside the conditional. I think it would be easier to read. bool isCurrentAction = String.Equals(action, currentAction as string, StringComparison.OrdinalIgnoreCase);bool isCurrentController = String.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase);if (isCurrentAction && isCurrentController){ builder.AddCssClass(active); return MvcHtmlString.Create(builder.ToString());}And since you are returning builder immediately after the if statement, there isn't really a reason to return inside the if statement, it is rather redundant. Just delete that from the if blockbool isCurrentAction = String.Equals(action, currentAction as string, StringComparison.OrdinalIgnoreCase);bool isCurrentController = String.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase);if (isCurrentAction && isCurrentController){ builder.AddCssClass(active);} |
_unix.241887 | Typically on Debian when you install things from the repository, they just work. It sets up things just fine and life is good. This is great for things that are up to date in the repository.I am building some tools that I would like to manually update from github or mercurial.using cmake or the configure script to build the code is fine, I also add my own prefix path so that I can easily remove or update the packages if need be.I just build SDL2 from mercurial and installed it into /opt/SDL2 and added that to my path. I had to do that to be able to build SDL_imagewhich gave me this output after finishing it's process.Libraries have been installed in: /opt/SDL_IMAGE/libIf you ever happen to want to link against installed librariesin a given directory, LIBDIR, you must either use libtool, andspecify the full pathname of the library, or use the `-LLIBDIR'flag during linking and do at least one of the following: - add LIBDIR to the `LD_LIBRARY_PATH' environment variable during execution - add LIBDIR to the `LD_RUN_PATH' environment variable during linking - use the `-Wl,-rpath -Wl,LIBDIR' linker flag - have your system administrator add LIBDIR to `/etc/ld.so.conf'See any operating system documentation about shared libraries formore information, such as the ld(1) and ld.so(8) manual pages.This output above says a lot and I am not really sure how to parse it. In the past I used a mac which simplified a lot of this stuff but on linux I am having some trouble.My understanding from reading that above code is that I should add something like this to my bashrc file.export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/SDL_IMAGE/libexport LD_RUN_PATH=$LD_RUN_PATH:/opt/SDL_IMAGE/libto my bashrc, so that when I am linking against sdl image headers it'll find it? I've skimmed the man pages for ld but honestly I don't get it and that's why I am asking.Especially this line: use the `-Wl,-rpath -Wl,LIBDIR' linker flag | building code from source and adding them to your path | path;c;bashrc;ld | Xcode and Fink|Homebrew|MacPorts on Mac OS X have these complications (they just largely hide it from you). There are two aspects to this problem, compiling, and running. Compiling will require a variety of details for any library installed to a custom path. This info for some libraries can be provided by pkg-config, e.g. for a little software depot I maintain under my home directory:$ ls ~/usr/rhel6-x86_64/lib/pkgconfig/goptfoo.pc jkiss.pc libsodium.pc$ echo $PKG_CONFIG_PATH/homes/jdoe/usr/rhel6-x86_64/lib/pkgconfig$ pkg-config --libs --cflags libsodium-I/homes/jdoe/usr/rhel6-x86_64/include -L/homes/jdoe/usr/rhel6-x86_64/lib -lsodium $ These magic strings must be fed into the compile process for any software that is being built against libraries in your custom install tree. Details will vary depending on whether Makefile or autotools or cmake or so forth. One easy way is to set CFLAGS to contain the pkg-config output, or just include the output on the build line:mkpwhash: mkpwhash.c gcc -std=gnu99 `pkg-config --cflags --libs libsodium` -lcrypt -Werror -Wall -Wextra -Wundef -ftrapv -fstack-protector-all -pedantic -pipe -o mkpwhash mkpwhash.cFor autotools or cmake, you'll need to dig around to see how they attach this particular onion to their belt, e.g. study existing configure.ac configurations from packages that use autotools, etc.For running something that has been compiled to use a shared library from the custom path, setting LD_LIBRARY_PATH probably will suffice (or, system-wide, fiddle with ld.so.conf):$ unset LD_LIBRARY_PATH$ ldd ~/usr/rhel6-x86_64/bin/mkpwhash | grep sodium libsodium.so.13 => not found$ exec $SHELL$ echo $LD_LIBRARY_PATH /homes/jdoe/usr/rhel6-x86_64/lib$ ldd ~/usr/rhel6-x86_64/bin/mkpwhash | grep sodium libsodium.so.13 => /homes/jdoe/usr/rhel6-x86_64/lib/libsodium.so.13 (0x00007e5c12ca7000)$(This being unix, there are several ways to exfoliate the Bos grunniens, hence the at least one of... advice from your build process output. More complicated software depots will likely use stow or similar, depending on how much rope (and, thus, headaches) you want to give yourself.) |
_softwareengineering.355389 | I have gone back and forth on this issue several times.On one hand, you could argue, a repository's single responsibility is to manage the persistent state of an entity, and the consuming application is the one that knows whether it will accept a stale value or not in exchange for performance.However, if you are dealing with an out of process cache, and many different applications/servers all need that same cached value, putting the caching code in the repository is a convenient place for, and would help avoid cache duplication. Since there is, at that point a single cache acting as a single source of truth, and acting as a buffer for the DB, it seems more appropriate for a repository to contain caching code.Does caching code belong in a repository? What about specifically an out of process cache (such as redis) acting as a buffer to the database? If caching code does not belong in a repository, where should it reside if many desperate pieces of code need that same value? | Does caching belong in a repository class? | design patterns;data access | null |
_datascience.15203 | I am trying to make a model of this image. Here is the relevant code:base_model = VGG16(weights='imagenet')conv4_3, conv3_3, conv2_2, conv1_2 = base_model.get_layer('block4_conv3').output, base_model.get_layer('block3_conv3').output, base_model.get_layer('block2_conv2').output, base_model.get_layer('block1_conv2').output# Use the output of the layers of VGG16 on x in the modelconv1 = Convolution2D(256, 1, 1, border_mode='same')(BatchNormalization()(conv4_3))conv1_scaled = resize(conv1, 56)...conv5 = Convolution2D(3, 3, 3, border_mode='same')(merge([ip_img, conv4], mode='sum'))op = Convolution2D(2, 3, 3, border_mode='same')(conv5)for layer in base_model.layers: layer.trainable = Falsemodel = Model(input=base_model.input, output=op)model.compile(optimizer='sgd', loss=custom_loss_fn)I have a bunch of colored images in a directory. The input image should be the grayscale of an image stacked thrice(224x224x3) and the op should be the UV planes of the image(224x224x2) which I can add to the grayscale(224x224x1) to get the YUV image. The custom loss function works on the UV of the original image and UV of the prediction.How do I train it? | Image as input and output in keras | python;deep learning;convnet;keras;theano | null |
_codereview.77052 | GetBootstrap v2.7.0 Update from GetBootstrap v2.5I add a progress bar feature in my console application customizer and update the #region grouping and convert the switch statement to Dictionary that suggested in the last version. For now I need help in reviewing my codes in ProgressBar.cs. You can also review my source code and contribute in my GitHub if you want. DOWNLOAD GetBootstrap v2.7.0My objective is to create a progress bar that can be modify to 4 different size (small, normal, medium, and large) and change color. This is the best code I can make. Any Suggestion?ProgressBar.cspublic class ProgressBar{ public int Max { get; set; } public int Value { get; set; } public ConsoleColor Color { get; set; } public ProgressBarSize Size { get; set; } float _Calculation { get; set; } public ProgressBar() { Max = 100; Value = 0; Color = ConsoleColor.Blue; Size = ProgressBarSize.Normal; } public void Increment(int value) { Value += value; if (Value <= Max) { SetUpProgressBar(); WriteProgressBar(); } } private void WriteProgressBar() { ProgressBarSize size = Size; object valueSize = Convert.ChangeType(size, size.GetTypeCode()); int position = 1; for (int i = 0; i <= _Calculation * Value; i++) { Console.BackgroundColor = Color; Console.CursorLeft = position++; Console.Write( ); } for (int i = Value; i <= (int)valueSize + 1; i++) { Console.BackgroundColor = ConsoleColor.Gray; Console.CursorLeft = position++; Console.Write( ); } WriteProgressBarStatus((int)valueSize); } private void WriteProgressBarStatus(int p) { Console.CursorLeft = p + 5; Console.ResetColor(); Console.Write(Value + of + Max); } private void SetUpProgressBar() { ProgressBarSize size = Size; object valueSize = Convert.ChangeType(size , size.GetTypeCode()); Console.CursorLeft = 0; Console.Write(|); Console.CursorLeft = (int)valueSize + 2; Console.Write(|); Console.CursorLeft = 1; _Calculation = ((int)valueSize + 0.0f) / Max; }}public enum ProgressBarSize{ Small = 20, Normal = 30, Medium = 40, Large = 60} | Console Application Customizer - GetBootstrap v2.7.0 | c#;console | It is normally a good idea to separate data from behavior as this way we follow SOLID guidelines.I recommend creating a ProgressBar object and maybe a ProgressBarOperationService or the like with the behavior. The ProgressBarOperationService would receive the ProgressBar that needs the operation in all its methods. |
_unix.382570 | 06/26/2017 23:40:40 CAUAJM_I_10082 [aspsun14 connected for IOALPPRXXBD_ALPGLGENFAALL 55443.15215291.1]06/26/2017 23:40:40 CAUAJM_I_40245 EVENT: CHANGE_STATUS STATUS: STARTING JOB: IOALPPRXXBD_ALPGLGENFAALL MACHINE: aspsun1406/26/2017 23:40:42 CAUAJM_I_40245 EVENT: CHANGE_STATUS STATUS: RUNNING JOB: IOALPPRXXBD_ALPGLGENFAALL MACHINE: aspsun1406/26/2017 23:49:19 CAUAJM_I_40245 EVENT: CHANGE_STATUS STATUS: SUCCESS JOB: IOALPPRXXBD_ALPGLGENFAALL MACHINE: aspsun14 EXITCODE: 006/27/2017 23:40:23 CAUAJM_I_40245 EVENT: CHANGE_STATUS STATUS: STARTING JOB: IOALPPRXXBD_ALPGLGENFAALL MACHINE: aspsun1406/27/2017 23:40:24 CAUAJM_I_10082 [aspsun14 connected for IOALPPRXXBD_ALPGLGENFAALL 55443.15236942.1]06/27/2017 23:40:25 CAUAJM_I_40245 EVENT: CHANGE_STATUS STATUS: RUNNING JOB: IOALPPRXXBD_ALPGLGENFAALL MACHINE: aspsun1406/27/2017 23:48:19 CAUAJM_I_40245 EVENT: CHANGE_STATUS STATUS: SUCCESS JOB: IOALPPRXXBD_ALPGLGENFAALL MACHINE: aspsun14 EXITCODE: 006/28/2017 23:41:36 CAUAJM_I_40245 EVENT: CHANGE_STATUS STATUS: STARTING JOB: IOALPPRXXBD_ALPGLGENFAALL MACHINE: aspsun1406/28/2017 23:41:37 CAUAJM_I_10082 [aspsun14 connected for IOALPPRXXBD_ALPGLGENFAALL 55443.15258301.1]06/28/2017 23:41:38 CAUAJM_I_40245 EVENT: CHANGE_STATUS STATUS: RUNNING JOB: IOALPPRXXBD_ALPGLGENFAALL MACHINE: aspsun1406/28/2017 23:48:47 CAUAJM_I_40245 EVENT: CHANGE_STATUS STATUS: SUCCESS JOB: IOALPPRXXBD_ALPGLGENFAALL MACHINE: aspsun14 EXITCODE: 0I have a file having above content, I want the output like, job name then start time then End timeIOALPPRXXBD_ALPGLGENFAALL 06/26/2017 23:40:40 06/26/2017 23:49:19IOALPPRXXBD_ALPGLGENFAALL 06/27/2017 23:40:23 06/27/2017 23:48:19IOALPPRXXBD_ALPGLGENFAALL 06/28/2017 23:41:36 06/28/2017 23:48:47 | Shell Script for formatted output | bash;shell script;shell;ksh;shell builtin | null |
_hardwarecs.6809 | I would like remote on/off control for two heating zones and hot water. There are many more or less smart thermostats which can do this, however they require internet access. The trouble is my phone is my wireless router - if I leave the house, so does the internet connection.Alternatively there are a few thermostats with GSM radios like this one, but with more limited functionality/channels or they come with locked SIM modules and poor value subscriptions.So as I have some programming skills, I thought about setting one up myself using a normal thermostat and having my own thing as an on/off override switch, perhaps between the thermostat and heating devices.This option looks fairly simple, and if it all goes wrong, I can probably use the wingle on its own. That being said, I might not need an integrated WiFi router for this purpose!So what I really want to ask: What embedded or mini-computer board and SIM module would make sense for a beginner with programming experience (beginner meaning the integration of the two should not be too hard)?I suspect a Raspberry or similar thing might be an idea because of the luxury of the screen output making debugging easier? Second priorities would be low standby power and lowish cost. Thank you. | Sensible embedded board and SIM module to switch heating on and off in response to text messages | embedded systems;mobile phone | null |
_codereview.3954 | I'm writing GUI controls and there are many places where there are many nested ifs checking for some result.function TMyObject.GetCursor: TCursor;begin if CanDragX then begin if CanDragY then Result := crSizeAll else Result := crSizeWE; end else if CanDragY then Result := crSizeNS else if CanClick then Result := crHandPoint else Result := crArrow;end;How would you format/rewrite this code? | Nested IF code in GUI Controls | delphi | I would do this:function TMyObject.GetCursor: TCursor;begin if CanDragX and CanDragY then Result := crSizeAll else if CanDragX then Result := crSizeWE else if CanDragY then Result := crSizeNS else if CanClick then Result := crHandPoint else Result := crArrow;end;But really it is a matter of style and what is most readable to you (and the person who will maintain it). |
_cs.9844 | I have read some complexity papers in which for infinitely many input sizes is used.What is the difference in the computational complexity context between for infinitely many input sizes and for all input sizes? | What is the difference between for infinitely many n and for all n? | complexity theory;terminology | for infinitely many input sizes $n$, $P(n)$ holds means there are input sizes $n_1$, $n_2$, $\ldots$, (infinitely many) such that $P(n_i)$ holds for all $i$. In other words, for every integer $k$, there is an input length $n \geq k$ such that $P(n)$ holds.In contrast, for all input sizes, $P(n)$ holds means that for every input size $n$, $P(n)$ holds.Typically, for all input sizes, $P$ holds and for almost every input size, $P$ holds are used interchangeably, although the latter technically means that there is a $k$ such that for all input sizes $n \geq k$, $P$ holds. (Note that the negation of for infinitely many input sizes, $P$ holds is for almost every input size, $\neg P$ holds.) This is generally because in the models of computation being considered, constant factors don't matter, so from an almost every input size statement you can generally hardcode the solutions for all inputs of length less than $k$ in your model, and get a for all input sizes statement. |
_unix.185602 | I have used the ltunify pairing tool for Logitech Unifying Receiver, written by Lekensteyn, on my Logitech M510 mouse and K350 keyboard, which works perfectly. However, when I reboot, these changes are lost and I have to plug in an old keyboard so that I can re-run ltunify.Is there any way to make these changes permanent so that I don't have to keep switching my devices on and off each time I reboot?EDIT: After rebooting the machine and executing ltunify list, it shows that the devices ARE connected and paired, despite the fact that they are not working: Devices count: 2 Connected devices: idx=1 Mouse M510 idx=2 Keyboard K350Note also, that:In the BIOS, both the keyboard and mouse work out-of-the-boxIn the GRUB boot menu, the keyboard works (cannot test the mouse, as it's not a GUI)In the installer (CentOS 7) both the keyboard and mouse work out-of-the-boxCentOS 7 64-bit with kernel 3.10.0-123.20.1.el7.x86_64EDIT2: The system I'm using is an Intel NUC DN2820HKFY. | How can I make the pairing of the 'ltunify' program permanent? | keyboard;hardware;mouse | null |
_webmaster.21678 | We planning to launch a mobile WAP site to our exiting customer lead tracking website. Is it necessary to buy a WAP domain or can we create a subdomain for our existing domain like wap.example.com? | Can a WAP site go on a subdomain or does it need a new domain? | domains;subdomain;mobile | You can do whatever you want. You can:get a .mobi domain just for the mobile websiteuse a subdomain for the mobile content (I.e. m.domain.com)use media queries to display your site depending on the resolution of the device used to view itOn my new site I am developing I am using media queries. iIt's a small website so that easy to do. Facebook uses a subdomain. Use whatever works for you. |
_codereview.67722 | A couple of date-related questions have come up recently, and on both occasions I have been taken back to my 'early' days where one of my first forays in to programming involved implementing Zeller's Congruence.Zeller's congruence is a neat calculation because it involves a mathematical approach to date manipulation, and the math relies on both modular and integral arithmetic, combined with a smart way of visualizing time progression.$$\begin{align}h =&\ \left(q + \left\lfloor \frac{13(m + 1)}{5} \right\rfloor + K + \left\lfloor \frac{K}{4} \right\rfloor + 5J + \left\lfloor \frac{J}{4} \right\rfloor \right) \mod7\\where\\h =&\ \text{the day of the week (0 is Saturday ... 6 is Friday)}\\q =&\ \text{the day of the month}\\m =&\ \text{the month (3 = March, 4 = April, ..., 13 = January, 14 = February)}\\ &\ \text{If Jan or Feb, then you have to adjust the year back by 1 year}\\ &\ \text{Jan 2001 is month 13 of year 2000}\\K =&\ \text{the century count} \implies \left\lfloor\ \frac{\mathtt{adj.year}}{100}\right\rfloor\\J =&\ \text{the adjusted year in the century} \implies (\ \mathtt{adj.year} \mod 100)\\\end{align}$$The two recent questions that have inspired me to go back and re-implement Zeller's Congruence are:Function for checking leap yearsIs it Friday yet?As a secondary exercise, I tested the code using the new-in-Java8 time API.Zeller's CongruenceNote: The code contains comments which go some way to explaining how the congruence works// Used for a quick validation of days in a month.// Note filler at MONTHDAYS[0] because months are 1-based.private static final int[] MONTHDAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };private static final boolean isLeap(final int year) { return (year % 4) == 0 && (year % 100 != 0 || year % 400 == 0);}/** * Calculate the day of the week (1=Monday, 7=Sunday) for the supplied * (valid) date. * @param year The year to calculate (year 1 or more recent) * @param month The month (1 through 12 for January through December) * @param day The Day-in-month (1 through 28/29/30/31 depending on the month) * @return The day of the week (1 represents Monday, 7 represents Sunday). * @throws IllegalArgumentException if the input values are not a valid date */public static final int computeDayOfWeek(final int year, final int month, final int day) throws IllegalArgumentException { // easy checks for valid dates. if (year < 1 || month < 1 || month > 12 || day < 1 || day > MONTHDAYS[month]) { throw new IllegalArgumentException(String.format( %04d-%02d-%02d is not a valid date, year, month, day)); } // leap year validation if (day == 29 && month == 2 && !isLeap(year)) { throw new IllegalArgumentException( String.format( %04d-%02d-%02d is not a valid date (Feb 29 but not a leap year), year, month, day)); } // Forumla is here: https://en.wikipedia.org/wiki/Zeller%27s_congruence // Using the wikipedia's variable names: // h = (q + floor((13*(m+1)/5)) + K + floor(K/4) + floor(J/4) + 5J) // translate variable names in to algorithm components. // q is the day of month. final int q = day; // m is the month, but Jan and Feb need to be month 13 and 14 // respectively final int m = month + (month < 3 ? 12 : 0); // if the month is jan, or feb, then year is of the previous year. final int calcyear = year - (month < 3 ? 1 : 0); // K is the year-in-century final int K = calcyear % 100; // J is the century number final int J = calcyear / 100; /* Algorithm works by following a concept of adding days in to a sequence, and performing modular arithmetic. The fundamental concept is that if you know one specific date's day-of-week, then all you need to do is calculate how many days you are in front of, or behind that day. If you know the days, you can perform a %7 on that, and get the day difference. If you choose your algorithm to start on a specific day and call it 0, then the difference from the %7 is simply the day. As it happens, to make things work well, starting with Saturday as day 0 is right. */ // how many days (possibly %7) are we offset at this point in time? int offset = 0; /* Now, how to calculate the days between. Well, there are 36524 days in a century, unless the century is divisible by 4, in which case there is an extra day. so, the days between epoch and now is the number of centuries * days-in-century + number-of-4-centuries. But, because we only need extra days, we can do these things %7. So, since 36524%7 is 5, we need to add 5 days for each century since epoch. Additionally, we need to add another day for each of those special leap years that are divisible by 400 */ // 5 days per century plus the number of 400 years too. offset += J * 5 + J / 4; // now, inside a century, there's leap years.... // a normal year has 365 days, which is 52 weeks and 1 day. // so, each year since the start, is 1 more day of offset. And, each // leap year adds another... offset += K + K / 4; /* So, that gives us the right number of offset days to get us to the current year. Now, if we start our logical year on March 1st, we don't need to worry about the odd day at the end of february. Also, the number of days in a month, starting from March, is: Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec,Jan,Feb 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28/29 Notice how Aug and Jan are at positions 5 and 10? Also, a 30-day month adds 2 days of offset, and a 31-day month adds 3 days of offset. So, for each 30 day month we add 2 days, and for each 31 day month we add 3. This formula can be hard-coded as (13 * (m + 1))/5 */ offset += (13 * (m + 1)) / 5; // Now all we need to do is add the days in our current month, to get // the final offset: offset += q; // Then, the actual day of week is the zero-day + offset % 7 int h = offset % 7; // Now adjust the 0-6 based Saturday-Friday to a 1-7 based Monday-Sunday return ((h + 5) % 7) + 1;}Test CodeI used the Time API to test the code. Obviously, the time API's LocalDateTime class is able to give you the weekday for a given date. The above code is completely reinventing the wheel... I used that LocalDateTime to validate the results:/* * method for testing only. */private static final void check(LocalDateTime then, boolean print) { // do an us vs. them comparison int us = computeDayOfWeek( then.get(ChronoField.YEAR), then.get(ChronoField.MONTH_OF_YEAR), then.get(ChronoField.DAY_OF_MONTH)); int them = then.get(ChronoField.DAY_OF_WEEK); if (us != them || print) { System.out.printf(%14s %14s is %s%n, then.toString(), DayOfWeek.of(them), DayOfWeek.of(us)); } if (us != them) { throw new IllegalStateException(String.format( Unable to correlate our calculation %d to the system %d, us, them)); }}public static void main(String[] args) { LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS); LocalDateTime past = LocalDateTime.of(1, 1, 1, 0, 0); LocalDateTime then = past; // test every day since 1 Jan, 0001 through to today while (then.isBefore(now)) { check(then, false); then = then.plusDays(1); } check(now, true); then = LocalDateTime.of(2, 1, 1, 0, 0); // recheck, and print the first year's dates. while (then.isAfter(past)) { then = then.minusDays(1); check(then, true); } LocalDateTime future = now.plusYears(1); then = now; // check, and print the next year's dates. while (then.isBefore(future)) { check(then, true); then = then.plusDays(1); }} | It's Friday! - Zeller's Congruence Revisited | java;datetime;reinventing the wheel | final int q = day;final int m = month + (month < 3 ? 12 : 0);final int calcyear = year - (month < 3 ? 1 : 0);final int K = calcyear % 100;final int J = calcyear / 100;int offset = 0;offset += J * 5 + J / 4;offset += K + K / 4;offset += (13 * (m + 1)) / 5;offset += q;int h = offset % 7;return ((h + 5) % 7) + 1;That's the code without any comments. I'm going to try to optimize it, although you'll have to do your own performance testing.A couple things come to mind already:final int m = month + (month < 3 ? 12 : 0);final int calcyear = year - (month < 3 ? 1 : 0);Assign the month < 3 to isJanOrFeb instead.final boolean isJanOrFeb = month < 3;final int m = month + (isJanOrFeb ? 12 : 0);final int calcyear = year - (isJanOrFeb ? 1 : 0);Don't do unnecessary assignment...int offset = 0;offset += J * 5 + J / 4;It's a waste.int offset = J * 5 + J / 4;There's only 1 usage of m...offset += (13 * (m + 1)) / 5; And since it's final only one set toofinal int m = month + (month < 3 ? 12 : 0);So maybe combine the + 1?final int m = month + (isJanOrFeb ? 13 : 1);offset += (13 * m) / 5;This bit of code can be collapsed easily...int h = offset % 7;return ((h + 5) % 7) + 1;To thisint h = (offset + 5) % 7;return h + 1;But then again, one wonders why you don't declare h as final... or whether you need it at all.return ((offset + 5) % 7) + 1;All I did was remove the h line and replace h with offset.Final code:final int q = day;final boolean isJanOrFeb = month < 3;final int m = month + (isJanOrFeb ? 12 : 0) + 1;final int calcyear = year - (isJanOrFeb ? 1 : 0);final int K = calcyear % 100;final int J = calcyear / 100;int offset = q;offset += (13 * m) / 5;offset += K + (K / 4);offset += (J * 5) + (J / 4);return ((offset + 5) % 7) + 1;I moved the statements around so it looks more like the original function. |
_unix.207010 | I have this file1.txtdeiauk 9kespaul 8luktol 7 titkur 6and other file2.txtkespaul bdeiauk a And I want to merge both files in one by first value, so my result should bedeiauk 9 akespaul 8 bluktol 7 titkur 6 | Merge two files | shell script;text processing;join | sort file2.txt | join -a 1 file1.txt -join requires sorted input. The '-' specifies that standard input will be used for the second file, which allows the output of sort to be used as input. The '-a 1' specifies that non-matching lines from the first file will be included in the output. |
_opensource.2060 | I want to include two open-source libraries in my application: Ghostscript and iTextSharp. In 3 commercial applications that I will develop myself:Commercial software will use both above two opensource software.Commercial software will use only iTextSharp.Commercial software will use iTextSharp along with another commercial software library for which I have the rights to distribute with my application. I bought the distribution license of that commercial library for US $1 just for the sake of having a legal distribution license. The owner is willing to help me use his software library in my application and distribute.I am willing to open-source the parts of application that I wrote. I can forward the same license agreement in the distribution and can agree to specify the developer names etc in the software sold and willing do to anything needed to do except any payment for the opensource software libraries. Obviously I can't opensource that commercial library that I will use in the third software because I don't have its source code and I just have its distribution rights when I sell the third software which uses that commercial library.I want to make money from the application that I wrote but can not purchase the commercial license of Ghostscript and iTextSharp because:Their commercial license are very expensive.I am willing to open source the applications that I will write.I am not sure if I will make any money from the applications that I will develop, so I don't have the means to pay for a commercial license and can not pay as of now.So, please guide me if I can make all of the three software. If not, then can I make any one or two of the three? | How can I include two open-source libraries in my commercial applications? | commercial;agpl 3.0 | You can distribute what you develop under several licences, probably by stating that the user gets to choose.I'd advise against it, unless it is cleanly separate pieces that warrant different licenses. Please don't make life hard for downstream (it hurts yourself, in the end, if your software can't be used due to murky licensing issues, or some downstream picking one option and another the other, with the result that the branches can't be merged due to license mismatch), pick one of the standard licenses, and make sure you stay GPL compatible for software. |
_computerscience.3904 | To reduce noise of edge detection the norm seems like it is to apply a blur. However, is it generally better to apply the blur to the input of the edge detection. The input in my case being the depth and normal GBuffers in which I compare neighbouring pixels.Or is it better to blur the output of the edge detection, e.g. a greyscale image of edge strength, before I use that to apply some edge to a colour buffer? | Is it better to blur the input or output of an edge detection shader for noise reduction? | image processing;blur;edge detection | Standard blur removes high frequency content from the signal, whereas edge detection usually look into high frequency to detect edges. Be careful on how much blurring to apply to ensure that you don't lose desirable edges. The goal of blurring is to perform noise reduction, so the best would be to come up with a model of the noise present in your images and what your desired edges looks like (their frequency, orientation, what caused them: shading on a smooth object, shadows, etc.) and tailor your blur filter to remove the noise but not the edges.Seems like you want to implement an edge detector into a shader. Be sure to check what are the sources of noise in your image. For example, if you are displaying pure lambertian surfaces, chances are that there is virtually no noise in your data, so you don't need to apply a smoothing filter before detecting edges.Also, instead of using a standard gaussian blur, you could look into edge-preserving filters like the bilateral filter. It is much slower, but is good to remove noise without altering too much the edges.If you are performing filtering and edge detection through convolutions (the standard way of doing it), it doesn't matter if you do one before another, as convolutions are commutative, meaning $a*b = b*a$, where $*$ is the convolution operator, $a$ being the edge detector and $b$ the smoothing kernel.On non-associative operations (like the bilateral filter), you must ask yourself the question what is the goal of this operation? Basically, blurring before the edge detection will diminish the image noise while blurring after will give you blurred edges (potentially caused by noise) instead of sharp edges. The same edges will be found, though, but the blurred one will be less precise. It depends on what you want to achieve: it could be interesting for art, but it just removes interesting information for signal analysis.Not sure what applying an edge to a color buffer means; is the goal to perform edge enhancement? |
_softwareengineering.238535 | Recently I wrote an interpreter for operations on sparse matrices (a sparse matrix calculator) in lex/yacc. The language is still very bare bones and doesn't even include control structures or parameterized subroutines, yet it is already at several thousand lines of code, and that's not including the matrix classes. In particular, the yacc file is close to two thousand lines in length. Because of this I'm finding it quite difficult to work on. Is this normal or is there a way I can simplify things?If you want to review my code, it can be found at:http://sourceforge.net/projects/msci/files/libpetey/ | How do I simplify a compiler/interpreter? | compiler;dsl | null |
_unix.191601 | While following the systemd guide I ran into an issue with this example configuration:[Unit]Description=MyAppAfter=docker.serviceRequires=docker.service[Service]TimeoutStartSec=0ExecStartPre=-/usr/bin/docker kill busybox1ExecStartPre=-/usr/bin/docker rm busybox1ExecStartPre=/usr/bin/docker pull busyboxExecStart=/usr/bin/docker run --name busybox1 busybox /bin/sh -c while true; do echo Hello World; sleep 1; done[Install]WantedBy=multi-user.targetIf I run systemctl start hello while the system is running the docker will boot, but if I enable hello.service to boot on start through systemd and reboot the machine I receive this error:-- Reboot --Mar 15 01:17:44 general systemd[1]: Starting MyApp...Mar 15 01:17:47 general docker[510]: Error response from daemon: No such container: busybox1Mar 15 01:17:47 general docker[510]: time=2015-03-15T01:17:47Z level=fatal msg=Error: failed to kill one or more containersMar 15 01:17:47 general docker[637]: Error response from daemon: No such container: busybox1Mar 15 01:17:47 general docker[637]: time=2015-03-15T01:17:47Z level=fatal msg=Error: failed to remove one or more containersMar 15 01:17:47 general systemd[1]: hello.service: control process exited, code=exited status=1Mar 15 01:17:47 general systemd[1]: Failed to start MyApp.Mar 15 01:17:47 general systemd[1]: Unit hello.service entered failed state.Mar 15 01:17:47 general systemd[1]: hello.service failed.Mar 15 01:17:47 general docker[673]: Pulling repository busyboxMar 15 01:17:47 general docker[673]: time=2015-03-15T01:17:47Z level=fatal msg=Get https://index.docker.io/v1/repositories/library/busybox/images: dial tcp: lookup index.docker.io: connection refusedAny clue what I'm doing wrong? | CoreOS can't pull docker container on boot | docker;systemd;coreos | null |
_codereview.74774 | Please review my pointer class.template<typename T>class Ptr {public: Ptr(T* t, int s = 1) { sz = s; p = new T[sz]; for (int i = 0; i < sz; ++i) { p[i] = t[i]; } } Ptr(const Ptr&) = delete; Ptr& operator=(const Ptr&) = delete; Ptr(Ptr &&t) :p{t.p}, sz{t.sz} { t.p = nullptr; t.sz = 0; } Ptr& operator=(Ptr &&t) { std::swap(t.p,p); std::swap(t.sz,sz); return *this; } T& operator*() { check_range(); return *p; } T& operator[](int i) { check_range(i); return p[i]; } Ptr& operator+=(int i) { check_range(index+i); index += i; p+= i; return *this; } Ptr& operator-=(int i) { check_range(index-i); index -= i; p -= i; return *this; } Ptr& operator+(int i) { Ptr old{*this}; return old+=1; } Ptr& operator-(int i) { Ptr old{*this}; return old-=1; } Ptr& operator++() { return operator+=(1); } Ptr operator++(int) { Ptr<T> old{p}; operator++(); return old; } Ptr& operator--() { return operator-=(1); } Ptr operator--(int) { Ptr<T> old{p}; operator--(); return old; } ~Ptr() { while (index < sz-1) { operator++(); } while (index != 0) { delete p; operator--(); } delete p; }private: T* p; int sz; int index = 0; void check_range(int i) { if (i < 0 || i > sz-1) { throw std::out_of_range(out of range); } } void check_range() { if (p == nullptr) { throw std::out_of_range(null pointer); } }}; | Pointer class/handle | c++;c++11;reinventing the wheel;pointers | Only need to point out one thing.Constructor: p = new T[sz];Destructor: delete p;This code is broken. If you allocation with new [] you MUST destroy with delete [].In the operator+= and operator-=Ptr& operator+=(int i) { check_range(index+i); index += i; p+= i; return *this;}Ptr& operator-=(int i) { check_range(index-i); index -= i; p -= i; return *this;}Thus moving p during the lifetime of the object is not a good idea (because you must call delete on the pointer returned by new). So if you are going to move p you need to keep track of the original pointer in another member. But I would not move it all. You are adjusting index so why adjust p?These can't return by reference:Ptr& operator+(int i) { Ptr old{*this}; return old+=1;}Ptr& operator-(int i) { Ptr old{*this}; return old-=1;}You have to return by value because you are creating new values.I am surprised that this works: Ptr old{*this};Because you have deleted the copy constructor.Ptr(const Ptr&) = delete;If it compiles I am not sure what is happening. But it is definitely not good.In the constructor you should prefer initializer list.Ptr(T* t, int s = 1) { sz = s; // Initializer list p = new T[sz]; // Initializer list. // This seems inefficient. // Since the line above has just called the constructor on each element // element in the array. You are now calling the assignment operator // on each element in the array. for (int i = 0; i < sz; ++i) { p[i] = t[i]; }}You can optimize the abovePtr(T* t, int s = 1) : sz(s) , p(reinterpret_cast<T*>(new char[s * sizeof(T)]) // Allocate aligned but uninitialized memory.{ for (int i = 0; i < sz; ++i) { new (p + i) T(t[i]); // Its called placement new. // The `(p + i)` is the address where you want the // construction to take place (ie don't allocate) // Then we use the copy constructor to create the // copy }} |
_unix.13868 | I'm running the following command:rdiff-backup --remote-schema '%s' 'sudo /usr/bin/rdiff-backup --server \ --restrict-read-only /'::/etc /var/backups/hosts/derpIt's backing up /etc from localhost and putting it in /var/backups/hosts/derp just fine. I can scarcely imagine it working better, but I have no idea how to get this to run and pull the files from another host. Maybe I'm just being silly and assuming that the remote part in --remote-schema actually means remote. | Need a little help with --remote-schema option for rdiff-backup | backup;rdiff backup | null |
_unix.121101 | I have a bash script with a variable called VAR_AI also have a local env variable called VAR_AThe bash script calls the command:echo ${VAR_A}I am not able to change the variable in the script to another name, but I can change how the script calls the echo command. How can I modify the echo command to ensure it's printing the local env variable instead of the one provided in the script?UPDATE FOR CLARITY:The situation:User has an existing .bashrc file which on login, sets:VAR_A=someValueexport VAR_AThis allows the user to:~]$ echo ${VAR_A} someValueI have a configuration file for some bash scriptsVAR_A=someOtherValueI have a bash script:#!/bin/bash. ../configuration # imports config file with some values# do stuffecho ${VAR_A}Executing the script from the terminal (bash shell as logged in user) prints:~]$ ./run_script.sh someOtherStuffI need it to print:~]$ ./run_script.sh someStuffI hope that helps clear things up. | bash script and local env variable namespace collision | bash;environment variables | Shell variables are initialised from environment variables in every shell, you can't get around that.When the shell starts, for every environment variable it receives that has a valid name as a shell variable, the shell assigns the corresponding shell variable the corresponding value. For instance, if your script is started as:env VAR_A=xxx your-script(and has a #!/bin/bash - she-bang), env will execute /bin/bash and pass VAR_A=xxx to that bash command, and bash will assign its $VAR_A variable the value xxx.In the Bourne shell and in the C-shell, if you assign a new value to that shell variable, it doesn't affect the corresponding env variable passed to later commands executed by that shell, you have to use export or setenv for that (note however that in the Bourne shell if you unset a variable, it removes both the shell variable and environment variable).In:env VAR=xxx sh -c 'VAR=yyy; other-command'(with sh being the Bourne shell, not modern POSIX shells) Or:env VAR=xxx csh -c 'set VAR = yyy; other-command'other-command receives VAR=xxx in its environment, not VAR=yyy, you'd need to write it:env VAR=xxx sh -c 'VAR=yyy; export VAR; other-command'orenv VAR=yyy csh -c 'setenv VAR yyy; other-command'For other-command to receive VAR=yyy in its environment.However, ksh (and POSIX as a result, and then bash and all other modern Bourne-like shells as a result) broke that.Upon start-up those modern shells bind their shell variable to the corresponding environment variable.What that means is that a script may clobber the environment just by setting one of its variables even if it doesn't export it. Some shells are even known to remove the environment variables it cannot map to shell variables (which is why it's recommended to only use shell-mappable variable names for environment variable names).That's a main reason why by convention, all uppercase variables should be reserved for environment variables.To work around that, if you want the commands executed by your script to receive the same environment as the shell interpreting your script received, you'd need to store that environment somehow. You can do it by adding:my_saved_env=$(export -p)at the start of your script, and then run your commands with:(eval $my_saved_env; exec my-other-command and its args) |
_cs.70648 | I'm looking at symmetric trees and checking if two trees are mirrors of each other. That part is straightforward enough, but what I'm having trouble with is: say your computer isn't powerful enough to handle these two trees on its own. How can you make this scalable and run on multiple machines? | What options are there to make the mirror tree problem scalable? | algorithms;binary trees;parallel computing | null |
_unix.276253 | Will grep [0-9] work in the same way as grep [:digit:]? | In grep command, can I change [:digit:] to [0-9]? | grep | null |
_unix.228275 | i have a server in internal network and i want to access it from external. the network is like this:Server A (132.196.28.229) is in external network Server B (10.35.202.24) can access both networkServer C (192.168.10.99) is in internal networkSo, i configure iptables on Server B to forward all traffic from Server A to Server Ciptables -t nat -A PREROUTING -d 10.35.202.24 -j DNAT --to-destination 192.168.10.99Then i test it with ping and it works. Tcpdump on Server B, you can see the ping from Server A and target is 10.35.202.24:15:34:36.366034 IP 132.196.28.229 > 10.35.202.24: ICMP echo request, id 24510, seq 1, length 6415:34:37.366321 IP 132.196.28.229 > 10.35.202.24: ICMP echo request, id 24510, seq 2, length 6415:34:38.374983 IP 132.196.28.229 > 10.35.202.24: ICMP echo request, id 24510, seq 3, length 6415:34:39.374849 IP 132.196.28.229 > 10.35.202.24: ICMP echo request, id 24510, seq 4, lengthand Tcpdump on Server C. now the target adress is changed to 192.168.10.99:15:34:35.741802 IP 132.196.28.229 > 192.168.10.99: ICMP echo request, id 24510, seq 1, length 6415:34:36.742018 IP 132.196.28.229 > 192.168.10.99: ICMP echo request, id 24510, seq 2, length 6415:34:37.750633 IP 132.196.28.229 > 192.168.10.99: ICMP echo request, id 24510, seq 3, length 6415:34:38.750499 IP 132.196.28.229 > 192.168.10.99: ICMP echo request, id 24510, seq 4, length 64but, same forwarding not work for SCTP message. Here is the INIT message i triggered from Server A:15:39:18.787145 IP 132.196.28.229.32763 > 10.35.202.24.36412: sctp (1) [INIT] [init tag: 495530240] [rwnd: 62464] [OS: 64] [MIS: 64] [init TSN: 322647100] 15:39:18.787189 IP 10.35.202.24 > 132.196.28.229: ICMP 10.35.202.24 protocol 132 unreachable, length 7615:39:21.786640 IP 132.196.28.229.32763 > 10.35.202.24.36412: sctp (1) [INIT] [init tag: 495530240] [rwnd: 62464] [OS: 64] [MIS: 64] [init TSN: 322647100] 15:39:21.786687 IP 10.35.202.24 > 132.196.28.229: ICMP 10.35.202.24 protocol 132 unreachable, length 76And i can't capture anything on Server C for sctp. Looks like that the NAT for sctp not work, and due to server B don't have any sctp service on. so the server B reply as unreachable. I have tested ssh as well. The forwarding works well. so it looks only not working for SCTP!!??Any suggestion why this happen? is any special configure for sctp i missed? | iptables nat not work for sctp | linux;iptables | null |
_unix.344465 | Not a severe issue because it can be fixed with a reboot, but I'm curious to know whether there's a way to restore files (probably not all, but as many as possible) in /proc, /sys, /dev/pts and /dev.I deleted them partially when removing a chroot directory with those directories mounted withmount -t proc proc [path/to/chroot]/procmount -t sysfs sys [path/to/chroot]/sysmount --bind /dev/[path/to/chroot]/devmount -t devpts /dev/path [path/to/chroot]/dev/ptson Ubuntu 16.10 amd64. The removal failed for some files (I didn't record the error message) because removal of files was refused which I can understand. I guess that solutions will apply to all Debian-based systems.After quitting the chroot I'm seeing things like$ ls -bash: /dev/null: Keine Berechtigungbash: _upvars: `-a2': invalid number specifier-bash: /dev/null: Keine Berechtigungbash: _upvars: `-a0': invalid number specifierduring autocompletion with Tab on ls (after exporting LANGUAGE=en). | Recover from rm -rf /proc /sys/ /dev/pts /dev without reboot? | linux;mount;devices;proc;sysfs | null |
_unix.19949 | I have recently moved to a university where all computers get a public IPv4 address. Since the teredo tunnel I was using doesn't work anymore and I have a public address, I am wanting to use Hurricane Electric's tunnel broker service on my Fedora 15 Gnome machine.I've already configured HE with my information and am just trying to get it working in Fedora. I'm using a modified configuration script from the Fedora Wiki (which didn't work without modifications).My /etc/sysconfig/network config:NETWORKING=yesHOSTNAME=quackpad-fedoraNTPSERVERARGS=iburstNETWORKING_IPV6=yesIPV6INIT=yesIPV6_DEFAULTDEV=he-ipv6IPV6_DEFAULTGW=2001:470:1f10:11d0::1/64 # Server IPv6 AddressAnd my /etc/sysconfig/network-scripts/ifcfg-he-ipv6DEVICE=he-ipv6BOOTPROTO=noneONBOOT=yes IPV6INIT=yesIPV6TUNNELIPV4=209.51.181.2 # Server IPv4 addressIPV6TUNNELIPV4LOCAL=***.***.*.*** # My IPv4 addressIPV6ADDR=2001:470:1f10:11d0::2/64 # Client IPv6 addressIf I do sudo ifup he-ipv6 I get (why does ifup-eth care about that?) ERROR : [/etc/sysconfig/network-scripts/ifup-eth] Device he-ipv6 does not seem to be present, delaying initialization.If I do sudo service network restartSep 1 18:15:07 quackpad-fedora NetworkManager[938]: <warn> connection /org/freedesktop/NetworkManager/Settings/1 failed to activate: (2) Device not managed by NetworkManager or unavailableSep 1 18:15:07 quackpad-fedora NetworkManager[938]: <warn> connection /org/freedesktop/NetworkManager/Settings/2 failed to activate: (2) Device not managed by NetworkManager or unavailableSep 1 18:15:08 quackpad-fedora /etc/sysconfig/network-scripts/ifup-eth: Device he-ipv6 does not seem to be present, delaying initialization.Sep 1 18:15:08 quackpad-fedora NetworkManager[938]: <warn> connection /org/freedesktop/NetworkManager/Settings/0 failed to activate: (2) Device not managed by NetworkManager or unavailableSep 1 18:15:08 quackpad-fedora systemd[1]: network.service: control process exited, code=exited status=1Sep 1 18:15:08 quackpad-fedora systemd[1]: Unit network.service entered failed state.What am I doing wrong here? Why do these keep failing? | Can't get Hurricane Electric IPv6 tunnel to work on Fedora | fedora;ipv6 | null |
_softwareengineering.283386 | I want to become more efficient and I want to use ops tools efficiently.With this in mind, I wanted to learn more about continuous integration, but it seems that there is many different things concerning it.I m actually working with Jetbrains suits in my work (IntelliJ, WebStorm...), so I wanted to continue using them, and I wanted to use TeamCity which seemed to be a great tool with many plugins for continuous integration.My problem is that I don't know what are the differences between:building automation (TeamCity is this kind of software): I know that we can build our application with a remote VCS repository and it's great, but what is the main aim of that ? What kind of information is important while doing this ? In fact, I already know if my software builds or not locally, and my teammates too. So, what is the aim of using it without deploying automation?deploying automation (TeamCity doesn't seem to do it easily)continuous integration (which seems to be a conjunction of the two above)continuous delivery (what is this exactly? why it's different from continuous integration?)Can you help me to understand a bit more this? | Build automation vs deploy automation vs continuous integration | continuous integration;continuous delivery | Wikipedia gives pretty good summaries of most of these terms. Here is my take on them:Build automation is automating how the software is built instead of manually invoking the compiler. This would be accomplished via tools such as e.g. Make or Ant.Deployment automation is taking your built software and deploying or installing it on a test or production system.Continuous integration means having an automated process build your software continuously as developers check in code, and run unit tests to ensure the code still works. For example, every 15 to 30 minutes a server might wake up, scan VCS for new check-ins, then update and build the project if any changes were made. In addition to performing compile steps, this is also a great opportunity to run automated unit tests and code quality checks.Continuous delivery is a combination of all of the previous concepts where the software builds are also deployed to a test system, optionally with tests performed and reports generated.At the very least, you need to have build automation, i.e. a build script of some sort. That allows you to click one button or issue one command to build your project. The benefit to this is reducing errors from manually running steps. Complex build environments might involve generating code (think DAOs from configs, interface code such as JAXB), compiling code, packaging it up, customizing metadata, etc. With a lot of stuff to do you need a checklist: why not make the checklist be your build script, and use a tool to run it? It reduces errors and provides consistency.Next up is CI: this is really good to have but not strictly required. It helps identify build problems early. If you have multiple developers checking in code throughout the day and perhaps not syncing up their own workspaces constantly, there is a risk that their changes will interfere with each other. I am referring specifically to static code errors, not version control conflicts. A CI build server will mitigate this risk.Finally we have the deployment steps. The idea here is to save time and reduce error from manually deploying software. Much like build automation, there are a hundred ways to screw up a software deployment. I have personally stayed late at the office to fix manual deployment problems on many occasions when we need a functioning system for customers coming on-site tomorrow. Automating multiple systems introduces more risk: instead of one system possibly crashing or having weird errors, we now have multiple systems that can go wrong. However, that risk is far lower than somebody missing a step on a checklist or issuing the wrong command and messing up a deployment. If you are lucky you can simply restore a DB backup and start over, if you are unlucky an error might cause the system to function incorrectly. Is it a software defect? Did the technician not set a configuration correctly? This takes time to diagnose, time that you may not have and time that need not be spent if you automate the process. |
_softwareengineering.252063 | Questions in bold:I've read the Apache Software License 2.0... What I gather is that all a person needs to do when redistributing the licensed software is include their name in all the parts they've modified(if any), include some notices and whatnot, and you're away. You don't even need to follow along with the license in all your additions/edits, because you can sub-license.The thing I don't really get is, why would anyone want to use this kind of license, honestly? Am I missing something?One more thing, does #include-ing(or similar) a licensed library mean that you are making a derivative of the licensed source, therefore binding you to the terms and conditions of the license? | Copying and Selling Apache Licensed Software? | licensing;gpl;apache license | null |
_unix.298695 | I am at a complete loss here. I have this working on 398/400 servers. The remaining two are RedHat 6.3 machines.I have setup user accounts, ssh keys and .ssh directories. 700 on .ssh 600 on authorized_keysWhen logging in from BitVise I capture the following error:LocalSshDisconn, code: ConnectionLost, message: FlowSshTransport: received EOF.When logging in from a terminal I see :debug3: sign_and_send_pubkey: RSA 22:ed:e8:ce:f3:e0:e0:68:a7:33:e9:db:ac:7d:5f:e6:a9:93:93:b7debug2: we sent a publickey packet, wait for replydebug3: Wrote 656 bytes for a total of 1949Connection closed by 10.200.10.121 I have no idea where to go from here? I've been doing this for 15 years and have never seen an issue like this.Thanks! | SSH Login with key Error | rhel;openssh | null |
_unix.22157 | Is there a way to pass in a variable as an argument to a bash script and have it evaluated scoped by the bash script?Given:# cat /path/to/file/of/host/namesbobtomjoeetc...# doforFILE=$1shiftCMD=$*while read host; do # recursively turns ssh \$host hostname from $@ into: # ssh bob hostname # ssh tom hostname # ssh joe hostname # etc... eval $CMDdone < $FILEWhen:# dofor /path/to/file/of/host/names ssh \$host hostnameThen: I'd receive the output from running ssh host hostname for each hostname listed in /path/to/file/of/host/names. e.g.:bob.example.comtom.example.comjoe.example.cometc... | Evalute passed in variable in bash | bash;shell;shell script;scripting | You can use#!/bin/bashFILE=$1exec 3<$FILEwhile read -u 3 host; do $2 $host $3doneThen if you have:$ cat /tmp/hostnamessome.host1.comanother.host2.netsome.host3.org some.host4.comand run dofor.sh /tmp/hostnames ssh ls, it will run in sequence:ssh some.host1.com lsssh another.host2.net lsssh some.host3.org lsssh some.host4.com lsEDIT1:If you'd like to change ssh or ls into some longer commands (or parts of such), just use quotes:dofor.sh /tmp/hostnames ssh -p 23 ls -lh /EDIT2:With the following script, you'll be able to use $host variable in as many places in your command as you want:#!/bin/bashexec 3<$1while read -u 3 host; do eval $2done(I made this one shorter - no useless introducing of $FILE variable.)The important part here is that you need to use single quotes around the command containing the $host variable: dofor.sh /tmp/hostnames 'echo trying $host :; ssh -p 23 myuser@$host ls -lh /'But beware that it is dangerous to use eval (see l0b0's wall) because if the file /tmp/hostnames contained a command on some line, it would be executed. Better not use this as root! |
_codereview.117303 | I have been writing some code to add to our company's Bill of Materials template Excel file. Every project that we do has its own unique Bill of Materials. I am attempting to make it more dynamic and to add some functionality that it didn't previously have. I have created an add-in BOM MACROS.xlam that each user will add, and stored it on the company network so that I can modify the code and push it out to every file at once. As such, each file will contain the following code within the main worksheet:'Require all variables to be defined within the sub.Option ExplicitPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)Application.Run 'BOM MACROS.xlam'! & WorksheetSelectionChange, ActiveWorkbook, ActiveSheet, TargetEnd SubThe add-in then contains the following code:'Require all variables to be defined within the sub.Option ExplicitSub WorksheetSelectionChange(wb As Workbook, ws As Worksheet, ByVal Target As Range)'This sub will run whenever the selection is changed on this sheet. It will'check if any of the required headings have been deleted and prompt the user to'add the heading back if it has. It will also check if the selection is in the'DOC or PO ATTACHMENTS columns and proceed accordingly.Dim ErrorNo As LongDim HeaderRow As LongDim POAttachmentsColumn As LongDim POFilesColumn As LongDim CodeColumn As LongDim QTYColumn As LongDim DescriptionColumn As LongDim CostColumn As LongDim LastRow As LongDim YNAnswer As IntegerDim DOCColumn As LongDim Option1Row As LongDim AdderDeductColumn As LongDim OptionTotalRow As LongDim Option1RowCount As LongDim i As Long'Disable screen updating if it is currently enabled.If Not (Application.ScreenUpdating = False) Then Application.ScreenUpdating = False'Go to Error_Handling on an error. Check if any of the required headings have been'deleted. If so, the Find function will throw an error and go to Error_Handling.'Renumber the ErrorNo variable before each Find so it reflects which heading was deleted.On Error GoTo Error_HandlingErrorNo = 1HeaderRow = ws.Columns(1).Find(What:=ITEM, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).RowErrorNo = 2LastRow = ws.Columns(1).Find(What:=LAST ROW, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext).RowIf Target.Columns.Count = 1 And Target.Rows.Count = 1 And Target.Row < LastRow Then ErrorNo = 3 POAttachmentsColumn = ws.Rows(HeaderRow).Find(What:=ATTACHMENTS, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column ErrorNo = 4 POFilesColumn = ws.Rows(HeaderRow).Find(What:=PO FILES, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column ErrorNo = 5 DOCColumn = ws.Rows(HeaderRow).Find(What:=DOC, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column ErrorNo = 6 CodeColumn = ws.Rows(HeaderRow).Find(What:=CODE, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column ErrorNo = 7 QTYColumn = ws.Rows(HeaderRow).Find(What:=QTY, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column ErrorNo = 8 DescriptionColumn = ws.Rows(HeaderRow).Find(What:=DESCRIPTION, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column ErrorNo = 9 CostColumn = ws.Rows(HeaderRow).Find(What:=COST, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column ErrorNo = 0 If Target.Column = POAttachmentsColumn And Target.Row > HeaderRow And Target.Value <> Then 'If the selection is in the POAttachmentsColumn, and it is between the HeaderRow and 'the LastRow, and only one cell is selected, and the selected cell is not empty, ask 'the user if they would like to manage the attachments for this item. If so, show the 'AddLinkForm userform. YNAnswer = MsgBox(Would you like to manage the attachments to be added to the PO for this component?, vbYesNo) If YNAnswer = vbYes Then AddLinkForm.Show End If ElseIf Target.Column = DOCColumn And Target.Row > HeaderRow And Target.Value = + Then 'If the selection is in the DOCCOlumn, and it is between the HeaderRow and the 'LastRow, and only one cell is selected, and the cell value is +, then run 'the InsertDocumentationRow sub. InsertDocumentationRow Target.Row, LastRow End IfElseIf Target.Columns.Count = 1 And Target.Rows.Count = 1 And Target.Row >= LastRow Then If Target.Column = 1 And Target.Value = + ADD OPTION Then YNAnswer = MsgBox(Would you like to add another option?, vbYesNo) If YNAnswer = vbYes Then With ws ErrorNo = 10 Option1Row = .Columns(1).Find(What:=OPTION 1, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext).Row ErrorNo = 11 AdderDeductColumn = .Rows(Option1Row + 1).Find(What:=ADDER/DEDUCT, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column ErrorNo = 12 OptionTotalRow = .Range(.Cells(Option1Row + 1, AdderDeductColumn), .Cells(Option1Row + 100, AdderDeductColumn)).Find(What:=TOTAL:, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext).Row ErrorNo = 0 Option1RowCount = OptionTotalRow - Option1Row + 1 LastRow = .Cells(.Rows.Count, AdderDeductColumn).End(xlUp).Row .Rows(Option1Row & : & OptionTotalRow + 1).Copy .Rows(LastRow + 2).Insert Shift:=xlDown Application.CutCopyMode = False .Cells(LastRow + 2, 1).Value = OPTION & Right(.Cells(Target.Row, 4), Len(.Cells(Target.Row, 4)) - 14) & - DESCRIPTION .Cells(LastRow + 2, 1).Characters(Start:=12, Length:=11).Font.Color = -16776961 If OptionTotalRow - Option1Row > 3 Then For i = LastRow + 1 + Option1RowCount To LastRow + 5 Step -1 .Rows(i).Delete Next i End If End With End If ElseIf Target.Column = DOCColumn And Target.Row > LastRow And Target.Value = + ADD ITEM Then YNAnswer = MsgBox(Would you like to add an item to this option?, vbYesNo) If YNAnswer = vbYes Then ws.Rows(Target.Row).Copy ws.Rows(Target.Row + 1).Insert Shift:=xlDown Application.CutCopyMode = False End If End IfEnd IfError_Handling:'If the Find function fails, check the ErrorNo variable and proceed accordingly. If Err.Number = 91 And ErrorNo = 1 Then MsgBox The ITEM header has been deleted. Please put this header back before continuing. ElseIf Err.Number = 91 And ErrorNo = 2 Then MsgBox The last row designator has been deleted. Please put LAST ROW back in the row under the last BOM item. ElseIf Err.Number = 91 And ErrorNo = 3 Then MsgBox The ATTACHMENTS header has been deleted. Please put this header back before continuing. ElseIf Err.Number = 91 And ErrorNo = 4 Then MsgBox The PO FILES header has been deleted. Please put this header back before continuing. ElseIf Err.Number = 91 And ErrorNo = 5 Then MsgBox The DOC header has been deleted. Please put this header back before continuing. ElseIf Err.Number = 91 And ErrorNo = 6 Then MsgBox The CODE header has been deleted. Please put this header back before continuing. ElseIf Err.Number = 91 And ErrorNo = 7 Then MsgBox The QTY header has been deleted. Please put this header back before continuing. ElseIf Err.Number = 91 And ErrorNo = 8 Then MsgBox The DESCRIPTION header has been deleted. Please put this header back before continuing. ElseIf Err.Number = 91 And ErrorNo = 9 Then MsgBox The COST header has been deleted. Please put this header back before continuing. ElseIf Err.Number = 91 And ErrorNo = 10 Then MsgBox The OPTION 1 header has been deleted at the bottom of the sheet. Please put this header back before continuing. ElseIf Err.Number = 91 And ErrorNo = 11 Then MsgBox The ADDER/DEDUCT header for OPTION 1 has been deleted at the bottom of the sheet. Please put this header back before continuing. ElseIf Err.Number = 91 And ErrorNo = 12 Then MsgBox The TOTAL: cell for OPTION 1 has been deleted at the bottom of the sheet. Please put this header back before continuing. ElseIf Err > 0 Then 'If the error is something else, run the error handler. ErrorHandler End If 'If screen updating is disabled, enable it. If Not (Application.ScreenUpdating = True) Then Application.ScreenUpdating = TrueEnd SubThe main function of this code is to check whether certain headings have been deleted. Since the Excel file will be used for many different project types by many different users, I need to make the code as dynamic as possible. As such, I do not have a good way to avoid using the Find function to locate headers for the code. Therefore, if certain headers are deleted, I need to notify the user to add them back.This code also allows the user to add options at the bottom of the sheet. Each option consists of a few rows with certain headers and formulas that I need to keep consistent for every row in the option, so I want the user to use the code to add lines to the option or to add new options. I also want to avoid using buttons on the sheet. I am considering moving this section of the code to a button on the custom add-in ribbon for this add-in to simplify this section of code.This code works fine, but I have a feeling that there is a better way to structure the code that captures the Find errors. Any feedback would be appreciated. | Structure for Multiple Potential Find Errors | vba;excel | Just some things that jump out at me:Integer is outdated. It only exists for backwards-compatibility reasons. The compiler will silently convert them into Long anyway, so just use Long. YNAnswer should be a Boolean If not A then A. Why not just A?Application.ScreenUpdating = False This:If Err.Number = 91 And ErrorNo = 1 Then MsgBox The ITEM header has been deleted. Please put this header back before continuing.ElseIf Err.Number = 91 And ErrorNo = 2 Then MsgBox The last row designator has been deleted. Please put LAST ROW back in the row under the last BOM item.ElseIf Err.Number = 91 And ErrorNo = 3 Then MsgBox The ATTACHMENTS header has been deleted. Please put this header back before continuing.ElseIf Err.Number = 91 And ErrorNo = 4 Then MsgBox The PO FILES header has been deleted. Please put this header back before continuing.ElseIf Err.Number = 91 And ErrorNo = 5 Then MsgBox The DOC header has been deleted. Please put this header back before continuing.ElseIf Err.Number = 91 And ErrorNo = 6 Then MsgBox The CODE header has been deleted. Please put this header back before continuing.ElseIf Err.Number = 91 And ErrorNo = 7 Then MsgBox The QTY header has been deleted. Please put this header back before continuing.ElseIf Err.Number = 91 And ErrorNo = 8 Then MsgBox The DESCRIPTION header has been deleted. Please put this header back before continuing.ElseIf Err.Number = 91 And ErrorNo = 9 Then MsgBox The COST header has been deleted. Please put this header back before continuing.ElseIf Err.Number = 91 And ErrorNo = 10 Then MsgBox The OPTION 1 header has been deleted at the bottom of the sheet. Please put this header back before continuing.ElseIf Err.Number = 91 And ErrorNo = 11 Then MsgBox The ADDER/DEDUCT header for OPTION 1 has been deleted at the bottom of the sheet. Please put this header back before continuing.ElseIf Err.Number = 91 And ErrorNo = 12 Then MsgBox The TOTAL: cell for OPTION 1 has been deleted at the bottom of the sheet. Please put this header back before continuing.ElseIf Err > 0 Then'If the error is something else, run the error handler. ErrorHandlerEnd IfShould be a Select Case statement:If Err.Number = 91 Select Case ErrorNo Case is = 1 ... Case is = 2 ... Case is = 3 ... Case Else ... End SelectEnd IfRepeated strings (or any hardcoded value) should be put in variables:Dim headerDeletedText as StringheaderDeletedText = header has been deleted. Please put this header back before continuing....ElseIf Err.Number = 91 And ErrorNo = 3 ThenMsgBox The ATTACHMENTS & headerDeletedText |
_webmaster.14245 | I need to implement a CAPTCHA for a Chinese (Simplified) website. Does anyone know how CAPTCHAs are normally presented on Chinese sites? I have seen some which just display standard decimal numbers but since there's less variation these are not as secure as I'd like. Is it acceptable to use a CAPTCHA containing letters from the standard English alphabet? | Chinese CAPTCHAs | internationalization;captcha | null |
_softwareengineering.350956 | I'm familiar with the concept of technical debt as the cost of effort (through maintenance, support, rework etc.) incurred when choosing an expedient solution over a complete one.What I am wondering about is, is technical debt incurred for any choice you make?Take for example securing an existing application that never had any security previously. Imagine that initially the requirement is simple enough - there are admins and non-admins. Admins can access the admin area and non-admins cannot. At this point the team has a choice, implement a simple security model e.g. a field indicating whether a user is an admin or not and restricting application access on this field or implement a complete security model e.g. roles, permissions and groups and associated application hooks.The costs attached to the implementations are:the simple model. quick to implement (5d), but the cost of addingand managing additional roles e.g. supervisor, manager etc. andapplying them throughout the application is expensive (5d per role)the complete model. longer to implement (20d), but the cost ofadding additional roles should be minimal and the cost of applyingthem throughout the application is lower than the simple option (1dper role)I get that by choosing the simple model I am saving 15d on the implementation time but incurring a technical debt of 4d for any additional roles.If I chose the complete model I'd incur an additional 15d of implementation cost, but am I incurring any technical debt? | Does every choice incur technical debt? | technical debt | Technical debt means you are in debt. If you complete your task (for example Admins/Users) and it works and is secure and easy to maintain, then there is no technical debt. Not being able to foresee potential future developments, new features or changes are not what is meant with technical debt. Always compare to the solution, needed to fulfill the current requirements.To use the famous car analogy, technical debt is when your brakes leak and you don't have money to fix it. If you own a perfectly good Volkswagen (not Diesel...), then not owning a Ferrari yet is not technical debt. |
_softwareengineering.204773 | JVM supports so many languages other than Java like Groovy,Clojure,Scala etc which are functional languages unlike Java(I am referring to Java before Version 8 where Lambda's are not supported) that doesn't support functional capabilities.On a high level what makes the JVM so versatile that it can support both Object Oriented as well as Functional languages? | What makes JVM so much versatile to support so many JVM languages? | java;programming languages;object oriented;functional programming;jvm | Compared to other VMs, the JVM actually isn't particularly versatile. It directly supports statically typed OO. For everything else, you have to see what parts you can use, and how you can build everything else your language needs on top of those parts.For example, until Java 7 introduced the invokedynamic bytecode, it was very hard to implement a dynamically typed OO language on the JVM - you had to use complex workarounds that were bad for performance and resulted in horribly bloated stack traces.And yet, a bunch of dynamic languages (Groovy, Jython, JRuby among others) were implemented on the JVM before that.Not because the JVM is so versatile, but because it is so widespread, and because it has very mature, well-supported and high-performing implementations. And, perhaps even more important, because there is a huge amount of Java code out there doing pretty much anything, and if your language runs on the JVM, you can easily offer facilities to integrate with that code. Basically, having your language run on the JVM is the 21st century version of offering interoperability with C. |
_unix.360276 | The xml file gets generated with empty tags is like this <headertag></headertag>It's in consecutive lines and i usually use a perl script to find it based on new line character between tags as pattern (\n) but Unix environment which I'm using now isn't supporting this perl script. Tried the same with sed but i couldn't find the place (line number) where there is a empty tag like this in a huge .xml file. Is there a solution to find this using sed or awk? | Find empty tag in `xml` using Unix command | awk;sed;xml | null |
_codereview.105295 | I have a web page containing n pages of paged data, showing 20 records at a time. The front end has a link to another page that opens the same data, but without the paging and calls window.print on document.ready.On my paged content view I have a link:<a href=printallthisstuff.php target=blank>Print all items</a>In printallthisstuff.php I have:$(document).ready(function(){ window.print();});printaallthisstuff.php can be a very large document, taking several seconds to load. What would be a better way of doing this? | Printing a huge document | javascript;php;jquery | null |
_unix.198230 | I recently installed Kali Linux on VMWare. I was able to successfully install openVPN following these instructions, but it seems that it does not pass the DNS Leak test. Is there anything that can fix that?Also, how can I stop my internet connection if my VPN fails? I do not want to expose my real IP. | Kali Linux openVPN does not pass the DNS Leak test | linux;dns;vpn;kali linux;openvpn | null |
_unix.379132 | I used Ubuntu as a desktop OS and Arch Linux for live USB (disk status detections and so). Recently I tried to install Arch Linux + Gnome instead of Ubuntu to my desktop, but was surprised gnome-terminal doesn't look as perfect as clean Arch. Is there a way, how to make gnome-terminal look like clean Arch UI?Currently my gnome-terminal look like this:Simply I want gnome-terminal look like this: | Is there a way to make gnome-terminal look like clean Arch? | arch linux;gnome terminal | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.