id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.169496 | When I first turn on the computer the mouse works as usual, but shortly after that the mouse cursor will stop moving and will stay stuck in one spot on the screen. This is hard to describe but although the picture of the cursor is stuck in one spot on the screen the position of the mouse seems to continue to update. So if I move the mouse around I'll see hyperlinks and buttons highlight to indicate that the mouse is moving over them. I can also click and the button or hyperlink activates as usual. The image of the cursor is stuck in one spot but it changes from pointer to cursor to text selection as I move the mouse around.I've tried to reset the mouse but the behavior stays the same.sudo rmmod psmousesudo modprobe psmouseThis behavior happened with Xubuntu 12.04 and I installed Linux Mint 17 and see the same behavior. I have a wireless Logitech mouse. I tried plugging in a wired mouse and see the same behavior.Any suggestions? I'm not even sure what to search for!Thanks! | Mouse cursor stuck but its movement is still registering | mouse | Your cursor problem seems to be the constant while distros change, indicating that it may be a hardware problem. Attempt disabling drawing the cursor via hardware and then restart the X server. This may be done by editing your xorg.conf which is often located in /etx/X11/xorg.conf. Note that it may be also be split into several files under /etc/X11/xorg.conf.d - see the xorg.conf(5) man page for more details.findSection: Devicewhich refers to the configuration of graphic your adapter.before the end of the section, add the following: Option HWCursor off(or change it appropriately, if already present)restart Xorg; this can be done in a number of ways:log out and ingo into a virtual terminal and kill it, e.g. killall Xorg (usually has to be done with root privileges) - the X server should be respawned after being killedrestart your computerSource: http://www.pendrivelinux.com/mouse-pointer-disappears-after-switching-users/ |
_softwareengineering.336284 | I'm just starting to explore SOLID and I'm unsure if reading from files and writing to files are the same responsibility.The target is the same file type; I want to read and write .pdf's in my application.The application is in Python if that makes any difference. | When following SOLID, are reading and writing files two separate responsibilities? | object oriented design;solid;single responsibility | The reading and writing implementation have a high probability of being highly cohesive. If one would change, so would the other. High cohesion is a strong indication of a Single Responsibility and the Single Responsibility Principle tells us that they should be put together in the same class.If however there are consumers that only read data without writing, or only write without reading, it is a indication that from an interface perspective you should separate these operations, as prescribed by the Interface Segregation Principle. This means that the consumers should define two interfaces that they can depend on, while the File class will implement both interfaces. |
_webmaster.75814 | My google webmaster tools is only showing a small subset of the full data for search traffic. I have 83 clicks but it's only displaying 5 clicks. Same with the impressions showing 831 impressions but only listing 138. Is there a way to see the complete data? | Google Webmaster Tools doesn't show all clicks | seo;google search console | null |
_codereview.156013 | I've written the following enum and have added a function, fromValue that allows the caller to map given int into the enum value. I was wondering if the value passed to the function can be validated, or is returning a null in case the value isn't present in the map (is an invalid enum) sufficient?public enum TestEnum { A(0x00), B(0x01), C(0x02); int test; private static final Map<Integer, TestEnum> VALUE_TO_TEST_ENUM; static { final Map<Integer, TestEnum> tmpMap = new HashMap<>(); for (TestEnum testEnum : TestEnum.values()) { tmpMap.put(testEnum.test, testEnum); } VALUE_TO_TEST_ENUM = ImmutableMap.copyOf(tmpMap); } TestEnum(final int test) { this.test = test; } public static TestEnum fromValue(final int value) { // Add validation? return VALUE_TO_TEST_ENUM.get(value); }} | Validate input that maps int to enum | java;validation;enum;hash map | Every instance in an enum already has an ordinal (the 0-based position of the value in the declaration order of the enum). For example, your instance C.ordinal() will return 2. See: Enum.ordinal(). These are the same values as the ones you are assigning to test. Is that a coincidence?Additionally, you're using a small range of 0-based values for the test field, and as a consequence, an array will be a better storage option than a Map. Even if the array is as much as 80% empty it would still be more efficient (space and performance) than the Map.About the exception - yes, I would throw a NoSuchElementException if the user tries to get a value that does not exist. Enums are compile-time constants and any use of the enum that's not legal should be reported, and found as soon as possible. In a sense, it's for this reason that Enums exist - to give compile-time certainty that your code references meaningful constants. The very fact that you are mapping the enum values back to an int is itself a bit concerning.There is no need to make the Map a read-only map. The map is completely contained/encapsulated in the enum and no other write accesses exist, and no user can write to it, so it's redundant to make it read-only.If your values can span a (very) wide range I would keep your Map-based lookup, but change the code to be:private static final Map<Integer, TestEnum> VALUE_TO_TEST_ENUM = new HashMap<>();static { for (TestEnum testEnum : TestEnum.values()) { tmpMap.put(testEnum.test, testEnum); }}public static TestEnum fromValue(final int value) { // Add validation? TestEnum v = VALUE_TO_TEST_ENUM.get(value); if (v == null) { throw new NoSuchElementException(No enum with value ' + value + '.); } return v;}If your values are in a small range, at, or close to 0, I would do:private static final TestEnum[] VALUE_TO_TEST_ENUM;static { int max = 0; for (TestEnum testEnum : TestEnum.values()) { max = Math.max(max, testEnum.test); } VALUE_TO_TEST_ENUM = new int[max + 1]; for (TestEnum testEnum : TestEnum.values()) { VALUE_TO_TEST_ENUM[testEnum.test] = testEnum; }}public static TestEnum fromValue(final int value) { // Add validation? if (value < 0 || value >= VALUE_TO_TEST_ENUM.length) { throw new NoSuchElementException(No enum with value ' + value + '.); } TestEnum v = VALUE_TO_TEST_ENUM[value]; if (v == null) { throw new NoSuchElementException(No enum with value ' + value + '.); } return v;}If your test values are from 0 to n-1 and are the same as the ordinals of the enums, then I would completely get rid of the test value, and have the code:private static final TestEnum[] VALUE_TO_TEST_ENUM;static { VALUE_TO_TEST_ENUM = TestEnum.values();}public static TestEnum fromValue(final int value) { // Add validation? if (value < 0 || value >= VALUE_TO_TEST_ENUM.length) { throw new NoSuchElementException(No enum with value ' + value + '.); } return VALUE_TO_TEST_ENUM[value];} |
_webapps.3790 | Is there a way to see a list of my pending friend requests on Facebook - that is, a list of people to whom I have sent a friend request, but who have not responded. I know that status is indicated when I look at a list of friends on account - edit friends - all connections list, but I don't see a way to filter that list by this criterion. | Is there a way to see a list of pending friend requests on Facebook? | facebook | There is an Application that (for the moment, anyway) will perform this function. It's called, predictably, Pending Friend Requests.Source |
_unix.82249 | I updated motherboard on x240 computer node, now the ethernet interfaces show up as eth2 and eth3 previously it was eth0 and eth1.I tried to delete /etc/udev/rules.d/70-persistent-net.rules file but the problem still persists. On boot it says that eth3 and eth2 cannot be recognized or mapped. The new mac addresses are clearly illustrated and mapped to name files eth2 and eth3.I did change in file ifcfg eth2 and eth3 and change its name to eth0 and eth1 respectively. But this too had little effect, do I need this change to be done in 70-persistent file as well? I.e. change name to match the entry in ifcfg?.Is there a way i can bring the old mapping back? Thanks. | Unable to recognize old interfaces after motherboard update | ubuntu;networking;ethernet | null |
_scicomp.16430 | I am solving a problem of the form:$\dfrac{\partial u(x,y,t)}{\partial t} = \nabla^2 u(x,y,t) - f(x,y,t)u(x,y,t) - \kappa(x,y,t)$At the moment, I am solving this at each time step by assuming a quasi-steady-state:$\nabla^2 u(x,y,t) = f(x,y,t)u(x,y,t) + \kappa(x,y,t)$To do this, I use finite differences, which means solving the following (forgetting boundary conditions for now, but for reference they are Neumann) at each time step:$\dfrac{u^t_{i, j+1} + u^t_{i+1, j} + u^t_{i, j-1} + u^t_{i-1, j} - 4u^t_{i,j}}{h^2} = f^t_{i,j} u^t_{i,j} + \kappa^t_{i,j}$This means I have to solve a linear system of the form:$Ax = b$Where $A$ is a matrix made of the laplacian, as well as the $f^t_{i,j} u^t_{i,j}$ term. For my 100x100 system (resulting in a laplacian of size 10000x10000), this takes about 0.4 seconds for each time step using Eigen's C++ library solver:SimplicialLLT. However, I would like to speed up solving by any means possible. The issue is that I am limited in the pre-conditioning that I can do since the matrix $A$ changes each time step.Does anyone have any ideas? Finite element, spectral methods, non-steady state approximations all welcome.Before anyone asks, the terms $f^t_{i,j}$ and $\kappa^t_{i,j}$ cannot be forecast ahead of time, as they depend on $u^{t-1}_{i,j}$. Hence parallelisation is not going to be possible I think. Best,Ben | Solve steady state reaction-diffusion/Helmholtz equation numerically | finite element;finite difference;linear solver;advection diffusion;spectral method | null |
_unix.275070 | I'm using Linux Mint MATE with Paper theme | Why do strange boxes appear on my Linux Mint MATE? | linux mint;mate | null |
_cs.75804 | Design a data structure for holding numbers in two sets:Init - initiate the DS with two empty sets. O(1)Insert(a,S) - insert number a to set S (S could be X or Y). O(log(n)). (n is the total number of numbers in the DS)Find - find a number a in the DS such that the number of numbers in X that are smaller than a equals the number of numbers in Y that are bigger than a, if exists such number. O(1)My attempt is using 2 augmented balanced binary search trees, each one presents set X or Y, insert into it the new number and saving in each node information for finding what is the number of numbers in X that are smaller than this node and the number of numbers on Y that are bigger than that node. But given that information how could I implement the Find procedure in O(1)? Or maybe someone have better design (preferably using augmented BST)? | A data structure for holding numbers in 2 sets, using BST? | data structures;binary search trees | null |
_webapps.87074 | I like to listen to an entire album at a time on YouTube. Many of the actual albums have songs that drift off into each other and all blend together. On YouTube, however, there is a pause in between each video ruining the effect. Is there a way to prevent this pause between tracks? | Prevent pauses between music tracks on YouTube Playlist | youtube | null |
_cs.11525 | Prove that context free languages aren't closed under this operation: $ A(L) = \{ zyx \mid x,y,z \in \{0,1 \}^*, xyz \in L \} $Obviously, we need to find a context free language $L$ such that $A(L)$ isn't context free. Here are some of my failed attempts:Take the language $ L = \{\ 0^n1^n \mid n \in N \} $ and then (since the intersection of a context free language with a regular language is context free) we get: $ A(L) \cap 1^*0^*1^*0^* = \{\ 1^{m}0^{n-k}1^{n-m}0^{k} \mid n,k,m \in N, m,k\le n \} $ which might look promising at first, but unfortunately this language is context free...I also tried my luck with the following languages:$ L = \{\ 0^n1^m0^m1^n \mid n,m \in N \} $$ L = \{\ ww^R \mid w \in \{0,1 \}^* \} $ but these languages didn't help me either... | Prove that context free languages are not closed under swapping prefixes and suffixes | formal languages;context free;closure properties;pumping lemma | Did you try $\{\ a^nb^nc^md^m \mid m,n \ge 1 \}$?Or, if you insist on alphabet $\{0,1\}$,consider $\{\ (01)^n(011)^n(0111)^m(01111)^m \mid m,n \ge 1 \}$?And be shure to intersect with a nice regular language after the operation, but from your question I see that you know how that works. |
_opensource.4676 | As an example, the real time operating system FreeRTOS is licensed under the FreeRTOS Open Source License which is based on a modified GNU GPL, the modification taking the form of an exception. The GNU GPL is approved by the Open Source Initiative, but not the FreeRTOS Open Source License. If I use FreeRTOS in my software, and the rest of my software is released under an approved Open Source licence, would I be wrong to call my software Open Source?The OSI FAQ says:Can I call my program Open Source even if I don't use an approved license? Please don't do that. If you call it Open Source without using an approved license, you will confuse people. This is not merely a theoretical concern we have seen this confusion happen in the past, and it's part of the reason we have a formal license approval process. See also our page on license proliferation for why this is a problem.The Open Source stamp is important to me and I like using FreeRTOS but I also want to call things what they are. I am not 100% sure about this one that is why I prefer to ask here. I asked the question in a generic way so it can also be useful to others. | Is it wrong to call a software Open Source if it is using a license based on GNU GPL? | gpl;open source definition | Unfortunately for you, the FreeRTOS license is fundamentally broken:Any FreeRTOS source code, whether modified or in it's original release form, or whether in whole or in part, can only be distributed by you under the terms of the GNU General Public License plus this exception. An independent module is a module which is not derived from or based on FreeRTOS.And the exception contains in particular:Clause 2:FreeRTOS may not be used for any competitive or comparative purpose, including the publication of any form of run time or compile time metric, without the express permission of Real Time Engineers Ltd. (this is the norm within the industry and is intended to ensure information accuracy).This contradicts the terms of the GPL which contain in particular:You may not impose any further restrictions on the recipients' exercise of the rights granted herein.Now this may sound confusing as the GNU FAQ page contains tons of references to exceptions that can be added to the GPL. And indeed there are tons of existing such exceptions. The most well known is nothing less than LGPL (which is just GPL + an exception). But what all those exceptions have in common is that they do not add any further restrictions. They just grant more rights! And in particular, any person is allowed to distribute the program further under GPL without the exception.What if the exception had been acceptable?If the exception to the GPL had been an exception in the usual sense, then by using GPL + exception, you would a fortiori be distributing your program under GPL, and thus, you would be distributing it under an approved open source license.What about calling your program open source anyway?If you choose to distribute the program you wrote under an open source license but it has a non-open source dependency, then you could just make sure that people understand that when you are saying my program is open source, you are talking about the program itself and not the dependencies. It is still interesting to people: they can replace the dependency by something else if they want and make the whole program open source. |
_unix.232581 | The script is working:#!/bin/shecho Enter Server IP Addressread IPecho 'mypassword' | sudo -S ssh $IP </home/myscript.sh How do I modify it so I can manually enter the IP address, and then mypassword? | Manually entering a password | shell script | null |
_softwareengineering.69018 | In my experience before you start working for a company you have no opportunity to look at the code-base (I've asked and for reasons of confidentiality everyone has always said no, I think that is fair), so during the interview process what do you think are the most important questions to ask to find out what kind of state the code is in (after all, if it's a dog, then you are going to be on of the poor unfortunates who has to walk it every day)?UPDATE:A check-list: Ask;What they think of the codebase. And when you do, pay close attention to facial expressions and the time it takes for them to respond. [Anon]What is the company's CMM level [DPD] (and if you hear Level 5 run the other way [Doug T])What lifecycle they use [DPD] (And if you do hear Agile, that's when you start asking some penetrating questions to try to figure out if by Agile they mean Agile or cowboy coding [Carson63000])What tools they use to asses code quality? [DPD]What tools they use for development? [DPD] (Look for refactoring tools and continuous build servers)What source code (version control) system they use, and a good follow up is to ask why they use it. [Zachary K].What are their testing procedures like? [Karl Bielefeldt] (Look especially for teams that use mocking frameworks and place an emphasis on thorough automated unit testing through established frameworks like NUnit / JUnit; don't be put off by teams that don't use test driven development TDD, but be wary if they don't consider testing to be integral to and the cornerstone of solid software development. Look for teams with dedicated testers.)What kinds of assignments are given to new developers? To experienced developers? [Karl Bielefeldt]How many people work on a project? [Karl Bielefeldt]Is refactoring allowed? Encouraged? [Karl Bielefeldt]What quality-related process or architecture changes are under consideration or have been made recently? [Karl Bielefeldt]How much autonomy do individuals have over their modules? [Karl Bielefeldt]Will you be developing newer projects (greenfield development) or legacy projects (brownfield development)? (Greenfield development is generally more fun and has less problems as you aren't cleaning up with someone else's mistakes).Is the employee turnover rate is high in the organization or the team? (This often indicates lower quality of code) [M.Sameer]Some programming problems of your own; but avoid seeming like a jerk. [Sparky]How do the developers collaborate and how is knowledge shared amongst the team? (This should match your personality; I would say a mixture of solo and pair work is probably best, with the ratio matching your social needs)How close their database is to 3rd Normal Form (3NF), and if it deviates where and why? (If they say 3NF???, leave. If not, and there might be good reasons for it not, then find out what they are).NOTE:I've accepted Anon's answer because after about a week the community thinks that it is the best one - I think this suggests that it is just something that you somehow need to develop a sixth-sense for. But, I think everyone has had something valuable to say. | How do you ascertain the quality of a potential employer's code before you take a position? | interview;code quality | Rather than ask to see their code, ask what they think of the codebase. And when you do, pay close attention to facial expressions and the time it takes for them to respond.Then apply your knowledge of your culture's non-verbal gestures to interpret what they're really saying. For a North American company, the following should be accurate:A small shrug, and quick response of it could be better: it's probably pretty good.A long pause, intake of breath, perhaps a small laugh: it's not pleasant, and the people that you're interviewing don't feel comfortable telling you that.Rolled eyes, quick response of it sucks: might be good, might be bad, but there are political games happening. Unless you're ready to play that game or be a quiet nobody, stay away.Raised or contracted eyebrows: they don't understand the question, and the codebase is almost certainly putrid.Of course, if you have trouble with inter-personal communication, this might not work for you. |
_unix.274963 | I am running NUnit tests on Ubuntu via mono. They require the certmgr tool to install certificates and keys that the tests utilize. The user cert/key I can install fine, but the tests fall over if the CA certificate is not installed in the MACHINE rather than LOCAL USER Trust store.However, the Machine store requires sudo to install certificates. The user running the tests, I don't want to give sudo privileges to. Can I reduce the privileges required to install certificates to the machine store? | Can I reduce the privileges level on mono's certificate machine store? | certificates;mono | The machine store keys and certificates are stored in the root user's home directory:/root/.config/.mono/However, when I chmod'd the subdirectories there to provide access to the user in question, it didn't work, I still got permission denied.Instead, I'm taking dave_thompson_085's tip. I gave the user sudo access to mono's certmgr utility and now it's working well. |
_unix.244650 | I have log files with a time stamp and six values in each linei want to reduce the amount of data, by removing consecutive lines with the same values (ignoring time stamps) and keeping the first and last line of each duplicate set. Preferably using a bash script. It should be a magic sed or awk command combination.Even if i have to parse the file multiple times, reading 3 lines at a time and removing the middle one, is a good solution.original file:1447790360 99999 99999 20.25 20.25 20.25 20.501447790362 20.25 20.25 20.25 20.25 20.25 20.501447790365 20.25 20.25 20.25 20.25 20.25 20.501447790368 20.25 20.25 20.25 20.25 20.25 20.501447790371 20.25 20.25 20.25 20.25 20.25 20.501447790374 20.25 20.25 20.25 20.25 20.25 20.501447790377 20.25 20.25 20.25 20.25 20.25 20.501447790380 20.25 20.25 20.25 20.25 20.25 20.501447790383 20.25 20.25 20.25 20.25 20.25 20.501447790386 20.25 20.25 20.25 20.25 20.25 20.501447790388 20.25 20.25 99999 99999 99999 999991447790389 99999 99999 20.25 20.25 20.25 20.501447790391 20.00 20.25 20.25 20.25 20.25 20.501447790394 20.25 20.25 20.25 20.25 20.25 20.501447790397 20.25 20.25 20.25 20.25 20.25 20.501447790400 20.25 20.25 20.25 20.25 20.25 20.50desired result:1447790360 99999 99999 20.25 20.25 20.25 20.501447790362 20.25 20.25 20.25 20.25 20.25 20.501447790386 20.25 20.25 20.25 20.25 20.25 20.501447790388 20.25 20.25 99999 99999 99999 999991447790389 99999 99999 20.25 20.25 20.25 20.501447790391 20.00 20.25 20.25 20.25 20.25 20.501447790394 20.25 20.25 20.25 20.25 20.25 20.501447790400 20.25 20.25 20.25 20.25 20.25 20.50 | Remove partial duplicates consecutive lines but keep first and last | text processing;sed;awk | With awk one liner:awk '{n=$2$3$4$5$6$7}l1!=n{if(p)print l0; print; p=0}l1==n{p=1}{l0=$0; l1=n}END{print}' fileThe whole point is to manipulate few variables: n stores all fields except first in current line, l1 the same for previous line and l0 the whole previous line. The p is just a flag to mark if previous line was already printed. |
_softwareengineering.82609 | In situations where I need to write observer/subscriber code, how would I choose between the following approaches?A) Declaring an event that simply notifies a client something happens but requires the client to make a query for data e.g.class SoothSayer{ int DaysUntilApocalypse{get;} event EventHandler<EventArgs> TheEndIsNigh;}B) Declaring an event with specific XXXEventArgs containing the event data e.g.class SoothSayer{ event EventHandler<ApocalypsePendingEventArgs> TheEndIsNigh}class ApocalypsePendingEventArgs:EventArgs{ int DaysLeft{get;}}C) Using a callback rather than an event e.g.class SoothSayer{ public SoothSayer(Action<int> endIsNighCallback){ _endIsNightCallBack = endIsNighCallback; }} | How To Choose Between Different Methods of Handling/Raising Events? | c#;design | Version (c) is a form of continuation passing, it is not an event at all. It is a wholly different method of control flow, and can be used to express some complex types of control flow that are difficult to express with primitive constructs such as loops and conditionals. For example, it's the basis for asynchrony in C# 5. All await really does, in essence, is pass a continuation.It is certainly a valid construct, but the answer to when you should use this for event-driven programming is never, because it's not an event. There is no subscription of any kind; the callback is coupled to method call. You also can't have multiple subscriptions, which you can have with any old event.So it comes down a choice between (a) using a plain EventHandler or (b) using a custom MyEventHandler with event data. And the answer to that is simple: use a custom event if there is important, transient data associated with the event.Imagine if you had to query for the cursor position every time you executed a MouseDown event handler. It would be completely unreliable, because the mouse position could and often would change between the time the event was fired and the time it was handled. On the other hand, an Initialized event is pretty self-explanatory; it's only going to happen once in the lifetime of an object and there's really not much else to say about it other than OK, I'm ready!.So, in summary, (a) use the default EventHandler when you've got nothing else interesting to say, (b) use a strong-typed EventHandler<T> when you do, and (c) don't use CPS for event notifications. |
_unix.311839 | In Backtrack I entered this command :vi /etc/network/interfacesAnd then set these lines :iface eth0 inet staticaddress 192.168.1.10netmask 255.255.255.0network 192.168.1.0gateway 192.168.1.1Saved and exited, then restarted my OS. But when I enter ifconfig command, it shows me that the:inet addr :192.168.1.105Why ?I am sure that the previous vi command is saved because when I again enter command:vi /etc/network/interfacesthe result shows me that:iface eth0 inet staticaddress 192.168.1.10netmask 255.255.255.0network 192.168.1.0gateway 192.168.1.1 | Why my IP is not set? | networking;vi;backtrack | null |
_cs.19066 | I am implementing a sample MESI simulator having two levels of cache (write back). I have added MESI status bits to both levels of cache. As it is a write back cache, the cache line is updated to L2 only when it is flushed. My doubts arewhat should be the behavior when a cache line with INVALID state is flushed from L1 cache. Will it just ignore the transaction? It seems that is the only possibility..but it doesn't seem right.Consider processor1(P1) modifying a cacheline shared by processor2(P2). Then that cache line in P2 will get status INVALID. If P2 has to update the same cache line in future and sees the state is INVALID, it should read the updated value from??what if it is still in modified state in P1(not yet written back to L2/Main memory)? Consider a similar situation that P1 has a cache line in MODIFIED state, P2 has the same line in INVALID state. When P3 tries to retrieve the same line, it broadcasts a request to all L1 caches. According to the theory,if P3 cant get the cache line from any other L1 caches, it sends request to L2/main memory. In this case where will P3 get the requested cache line from? From P1 or from the L2/main memory? Or will P1 update to the main memory first and then send the cache line to P3?I am using LRU for flushing the cache(write back). When flushing a cache if it is INVALID what should be the behavior? It just ignores the line? | MESI Protocol Invalid cache line is attempted to be stored? | cpu cache;protocols | null |
_unix.335569 | I need to select and output into a file some text contained in a specific string. Let's say the string is: ABCDEFGHIJKLMNOPWhat would be a command to extract what is after ABCDEF and before K? (i.e. GHIJ only) to another file?I tried with grep command but due to my poor understanding of its complexity it failed every time. I must be missing something very basic. Thanks a lot in advance. | How to select and output text in a string | grep;string;output | null |
_codereview.90329 | I just started learning commands for batch files. I figured a project is a good way to learn the language better, so I'm attempting to recreate the text-based RPG, Thy Dungeonman 3.So far, I've learned a lot from fixing a lot of minor problems such as lack of quotation marks, extra spaces at the end of environmental variables, and placement of certain commands that all gave a bit of frustration.I've got a good method down so far, but I feel like I'm being very long-winded with the commands. It might be that I'm just going with what I'm comfortable with, but I am trying to implement ELSE, and IF NOT DEFINED when I can. I'm just looking for some more experienced eyes to see if there is a more concise way of going about this (aside from the CHOICE option, which I plan to implement later, and probably won't fit the scenario now). Here is what I got so far after about 3.5 hours:@echo offcolor 0etitle Thy Dungeon Man 3echo -------------------------------------------------------------echo Thy Dungeon Man 3echo -------------------------------------------------------------pauseecho.echo Objective: Get ye flask!echo. echo Commands: Go, Get, Use, Look, Talk, Dance, etc...pauseecho.echo Type INV to open inventory.pauseclsset boneinv=0set clawsinv=0:Dungeon1echo Ye find yeself in yon dungeon. Thou art tied up with ropes. The spiked walls of the dungeon closeth in on thee. A dongrel skeleton with sharp CLAWS hangs next to you. A BONE layeth upon the ground. Obvious exits are nowheres!:Dungeon1aecho.echo What wouldst thou deau?set /p choice1=echo.if %choice1%==get bone ( if %clawsinv%==0 ( echo. echo Thou wouldst, if thou weren'st tiedst upst. echo. pause cls goto Dungeon1a ))if %choice1%==look ( if %boneinv%==2 ( cls echo Ye find teself in yon dungeon. The spiked walls of the dungeon are jammed open with a big ol' bone. A stone door layeth open to the NORTH. A dongrel skeleton with sharp CLAWS hangs next to you. goto Dungeon1a ) else ( cls goto Dungeon1 ))if %choice1%==inv ( if %boneinv%==0 ( echo. echo Nothing but streets and roads. Note to thyself: The spikey walls draw nearer. echo. pause cls goto Dungeon1a ))if %choice1%==inv ( if %boneinv%==1 ( echo. echo Ye has: a big ol' bone, and an unbearable lightness of being. echo. pause cls goto Dungeon1a ))if %choice1%==inv ( if %boneinv%==2 ( echo. echo Nothing but streets and roads. echo. pause cls goto Dungeon1a ))if %choice1%==get ye flask ( echo. echo Ho, ho. Aren't thee witty? Twere it that simple I wouldn't have bothered making this game. Note to thyself: The spikey walls draw nearer. echo. pause cls goto Dungeon1a)if %choice1%==get flask ( echo. echo Ho, ho. Aren't thee witty? Twere it that simple I wouldn't have bothered making this game. Note to thyself: The spikey walls draw nearer. echo. pause cls goto Dungeon1a)if %choice1%==talk dongrel ( echo. echo Ye decide to waste time talking to the dead dongrel skeleton. Good one. echo. pause cls goto Dungeon1a)if %choice1%==get claws ( if %clawsinv%==0 ( echo. echo Now thou art using thy dungeonsmarts! You shimmy all up on the dead dongrel and its razor sharp claws slice through the ties that bind. Thou art free! echo. pause set clawsinv=2 cls goto Dungeon1a ))if %choice1%==get bone ( if %clawsinv%==2 ( if %boneinv%==0 ( echo. echo Bone grasped! Note to thyself: The spikey walls draw nearer. echo. pause set boneinv=1 cls goto Dungeon1a ) ))if %choice1%==use bone ( if %boneinv%==1 ( echo. echo Ye waits until the spiked walls draw dangerously close then thou jammeth the sturdy bone in their collective craw! The walls shudder and quay and finally withdraw! A stone door opens to the NORTH! Exclamations! echo. pause set boneinv=2 cls goto Dungeon1a ))if %choice1%==go north ( if %boneinv%==2 ( cls goto Dungeon2 ))if %choice1%==go south ( if %boneinv%==2 ( echo. echo The walls in this room are totally cramping thy style. pause cls goto Dungeon1a ))if %choice1%==go east ( if %boneinv%==2 ( echo. echo The walls in this room are totally cramping thy style. pause cls goto Dungeon1a )) if %choice1%==go west ( if %boneinv%==2 ( echo. echo The walls in this room are totally cramping thy style. pause cls goto Dungeon1a ))if not defined %choice1% ( echo. echo Thou're not very goodst at thist gamest. echo. pause cls goto Dungeon1a):Dungeon2echo win!pauseexitThis is basically one room of many that I plan to follow the same style of writing for, unless I can find a more efficient way of putting all of the commands. So far, everything is working fine. | Thy Dungeonman 3 using batch | beginner;adventure game;batch | null |
_webapps.82557 | Recently (as of mid August 2015) YouTube has changed its UI so that it automatically sets the resolution to the window size (typically 360) and no longer gives the user the option to choose their resolution. Even if the user goes to full screen, it still stays at 360.How can control the resolution of the video and watch at HD full screen?I would prefer a solution that does not involve installing software or add-ins. | YouTube no longer allows user to set resolution | youtube | null |
_computergraphics.283 | I'm interested in how this applies to higher numbers of dimensions too, but for this question I will focus solely on 2D grids.I know that Perlin noise is not isotropic (direction invariant), and that the underlying square grid shows up enough to be able to identify its orientation. Simplex noise is an improvement on this but its underlying equilateral triangle grid is still not completely obscured.My intuition is that any attempt to make noise of a particular frequency on a grid will result in a lower frequency in directions not aligned to the grid. So while attempts can be made to disguise this, the noise cannot in principle be isotropic unless it is generated without reference to a grid, allowing the average frequency to be the same in all directions.For example, with a square grid without noise, with square side length $n$, the frequency of vertices horizontally or vertically is $\frac1n$, whereas the frequency of vertices at 45 degrees (through opposite corners of the squares) is $\frac1{\sqrt{2}n}$. Is there a random distribution that could be applied to offset the vertex positions that would result in the frequency becoming identical in all directions? My suspicion is that there is no such distribution, but I don't have a way of proving either way.In short, is there a way of making perfect grid based noise of a given frequency, or should I be focused on other approaches (non-grid based noise or ways of disguising artifacts)? | Is all grid based noise inevitably anisotropic? | noise;grid | null |
_cs.43956 | Given $n$ boolean variables $x_1,\ldots,x_n$ each of which is assigned a positive cost $c_1,\ldots,c_n\in\mathbb{Z}_{>0}$ and a boolean function $f$ on these variables given in the form$$f(x_1,\ldots,x_n)=\bigwedge_{i=1}^k\bigoplus_{j=1}^{l_i}x_{r_{ij}}$$($\oplus$ denoting XOR) with $k\in\mathbb{Z}_{>0}$, integers $1\leq l_i\leq n$ and $1\leq r_{i1}<\cdots<r_{il_i}\leq n$ for all $i=1,\ldots,k$, $j=1,\ldots,l_i$, the problem is to find an assignment of minimum cost for $x_1,\ldots,x_n$ that satisfies $f$, if such an assignment exists. The cost of an assignment is simply given by$$\sum_{\substack{i\in\{1,\ldots,n\}\\x_i\,\text{true}}}c_i.$$Is this problem NP-hard, that is to say, is the accompanying decision problem Is there a satisfying assignment of cost at most some value $K$ NP-hard?Now, the standard XOR-SAT problem is in P, for it maps directly to the question of solvability of a system of linear equations over $\mathbb{F}_2$ (see, e. g., https://en.wikipedia.org/wiki/Boolean_satisfiability_problem#XOR-satisfiability). The result of this solution (if it exists) is an affine subspace of $\mathbb{F}_2^n$. The problem is thus reduced to pick the element corresponding with minimal cost from that subspace. Alas, that subspace may be quite large, and indeed, rewriting $f$ in binary $k\times n$-matrix form, with a $1$ for each $x_{r_{ij}}$ at the $i$-th row and the $r_{ij}$-th column, and zero otherwise, we get a cost minimization problem subject to$$Ax=1,$$where $A$ is said matrix, $x$ is the column vector consisting of the $x_1,\ldots,x_n$ and $1$ is the all-1-vector. This is an instance of a binary linear programming problem, which are known to be NP-hard in general. So the question is, is it NP-hard in this particular instance as well? | Is weighted XOR-SAT NP-hard? | optimization;np hard;satisfiability;integer programming;xor | A classical result of Berlekamp, McEliece, and van Tilborg shows that the following problem, maximum likelihood decoding, is NP-complete: given a matrix $A$ and a vector $b$ over $\mathbb{F}_2$, and an integer $w$, determine whether there is a solution to $Ax = b$ with Hamming weight at most $w$.You can reduce this problem to your problem. The system $Ax = b$ is equivalent to the conjunction of equations of the form $x_{i_1} \oplus \cdots \oplus x_{i_m} = \beta$. If $\beta = 1$, this equation is already of the correct form. If $\beta = 0$ then we XOR an extra variable $y$ to the right-hand side, and then we force this variable to be $1$ by adding an extra equation $y = 1$. We define the weights as follows: $y$ has weight $0$, and the $x_1$ have weight $1$. We have now reached an equivalent formulation of maximum likelihood decoding which is an instance of your problem. |
_unix.309418 | I have a touch panel (goodix) and I need to send the device configuration to the firmware. I have a *.cfg file but I neither know nor find how to load this file.Do you know what is the way to load this file? | Load cfg file in kernel driver | linux kernel;drivers;kernel modules;firmware;touch screen | null |
_softwareengineering.314892 | Until now I didn't find anything good about monitoring a DB's specific table (or related tables) specific values changed. I want to know:Since most of DB's don't support monitoring changes for specific rows/values/columns, how to link them together? (I mean I don't want to use something like Timer or loop to check whether a specific row's value is changed and notify my client).So is it necessary for us to make another new technology that will support notifications to the client application about which is changed in my DB? Or is there anything that has made this come true? | How to do an Automatic DB monitor and notify the client | database;monitoring | Most databases use one-way request-response approach: the client contacts the server and (eventually) expects an answer in return. This, essentially, prevents the server from notifying a client about anything; techniques such as polling, exist, but have their own drawbacks (such as the heavy load on server and network).On the other hand, you seem to expect a two-ways communication; RethinkDB, already quoted in a comment, is one example of a database which supports this, so it may be a solution for the problem you are trying to solve.Another solution would be to simply track the changes within your own application, at data access layer. Depending on the language/framework you use, this could be more or less easy to implement, as well as to use technologies such as WebSockets in order to propagate the changes down to the end users.Finally, if you need to track changes to a table which is used across multiple applications, you may create a web service which will have exclusive rights to modify this table, and make all other applications call this service instead of querying the database directly. On change, the service may use a message queue service to broadcast the message indicating that the data was changed. |
_codereview.62314 | I would like to gather ideas on how to refactor the JavaScript/NodeJS controller code below to be more aesthetic. The code is using the koa framework thus I use yield commands. I also use mongoose (I'm waiting for 3.9.2 which will support promises). As a Ruby on Rails developer, I'm searching for a Rails-style way on writing NodeJS programs.'use strict'/* * Model dependencies */var _ = require('lodash')var parse = require('co-body')var db = require('mongoose-glue')/* * User controller. */module.exports = { /* * Lists available users. */ index: function*(id) { var skip, limit skip = Math.max(0, this.query.skip) limit = Math.min(10, this.query.limit) this.body = yield db.model('user').find().skip(skip).limit(limit).exec() }, /* * Displays user with an id. */ show: function*(id) { this.body = yield db.model('user').findById(id).exec() this.status = this.body ? 200 : 404 }, /* * Creates a new user. */ create: function*() { var data try { data = yield formData(this, 'name') this.body = yield createUser(data) this.status = 201 } catch(e) { this.body = e this.status = 403 } }, /* * Updates user with an id. */ update: function*(id) { var data try { data = yield formData(this, 'name') this.body = yield updateUser(id, data) } catch(e) { this.body = e this.status = 403 } }, /* * Removes user with an id. */ destroy: function*(id) { var item try { item = yield destroyUser(id) this.status = item ? 200 : 404 } catch(e) { this.body = e this.status = 403 } },}/* * Create user thunk */function createUser(data) { return function(next) { db.model('user').create(data, next) }}/* * Update user thunk. */function updateUser(id, data) { return function(next) { db.model('user').findByIdAndUpdate(id, data, next) }}/* * Create user thunk */function destroyUser(id) { return function(next) { db.model('user').findByIdAndRemove(id, next) }}/* * Returns form data. */function *formData(ctx) { var data data = yield parse.form(ctx) data = _.any(arguments) ? _.pick(data, arguments) : data return data} | Controller code using the koa framework | javascript;node.js;controller;mongoose | Interesting question,I understand you search for a rails-style way on how to write nodejs programs. However from a CodeReview perspective, your code should be idiomatic (conforming to the mode of expression characteristic of a language) so that other developers can grok your code and even maintain it.From that perspective your code is quite good, the only thing being that you really (really) should put those semi-colons. Just get over it, good JavaScript has semicolons at the end of each line.Other than that:I like the use of 'use strict', generator functions and yieldI like the amount of comments, not so much the style, I would go for less vertical real estate/* * User controller. */could just as well be//User controllerIt's a matter of taste but I find this more idiomatic var skip = Math.max(0, this.query.skip), limit = Math.min(10, this.query.limit);thanvar skip, limitskip = Math.max(0, this.query.skip)limit = Math.min(10, this.query.limit)I guess from a style perspective you want to split declaration from initialization, but I find this takes too much vertical real estate.Logging/Handling errors, you should consider putting more effort in handling errors than simply throwing a 403 on the client side, you should do something on the server side as wellMagic constants (404, 200) etc. are known well enough that you don't have to create named constants.All in all I like your code, I guess if I had to maintain I would run it thru a script to fix all the semicolons and comments and go from there ;) |
_cs.45325 | If I have two sorted lists.list A => 1 -> 2 -> 4 -> 11 -> 31list B => 2 -> 31 -> 54Now what should be the order of (sorted) merge and why?According to the rule, If the list lengths are m and n, the merge takes $O(m+n)$ operations, the order should be $O(5 + 3)$. Am I right? I would appreciate if someone help me out in understanding it. | If the list lengths are m and n, why does the merge take O(m+n) operations? | algorithm analysis;runtime analysis;linked lists | You are asking: Now what should be the order of merge and why?First of all, we need to fix the merging algorithm. I'll assume the canonical one, i.e.merge(A, B) { if ( A.size == 0 ) { return B } if ( B.size == 0 ) { return A } if ( A.head <= B.head ) { return A.head + merge(A.tail, B) } else { return B.head + merge(A, B.tail) }}Now you propose two lists:A = 1 -> 2 -> 4 -> 11 -> 31B = 2 -> 31 -> 54So just execute the algorithm and count operations! I'll assume that you only want to count the comparison A.head <= B.head. A compacted trace of the algorithm is (unfolding the recursion)C = A = 1 -> 2 -> 4 -> 11 -> 31B = 2 -> 31 -> 54C = 1A = 2 -> 4 -> 11 -> 31B = 2 -> 31 -> 54C = 1 -> 2A = 4 -> 11 -> 31B = 2 -> 31 -> 54C = 1 -> 2 -> 2A = 4 -> 11 -> 31B = 31 -> 54C = 1 -> 2 -> 2 -> 4A = 11 -> 31B = 31 -> 54C = 1 -> 2 -> 2 -> 4 -> 11A = 31B = 31 -> 54C = 1 -> 2 -> 2 -> 4 -> 11 -> 31A = B = 31 -> 54C = 1 -> 2 -> 2 -> 4 -> 11 -> 31 -> 31 -> 54A = B = So you see it took seven recursive calls (plus the main call), and six comparisons. You can easily swap the parameters and do the same; you'll get seven comparisons. So the order you have is slightly better. Do you see why? It's advantageous if one of the lists runs empty early.Note that the order of comparison and whether you use <= or < is crucial here; other choices may make the other order better.Having worked through this example, you are ready to think about what the worst case inputs are. Two lists of length $m$ and $n$ that run empty at the same time.And then you execute the algorithm symbolically and count the number of steps necessary. If you can never append more than one element when the other list is empty (return A resp. return B), you had to have had $n + m - 1$ recursive calls up to that point, one for each element, since you only ever pick one element per recursive call. Plus the last call, that's a total of n+m recursive calls. Since every call does merge at least one element, there can be no more than $n+m$ recursive calls, so this is indeed the worst case.Now you observe that each recursive call takes time $O(1)$, assuming a suitable list representation (in particular with $O(1)$-time size), and you are done.This is not rocket science, by the way; it's rater mechanic, in fact, as our reference question explains.As an exercise, you can carry over the analysis to a more typical iterative implementation of merge. |
_codereview.136787 | This code is meant to run through a column of values, bin the values based on specified ranges, then output the average value of each bin. The problem is the code is running quite slowly (approximately 30 min for around 100000 values). I am definitely a beginner at coding and was hoping there was some way to speed this code along.Sub BinValues()'binns seperation distance values for the creation of variogramApplication.ScreenUpdating = FalseApplication.EnableEvents = FalseApplication.Calculation = xlCalculationManualDim Cell As ObjectDim R1 As RangeDim R2 As RangeDim rng As Range'define range before runningSet rng = Range(A1:A105570)Dim K, n, L As Integer'n is equal to the number of lags'L is the lag sizen = 12L = 600For K = L To (n * L) Step 600 For Each Cell In rng Dim min As Integer min = K - L 'upper bound exclusive and lower bound inclusive If Cell.Value >= min And Cell.Value < K Then If R1 Is Nothing Then Set R1 = Range(Cell.Address) Else Set R1 = Union(R1, Range(Cell.Address)) End If Cells((K / L), 5) = WorksheetFunction.Average(R1) End If Next Set R1 = NothingNextApplication.ScreenUpdating = TrueApplication.EnableEvents = TrueApplication.Calculation = xlCalculationAutomaticEnd Sub | Output the average values of binned columns in Excel VBA | performance;beginner;vba;excel | Data belongs in an ArrayA worksheet *looks* like a grid of data, but there's an enourmous amount of overhead sitting behind it. Every time you do anything to a spreadsheet, events fire, formulas calculate and a million other things happen behind the scenes.Working with Ranges is computationally expensive, and you're doing it N*105,570*2 times.Instead, what you want is an Array. An Array is just a grid of data laid out in memory. Because it is *just* data there are no overheads, and so you can read/write to it about a Million times faster. You can create an Array by reading in a range, like so:Dim dataRange As RangeSet dataRange = Range(A1:A105570)Dim dataArray As VariantdataArray = dataRange.ValueAnd now, the value in A1 is in dataArray(1, 1), A2 in dataArray(2, 1) etc.Let's re-write your code to use an Array:Option ExplicitPublic Sub BinValues() 'binns seperation distance values for the creation of variogram Application.ScreenUpdating = False Application.EnableEvents = False Application.Calculation = xlCalculationManual Dim dataRange As Range Set dataRange = Range(A1:A105570) Dim dataArray As Variant dataArray = dataRange.Value Const NUM_LAGS As Long = 12 Const LAG_SIZE As Long = 600 Dim minValue As Double Dim maxValue As Double Dim lagCounter As Long Dim ix As Long Dim elementValue As Double Dim elementSum As Double Dim numElements As Double Dim elementAverage As Double For lagCounter = 1 To NUM_LAGS minValue = (lagCounter - 1) * LAG_SIZE maxValue = (lagCounter * LAG_SIZE) - 1 numElements = 0 elementSum = 0 For ix = LBound(dataArray, 1) To UBound(dataArray, 1) elementValue = dataArray(ix, 1) If elementValue >= minValue And elementValue <= maxValue Then numElements = numElements + 1 elementSum = elementSum + elementValue End If Next ix elementAverage = elementSum / numElements Cells(lagCounter, 5) = elementAverage Next lagCounter Application.ScreenUpdating = True Application.EnableEvents = True Application.Calculation = xlCalculationAutomaticEnd SubThat alone should take your runtime from 1/2 an hour to a couple of seconds (if that). |
_unix.128534 | I'm using Ubuntu 14.04, and the cron daemon is running:# ps ax | grep cron822 ? Ss 0:00 cronbut it is not executing any jobs. I was previously getting entries in /var/log/syslog such as this:2014-05-04T11:47:01.839754+01:00 localhost CRON[29253]: (root) CMD (test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ))but now there are no cron-related entries. I was also getting entries like this in /var/log/auth.log:2014-05-04T11:47:01.839183+01:00 localhost CRON[29252]: pam_unix(cron:session): session opened for user root by (uid=0)2014-05-04T11:47:13.495691+01:00 localhost CRON[29252]: pam_unix(cron:session): session closed for user rootbut again, now there are no cron-related entries.I am not aware that anything has changed. I have tried restarting cron:# service cron restartcron stop/waitingcron start/running, process 24907I tried using crontab -e to add a cron job * * * * * date >> /tmp/somefile which worked, but it installed a new crontab in /var/spool/cron/crontabs/root, whereas I want cron to use the file in /etc/crontab.Is there any debug option I can use, or a log somewhere that might give an error message that I can investigate? | How do I find out why cron is not running my jobs? | ubuntu;cron | null |
_unix.387383 | I use Barman 1.5.1 on Ubuntu 16.04.For several weeks, barman has been working smoothly. Some days ago, troubles started:Instead of backups I find other files in the <SERVER>/base/ directory of some of the backups (e.g. autoselect.h in .../base/20170816T230003 and fcall.hpp, parameterized.hpp, parser_binder.hpp in .../base/20170805T230003). Strangely, most of the other backups are fine.barman check <SERVER> yieldsPostgreSQL: OKarchive_mode: OKwal_level: OKarchive_command: OKcontinuous archiving: FAILEDdirectories: OKretention policy settings: OKbackup maximum age: FAILED (interval provided: 1 day, latest backup age: 6 days, 12 hours, 41 minutes)compression settings: OKminimum redundancy requirements: OK (have 6 backups, expected at least 0)ssh: OK (PostgreSQL server)not in recovery: OKAccording to sourceforge the second issue (2.) can be fixed by a barman update. Unfortunately, the latest version of barman in the repository is 1.5.1. How can I safely upgrade barman to a version > 1.5.1? Is this likely to solve the first problem (1.), too? | Barman >1.5.1 for Ubuntu 16.04 | ubuntu;apt;upgrade | null |
_codereview.19401 | Please help me to make more readable and simple code like this. What if I had 20 components? Is it right to organize code like this?package newpackage.view;import java.awt.GridLayout;import javax.swing.JButton;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JRadioButton;import javax.swing.JTextField;public class UserPanel extends JPanel{ private JLabel idLbl; private JLabel nameLbl; private JLabel passwordLbl; private JRadioButton adminRad; private JRadioButton userRad; private JTextField idFld; private JTextField nameFld; private JPasswordField passwordFld; private JButton submitBtn; public UserPanel() { setLayout(new GridLayout(4,2)); idLbl = new JLabel(ID); nameLbl = new JLabel(Name); passwordLbl = new JLabel(Password); adminRad = new JRadioButton(Admin); userRad = new JRadioButton(User); idFld = new JTextField(); nameFld = new JTextField(); passwordFld = new JPasswordField(); submitBtn = new JButton(Submit); add(idLbl); add(idFld); add(nameLbl); add(nameFld); add(passwordLbl); add(passwordFld); add(adminRad); add(userRad); add(submitBtn); }} | Readable code with many components (Swing) | java;swing;gui | Depending on your application structure, there are several ways to organize this.If you have only this window with small number of components, just use add(new Compenent(...)) as Roman Ivanov suggested.If you have to communicate a bit and have more Frames and more logic behind it, you could pick some of this bullet points:Do not extend JPanel, instead have a private JPanel attribute and deal with it (Encapsulation). There is no need to give access to all JPanel methods for code dealing with a UserPanel instance. If you extend, you are forced to stay with this forever, if you encapsulate, you can change whenever you want without taking care of something outside the class.Use a create() method to init the GUI (or createAndGet() if you need a reference). In this way you make it clear what happens there. The GUI is created. It is not obvious if this happens in the constructor.Some of your attribute names look like you want to do something with them later on. So you will probably need listeners. You can add a addListeners() method which takes care about all the listeners.If your init method still has too much work inside, you could split it up (like createFirstPanel(), createUserField(), createPlots() and so on).Think about a cleaning up method/way. Do you want to destroy the window, reuse the window, clear the window? Have a single instance, multiple instances? You can handle all the different cases inside the class if you use encapsulation (and probably inside the controller, depends on your application model).Use good names. Do not abbreviate Label with Lbl. Write Label. It is better readable and with auto completion, no more work to write. I would suggest to put the type before the name, like jLabelId, jLabelName, jTextFieldName, ... This is more consistent.Just to say it again: If it is just a small class and no one will touch it ever again, use the easiest approach possible. Do not code for a future which is not clearly visible. |
_webmaster.52914 | What could be causing a 1.18s wait time when my page loads?Just to make sure I did not have any conflicting or parallel scripts loading, I completely deleted all the script on my home page and ran the speed test again. Although I had a blank website and 5kb file size, there was still a 900ms waiting time.I'm wondering if it could be my server? Any other thoughts or suggestions as it doesn't seem to be scripts.EDIT - Just ran a DNS test on pingdom and here are my results. Does this tell me anything? No nameservers found at child? | What could be causing this long waiting time on page load? | javascript;page speed | null |
_codereview.18009 | I am developing a BlackJack game using Java, and it came to a point that I am using instanceof operator to determine if it is a type of some subclass.Here's an example:public void checkForBlackJack(Player player) { Hand fHand = player.getHands().get(0); if (fHand.getCardScore() == 21) { fHand.setBlackjack(true); } if(player instanceof BlackJackPlayer){ BlackJackPlayer bjplayer = (BlackJackPlayer) player; if(bjplayer.isSplit()){ //Check the users other hand if it is already blackjacked } } }Is using instanceof considered to be bad for such example? Just as an overview, here is my class diagram:I've decided to use instanceof to check for blackjack because The Dealer can also get blackjack. | Using Java's instanceof operator | java;design patterns;playing cards | null |
_unix.290283 | I am fairly new to the Linux OS. I'm being asked to learn the OS (Ubuntu & Fedora) for computational science purposes.The problem isn't getting involved or into the OS, but I don't exactly know what path to take in terms of delving deep. So far I've played around with the Terminal (e.g. issuing commands to create basic FORTRAN or C++ files, moving, deleting, copying, creating directories).I feel all of this is basic and that I'm missing so much more. I've searched online for various documentations, but I feel at a loss because I don't understand what path I am supposed to be taking. I would really appreciate any help. | New Linux User, Where do I begin and how do I master the OS | linux;ubuntu | null |
_softwareengineering.313090 | Was doing some reading today about Razor Syntax with MVC Framework and was wondering why would/should I use Razor? What benefit does it provide over doing the same thing in the code behind and/or controller? As an example I saw, they showed how you can use Razor to display the current time, doing arrays and loops, and other functions using inline coding right there within the HTML. Wouldn't this provide excess clutter to the front end that can easily be provided with the code behind? | Why use Razor Syntax? | c#;asp.net mvc;clean code;razor | More generally, you are asking about the benefits of using a template rather than generating content directly inside your source code.The answer is that mixing source code and HTML could be a viable alternative for small applications, but doesn't scale well. Once your project becomes large enough, it becomes too difficult to maintain code where chunks of HTML are all over the source code.Using a template solves this issue. All your logic resides in controllers, while HTML is put in templates, which, in MVC, are called views. When someone wants to modify HTML, there is no need to deal with the business logic: only the view is affected. It might also work the other way around: you can swap the logic while letting HTML unchanged (as soon as the models remain the same).So if templates are for HTML, what's all this source code in Razor?!Indeed, you still need some logical statements within your templates, usually in a form of conditions or loops. If you need to display an avatar of a person only when the person actually has an avatar, well, that's a good place for an if in your template. If you need to display every product which was provided by the controller through the model, there would be a foreach.The fact that you can write any code within your views doesn't mean you should. Be careful to keep business logic inside controllers. A few conditions and loops is fine, but if the code in your views becomes too complicate, it's a good sign that you've done too much. So:All business logic should be in controllers (or business classes called by the controllers, depending on the N-tier architecture you use and the complexity of your application).The models contain simple objects (usually POCO) which can be used easily, without too much code.The views contain only the most elementary logic needed exclusively to generate HTML from the model. No complex business logic here. |
_softwareengineering.246498 | I have been reading a number of posts and I am leaning towards building an SOA. My main dependencies are:Need to support multiple clientsNeed individual client environments to not effect other client environmentsFor example, if I want to add a text field to Client A's application, but I don't want Client B to be effected in any way.The solution I have is to send an API address along with the client auth token. For example, the client will send something like this:api: http://myWebsite/api/clients/ClientA/someServiceCallSimilarly, from a token, the (MVC) controller will know which view to render for a given user.My question is, is this a good solution to my problem? I understand that I am having to call an HTTP REST service for my data access; but, I feel this solves a lot of problems. For instance, I could see which services sending 404 errors and fix them (presumably) before they even get reported.I have read a number of articles that seem to enforce my idea. Have I misunderstood this concept? Is there a better architectural approach?Here's what I've been reading:Dogfooding: how to build a great APIShould a website use its own public API?Stevey's Google Platforms RantAgain, the goal is to keep individual client environments as separate as possible; such that if we push a change to the service layer, there is no downtime and no one gets logged out because of an app pool refresh.My over all plan is to incorporate these API calls wherever they are needed; i.e. in an MVC controller or a javascript AJAX call. For example:public class HomeController : Controller{ public ActionResult Index() { WebClient client = new WebClient(); string api = /* api from auth token */ User result = JsonConvert.DeserializeObject<User>(client.DownloadString(api)); return View(result); }} | Multitier architecture using API | architecture;rest;asp.net mvc;soa | null |
_webmaster.17600 | I've been pulling my hair out but can't figure out why my page looks like a huge mess in IE9, but Firefox, Chrome, Opera, Safari works great.My website is here:http://173.244.195.179/test-o.htmlCould anyone tell me what I'm doing that isn't compatible with IE9? | Why can't Internet Explorer render this page correctly? | html;css;internet explorer | Looking at your source code, you have a couple of serious issues:<script language=javascript type='text/javascript'> ...</script><!DOCTYPE html><html><head>You have a script tag at the very top of your page. They should go inside the head tags. Which leads me to the next issue:<!DOCTYPE html><html><head>...</head><body><head>...</head><body>You have two <head> tags, and two opening <body> tags. This should be replaced with:<!DOCTYPE html><html><head>...</head><body>...</body></html> |
_cs.55375 | In an algorithm book it said that to solve the coin denomination problem via Dynamic Programming approach a 2-D array is needed:Exercises 8.4 #9Is it not possible to do this using a 1-D array.I was thinking that maybe you could set the $C$ values in a 1-D array as:$C[0]=0$, $C[n]=1$ if $n$ is one of the denomination values and $C[n]= \infty$ if $n$ is less that the least denomination.Otherwise set $C[n] = \min_{1 <= i <= \frac{n}{2}}{(C[i]+C[n-i])}$What is wrong with my solution other than I won't be able to generate the actual solution because my goal is only to find the optimal number of coins for that $n$ value? | Is it possible to solve the coin denomination problem using a 1-D array? | algorithms;optimization;dynamic programming | null |
_webmaster.90684 | I created web site and from computer it works. But we have problem on android google chrome. errorYour connection is private ERR_CERT_DATE_INVALID.any idea? please help. | Can't open website on Android chrome | security certificate;google chrome;android | null |
_codereview.105953 | Recently, I added this class to my Spiky engine: its basic purpose is to allocate OpenGL-based objects (such as Textures, Shader, Fonts, ...) and then manage them by giving them an ID so the user can pull objects in and out. Any remarks, suggestions or other comments are welcome.Resourcemanager.h:#pragma once#include <memory>#include <vector>#include <unordered_map>#include ../render/Shader.h#include ../render/Mesh.h#include ../render/Texture.h#include ../render/Font2D.hnamespace Spiky{ class ResourceManager; void inline InitSpikyCore(); class ShaderImp { public: friend class ResourceManager; friend std::unique_ptr<ShaderImp>::deleter_type; std::unique_ptr<glDetail::CShader> const& operator->() const { return m_shader; } private: explicit ShaderImp(const char* vs, const char* fs) : m_shader(std::make_unique<glDetail::CShader>(vs, fs)) { } explicit ShaderImp(const char* vs, const char* fs, const char* gs) : m_shader(std::make_unique<glDetail::CShader>(vs, fs, gs)) { } ~ShaderImp() { } std::unique_ptr<glDetail::CShader> m_shader; }; typedef ShaderImp const& Shader; class MeshImp { public: friend class ResourceManager; friend std::unique_ptr<MeshImp>::deleter_type; std::unique_ptr<glDetail::CMesh> const& operator->() const { return m_mesh; } private: explicit MeshImp(Vertex* vertices, unsigned int numVertices, unsigned int* indeces, unsigned int numIndices) : m_mesh(std::make_unique<glDetail::CMesh>(vertices, numVertices, indeces, numIndices)) { } explicit MeshImp(const char* fileName) : m_mesh(std::make_unique<glDetail::CMesh>(fileName)) { } ~MeshImp() { } std::unique_ptr<glDetail::CMesh> m_mesh; }; typedef MeshImp const& Mesh; class TextureImp { public: friend class ResourceManager; friend std::unique_ptr<TextureImp>::deleter_type; std::unique_ptr<glDetail::CTexture> const& operator->() const { return m_texture; } private: explicit TextureImp(const char* texturePath, GLenum texTarget = GL_TEXTURE_2D, GLfloat filter = GL_LINEAR, GLfloat pattern = GL_REPEAT, GLenum attachment = GL_NONE) : m_texture(std::make_unique<glDetail::CTexture>(texturePath, texTarget, filter, pattern, attachment)) { } explicit TextureImp(int width = 0, int height = 0, unsigned char* data = 0, GLenum texTarget = GL_TEXTURE_2D, GLfloat filter = GL_LINEAR, GLfloat pattern = GL_REPEAT, GLenum attachment = GL_NONE) : m_texture(std::make_unique<glDetail::CTexture>(width, height, data, texTarget, filter, pattern, attachment)) { } ~TextureImp() { } std::unique_ptr<glDetail::CTexture> m_texture; }; typedef TextureImp const& Texture; //Inmplement Shader, Mesh, Texture, ... allocators here : class ResourceManager { friend inline void SpikyInitCore(); public: using ShaderRepo = std::unordered_map<const char*, std::unique_ptr<ShaderImp>>; using MeshRepo = std::unordered_map<const char*, std::unique_ptr<MeshImp>>; using TextureRepo = std::unordered_map<const char*, std::unique_ptr<TextureImp>>; //Shader static const ShaderImp& LoadShader(const char* ID, const char* vs, const char* fs) { shaderObjects.insert(std::pair<const char*, std::unique_ptr<ShaderImp>>(ID, std::unique_ptr<ShaderImp>(new ShaderImp( (shaderRootDir + std::string(vs)).c_str(), (shaderRootDir + std::string(fs)).c_str())))); return *(shaderObjects.at(ID).get()); } static const ShaderImp& LoadShader(const char* ID, const char* vs, const char* fs, const char* gs) { shaderObjects.insert(std::pair<const char*, std::unique_ptr<ShaderImp>>(ID, std::unique_ptr<ShaderImp>(new ShaderImp( (shaderRootDir + std::string(vs)).c_str(), (shaderRootDir + std::string(fs)).c_str(), (shaderRootDir + std::string(gs)).c_str())))); return *(shaderObjects.at(ID).get()); } static const ShaderImp& GetShader(const char* ID) { return *(shaderObjects.at(ID).get()); } //Mesh static const MeshImp& LoadMesh(const char* ID, Vertex* vertices, unsigned int numVertices, unsigned int* indeces, unsigned int numIndices) { meshObjects.insert(std::pair<const char*, std::unique_ptr<MeshImp>>(ID, std::unique_ptr<MeshImp>(new MeshImp( vertices, numVertices, indeces, numIndices)))); return *(meshObjects.at(ID).get()); } static const MeshImp& LoadMesh(const char* ID, const char* fileName) { meshObjects.insert(std::pair<const char*, std::unique_ptr<MeshImp>>(ID, std::unique_ptr<MeshImp>(new MeshImp( (meshRootDir + std::string(fileName)).c_str())))); return *(meshObjects.at(ID).get()); } //Texture static const TextureImp& LoadTexture(const char* ID, const char* texturePath, GLenum texTarget = GL_TEXTURE_2D, GLfloat filter = GL_LINEAR, GLfloat pattern = GL_REPEAT, GLenum attachment = GL_NONE) { textureObjects.insert(std::pair<const char*, std::unique_ptr<TextureImp>>(ID, std::unique_ptr<TextureImp>(new TextureImp( (textureRootDir + std::string(texturePath)).c_str(), texTarget, filter, pattern, attachment)))); return *(textureObjects.at(ID).get()); } static const TextureImp& LoadTexture(const char* ID, int width, int height, unsigned char* data = nullptr, GLenum texTarget = GL_TEXTURE_2D, GLfloat filter = GL_LINEAR, GLfloat pattern = GL_REPEAT, GLenum attachment = GL_NONE) { textureObjects.insert(std::pair<const char*, std::unique_ptr<TextureImp>>(ID, std::unique_ptr<TextureImp>(new TextureImp( width, height, data, texTarget, filter, pattern, attachment)))); return *(textureObjects.at(ID).get()); } static const TextureImp& LoadTextureCustomPath(const char* ID, const char* texturePath, GLenum texTarget = GL_TEXTURE_2D, GLfloat filter = GL_LINEAR, GLfloat pattern = GL_REPEAT, GLenum attachment = GL_NONE) { textureObjects.insert(std::pair<const char*, std::unique_ptr<TextureImp>>(ID, std::unique_ptr<TextureImp>(new TextureImp( texturePath, texTarget, filter, pattern, attachment)))); return *(textureObjects.at(ID).get()); } static const TextureImp& GetTexture(const char* ID) { return *(textureObjects.at(ID).get()); } private: static ShaderRepo shaderObjects; static MeshRepo meshObjects; static TextureRepo textureObjects; static std::string shaderRootDir; static std::string meshRootDir; static std::string textureRootDir; };}ResourceManager.cpp:#include ../core/ResourceManager.hnamespace Spiky{ ResourceManager::ShaderRepo ResourceManager::shaderObjects = ShaderRepo(); ResourceManager::MeshRepo ResourceManager::meshObjects = MeshRepo(); ResourceManager::TextureRepo ResourceManager::textureObjects = TextureRepo(); ResourceManager::Font2DRepo ResourceManager::font2DObjects = Font2DRepo(); std::string ResourceManager::shaderRootDir = std::string(assets/shaders/); std::string ResourceManager::meshRootDir = std::string(assets/models/); std::string ResourceManager::font2DRootDir = std::string(assets/fonts/); std::string ResourceManager::textureRootDir = std::string(assets/images/);} | Allocating and managing OpenGL-based objects | c++;c++11;graphics | Don't Repeat YourselfConsider ShaderImp, MeshImp, TextureImp. They all have the exact same structure: they befriend ResourceManager, hold onto some std::unique_ptr, which is exposable, and are privately constructible. When you see that kind of repetition in class definitions, that calls for a class template:template <typename T>class GenericImp{public: friend class ResourceManager; friend typename std::unique_ptr<T>::deleter_type; std::unique_ptr<T> const& operator->() const { return ptr_; } // might as well also provide this one T const& operator*() const { return *ptr_; }private: template <typename... U, typename = std::enable_if_t<std::is_constructible<T, U&&...>::value>> explicit GenericImpl(U&&... u) : ptr_{new T(std::forward<U>(u)...)} { } std::unique_ptr<T> ptr_;};That handles all the Imps:using ShaderImp = GenericImp<glDetail::CShader>;using MeshImp = GenericImp<glDetail::CMesh>;using TextureImp = GenericImp<glDetail::CTexture>;Don't Repeat Yourself IINow that we have our Imps, we need some maps to store them in:template <typename Imp>using Repo = std::unordered_map<std::string, std::unique_ptr<Imp>>;using ShaderRepo = Repo<ShaderImp>;...Note that having a const char* key type is highly questionable. Using std::string prevents you from having to deal with any lifetime issues. Don't Repeat Yourself IIILet's collapse all of our Loaders into a single function template. Because we can:template <typename Imp, typename Key, typename... Args>static const Imp& LoadImp(Repo<Imp>& map, Key&& key, Args&&... args){ auto it = map.emplace(std::forward<Key>(key), std::unique_ptr<Impl>(new Imp(std::forward<Args>(args)...)) ).first; return *(it->second);}Taking advantage of the fact that emplace() gives us where it was put in, we don't need to do the extra search. Now all the other loaders can just forward to that one, e.g.:template <typename... Args>static const ShaderImp& LoadShader(std::string const& ID, Args&&... args){ return LoadImp(shaderObjects, ID, (shaderRootDir + args)...);}Note that (shaderRootDir + std::string(vs)).c_str() gives you a dangling pointer so you should try to avoid that construct. Prefer std::strings.Don't Typedef Meaningless TypesWhen you introduces types like:typedef TextureImp const& Texture;That's confusing. The extra typedef adds no value. You could've just written TextureImp const&. It's not worth it. Also, you agree, since you don't actually use it anywhere yourself! |
_unix.188482 | In Vim, you can move a window to an edge of the viewport with H/J/K/L. Vim will make sure the window occupies the whole edge and resize/shift the other windows around it. Is there something similar for tmux? move-pane doesn't seem to have an option to preserve sizes like Vim does for you. rotate-pane is not the same behavior either and does not guarantee the pane will find the correct edge. | tmux command to move pane to edge of window? | tmux | null |
_webapps.28208 | I reported the following issue to Tumblr:I have setup Tumblr to post to Facebook as well. However, I have noticed that posts published from the queue do not appear in my Facebook timeline - only posts I publish directly. can this please be fixed?And this is the reply I received:Facebook has altered the way it displays information from Tumblr and other applications. While you should see some of your posts appearing in your newsfeed, not all posts will appear there. This is to keep applications from cluttering your Facebook newsfeed.Unfortunately, we can't control how Facebook displays content from Tumblr.This does not sound right to me: Tumblr would surely have been the author of a plugin - and failing to post to Facebook items that came from the queue does not sound like something on the Facebook side, but in the plugin. Is it possible that I am doing something wrong here?-edit-Why would Facebook discriminate between posts published from a queue and posts published directly? More importantly, HOW could they discriminate? Is this data provided by Tumblr to Facebook? Either way, this looks like a bug to me, and I believe it more likely that it's a bug on the Tumblr side and I am disappointed that Tumblr apparently will not even investigate. | Tumblr items published from queue do not show in Facebook timeline - only those items published directly | facebook;tumblr;facebook timeline;facebook apps | Even though @FelixBonkoski's ifttt seems good, I found my solution a different way: I had already set up Tumblr to publish automatically to Twitter.. And thankfully Twitter can publish to Facebook, and this seems to work well for me - for items published from the queue or directly. |
_cs.23407 | Let A = $(Q, \Sigma, \delta, S, F)$ be a deterministic finite automaton associated with the language $L \subseteq \Sigma^*$ $L' = \{y \in \Sigma^*:\exists x\in L. |x| = |y|\}$ $L \subseteq L'$How do I show that there exist a NDFA associated with L' ? | NDFA associated with language L | regular languages;finite automata;nondeterminism | Hint: Replace every transition labelled $a \in \Sigma$ with a transition labelled $\Sigma$. |
_webapps.97579 | At some point I disabled website link previews from YouTube in our Slack team. But this was a huge mistake, we need them back. How do I re-enable link previews for a specific website that was disabled, or for all websites?I have already disabled / re-enabled all preview types under Preferences > Messages & Media, but YouTube is still disabled. | How do I re-enable link previews in Slack? | slack | null |
_unix.314621 | I am trying to automate domain join on RedHat 7 using the following command:realm join -U serviceaccount --client-software=sssd abc.com The problem is this command prompts for password which stops my script. How do I workaround so it doesn't prompt for the password? I need a solution which will definitely work. | Join Redhat 7 without prompting the password | rhel;password;active directory;sssd | null |
_webmaster.39051 | A lot of developers place all image files inside a central directory, for example:/i/img//images//img/Isn't it better (e.g. content architecture, on-page SEO, code maintainability, filename maintainability, etc.) to place them inside the relevant directories in which they are used?For example:example.com/logo.jpgexample.com/about/photo-of-me.jpgexample.com/contact/map.pngexample.com/products/category1-square.pngexample.com/products/category2-square.pngexample.com/products/category1/product1-thumb.jpgexample.com/products/category1/product2-thumb.jpgexample.com/products/category1/product1/product1-large.jpgexample.com/products/category1/product1/product2-large.jpgexample.com/products/category1/product1/product3-large.jpgWhat is the best practice here regarding all possible considerations (for static non-CMS websites)?N.B. The names product1-large and product1-thumb are just examples in this context to illustrate what kind of images they are. It is advised to use descriptive filenames for SEO benefit. | Convenient practice for where to place images? | seo;images;best practices;architecture;filenames | I personally use a bit of both... I place all the images with a general purposes (things like : design, icons, site content, sprites, etc..) in a single directory.Then for everything related to a single thing on my website, by example a .jpg avatar related to a single user, I put that in a specific directory but inside of a centralized structure.. something like this :/data/users/1/avatar.jpg/data/users/2/avatar.jpg/data/articles/1/main_picture.jpgAt first there is the data directory, it's a good idea to have a main directory like that because when comes the time where you want to do urlRewriting like that : http://mywebsite.com/users/1/, that will confuse everything as the directory already exists on the server root... so putting everything in a centralized directory prevents that.Also note that I don't use product's name or category's name in the sub-directories, I prefer to use IDs as it's more optimized and simple to use.I can't prove this is the best structures considering SEO, but it's the best structure that I've experienced and I can say it's the most extensible because everything is placed in a logical way in a point of view of object oriented programming. If you want to add a personalized profile song for every site's users, fine ! You already have the structure right there, no need to add a new directory called songs/ and etc...And based on that structure, nothing prevents you from using some kind of urlRewriting to have URLs with the products/categories name in it, and then point to the IDs based structure on your server, that would be perfect I guess, but I've never tried...Hope it helps :) |
_unix.353065 | I would like to install Qubes OS on a 32GB USB Stick, and use it for Live Sessions. Is there a way in which I could have WiFi Connection during a Live Session without rebooting? (I use Lenovo Ideapad 310 14ISK).If so, does the procedure of WiFi Connection apply to the Qubes OS Live USB Option as well?What about the Terminal option of: echo blacklist ideapad-laptop | sudo tee /etc/modprobe.d/ideapad-laptop.conf ?Thank you. | How to connect to WiFi on Qubes OS Live Session/Live USB? | wifi;qubes | null |
_unix.89551 | I would like to change the PATH of my Debian 7.1.0 system to link the java version I want. If I insert into the terminal:java -versionI get:java version 1.6.0_27OpenJDK Runtime Environment (IcedTea6 1.12.6) (6b27-1.12.6-1~deb7u1)OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)This is the java version preinstalled by my distribution. I have now downloaded the SUN JDK 1.7.0 update 25. I would like my system to use this version instead of the preinstalled version. I have made to changes to my PATH in .bashrc but I have the same java version. My .bashrc file has the line:PATH=PATH:/usr/local/jdk1.7.0_25export PATH | Change PATH in Debian 7.1.0 for JAVA | debian;path;java | What you actually want is this in your ~/.profile (or .bashrc if you insist, but .profile is better):PATH=$PATH:/usr/local/jdk1.7.0_25/binexport PATHYou were losing the original $PATH because you were using PATH instead of $PATH so it was interpreted as a simple string and all you were doing is setting your path to:PATH:/usr/local/jdk1.7.0_25/bin |
_vi.2875 | Is there anything I can do to keep syntax on when using Vim?As soon as I open anything substantial it becomes nearly impossible to edit after a while. Every keypress causes a delay. If I turn syntax highlighting off or relaunch vim it is fine again.I have synmaxcol set to 120. Sample ruby file is only 59 lines long and not exceeding 80 characters.I am using vim-ruby and vim-rails.The problem is that the delay seem to accumulate over time. When I open the file from scratch it is fine. After a while it gets slower and slower. | Vim slows down over time with syntax on | syntax highlighting;performance | Recent Vim versions have a :syntime command to troubleshoot slowness of syntax highlighting by generating a report of how long each syntax group takes to match. This is very helpful and quickly lets you find the culprit; the only downside is that you need a (usually HUGE) build of Vim with profiling enabled. :help :syntime provides good instructions how to employ it.Alternatively, you can try removing individual syntax scripts from ~/.vim/syntax/ and $VIMRUNTIME/syntax/ (according to the current 'filetype'), and then further drill down by removing parts of the syntax definitions inside the script. |
_codereview.32653 | I created a function that compares an array of letters to the alphabet, and returns the letters that are not in the original array.While this works, it looks somewhat clumsy to me, but I don't know what I'm looking for to improve the code...Is there a way to make it more elegant? Perhaps getting rid of the notPresent array somehow?getLettersNotInContent(['z', 'a', 'p']);function getLettersNotInContent(letters) { // Filter dups if present var uniques = []; letters.filter(function(letter) { if (uniques.indexOf(letter) === -1) { uniques.push(letter); } }); // Filter and return the letters that are not present in the content var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p','q','r','s','t','u','v','w','x','y','z']; var notPresent = []; alphabet.filter(function(letter) { if (uniques.indexOf(letter) === -1) notPresent.push(letter); }); return notPresent;} | Improving a JavaScript filtering function | javascript | You're mixing up two different ways of doing this. The old-fashioned way involves looping through the alphabet and pushing the letters not present into an array:function getLettersNotInContent2(letters) { var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; var notPresent = []; for (var i = 0; i < alphabet.length; i++) { if (letters.indexOf(alphabet[i]) === -1) notPresent.push(alphabet[i]); } return notPresent;}The newer way (more elegant but not supported in IE8) uses the filter method with a function that returns true or false:function getLettersNotInContent3(letters) { var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; return alphabet.filter(function (letter) { return letters.indexOf(letter) === -1 });}Your code happens to work because, under the hood, filter also loops through the values of an array in turn. But you're not using it in the intended way.(In both cases I removed the filtering out of duplicates as this seems unnecessary.) (jsfiddle) |
_codereview.1070 | As far as I know the standard Delegate.CreateDelegate() which allows to create a delegate by using reflection, doesn't allow doing something as follows when the first parameter of method isn't exactly of type object.public class Bleh{ public void SomeMethod( string s ) { }}...object bleh = new Bleh(); MethodInfo method = bleh.GetType().GetMethod(SomeMethod); // Starting from here, all knowledge about Bleh is unknown. // Only bleh and method are available.Action<object> a = (Action<object>)Delegate.CreateDelegate( typeof( Action<object> ), bleh, method );Which is why I now have an implementation which allows the following:Action<object> compatibleExecute = DelegateHelper.CreateCompatibleDelegate<Action<object>>( bleh, method );method can be any method, with or without return type, and with as many parameters as desired. I need to create an Action<T>, since other code is dependant on this strong typed delegate.In this example, I know the method is at least an Action<object>.The following code improves on the original CreateDelegate in two ways:It is generic now, instead of passing type as a first parameter.It does conversion to suitable lower types when possible.This is the first time for me working with expression trees, so I don't know whether what I'm doing is correct or the best approach. I based this implementation on an article by Jon Skeet (without fully understanding it :)), but the code seems to be working!/// <summary>/// A generic helper class to do common/// <see cref = System.Delegate>Delegate</see> operations./// </summary>/// <author>Steven Jeuris</author>public static class DelegateHelper{ /// <summary> /// The name of the Invoke method of a Delegate. /// </summary> const string InvokeMethod = Invoke; /// <summary> /// Get method info for a specified delegate type. /// </summary> /// <param name = delegateType>The delegate type to get info for.</param> /// <returns>The method info for the given delegate type.</returns> public static MethodInfo MethodInfoFromDelegateType( Type delegateType ) { Contract.Requires<ArgumentException>( delegateType.IsSubclassOf( typeof( MulticastDelegate ) ), Given type should be a delegate. ); return delegateType.GetMethod( InvokeMethod ); } /// <summary> /// Creates a delegate of a specified type that represents the specified /// static or instance method, with the specified first argument. /// Conversions are done when possible. /// </summary> /// <typeparam name = T>The type for the delegate.</typeparam> /// <param name = firstArgument> /// The object to which the delegate is bound, /// or null to treat method as static /// </param> /// <param name = method> /// The MethodInfo describing the static or /// instance method the delegate is to represent. /// </param> public static T CreateCompatibleDelegate<T>( object firstArgument, MethodInfo method ) { MethodInfo delegateInfo = MethodInfoFromDelegateType( typeof( T ) ); ParameterInfo[] methodParameters = method.GetParameters(); ParameterInfo[] delegateParameters = delegateInfo.GetParameters(); // Convert the arguments from the delegate argument type // to the method argument type when necessary. ParameterExpression[] arguments = (from delegateParameter in delegateParameters select Expression.Parameter( delegateParameter.ParameterType )) .ToArray(); Expression[] convertedArguments = new Expression[methodParameters.Length]; for ( int i = 0; i < methodParameters.Length; ++i ) { Type methodType = methodParameters[ i ].ParameterType; Type delegateType = delegateParameters[ i ].ParameterType; if ( methodType != delegateType ) { convertedArguments[ i ] = Expression.Convert( arguments[ i ], methodType ); } else { convertedArguments[ i ] = arguments[ i ]; } } // Create method call. ConstantExpression instance = firstArgument == null ? null : Expression.Constant( firstArgument ); MethodCallExpression methodCall = Expression.Call( instance, method, convertedArguments ); // Convert return type when necessary. Expression convertedMethodCall = delegateInfo.ReturnType == method.ReturnType ? (Expression)methodCall : Expression.Convert( methodCall, delegateInfo.ReturnType ); return Expression.Lambda<T>( convertedMethodCall, arguments ).Compile(); }}So, did I do this the easiest/best way? Am I doing something completely unnecessary? Thanks! | Generic advanced Delegate.CreateDelegate using expression trees | c#;expression trees | By applying some extra LINQ 4.0 Zip magic, I was able to reduce the code to the following. Anyone sees any more improvements? IMHO this is already a bit clearer.public static T CreateCompatibleDelegate<T>( object instance, MethodInfo method ){ MethodInfo delegateInfo = MethodInfoFromDelegateType( typeof( T ) ); var methodTypes = method.GetParameters().Select( m => m.ParameterType ); var delegateTypes = delegateInfo.GetParameters().Select( d => d.ParameterType ); // Convert the arguments from the delegate argument type // to the method argument type when necessary. var arguments = methodTypes.Zip( delegateTypes, ( methodType, delegateType ) => { ParameterExpression delegateArgument = Expression.Parameter( delegateType ); return new { DelegateArgument = delegateArgument, ConvertedArgument = methodType != delegateType ? (Expression)Expression.Convert( delegateArgument, methodType ) : delegateArgument }; } ).ToArray(); // Create method call.; MethodCallExpression methodCall = Expression.Call( instance == null ? null : Expression.Constant( instance ), method, arguments.Select( a => a.ConvertedArgument ) ); // Convert return type when necessary. Expression convertedMethodCall = delegateInfo.ReturnType == method.ReturnType ? (Expression)methodCall : Expression.Convert( methodCall, delegateInfo.ReturnType ); return Expression.Lambda<T>( convertedMethodCall, arguments.Select( a => a.DelegateArgument ) ).Compile();}At first I got the dreaded variable .. of type ... referenced from scope '' but it is not defined. exception, but after some pondering I realized I had to add ToArray() after the Zip() statement to make sure the delegate arguments would already be defined. Powerful stuff this deferred execution, but apparently also a source for errors. I got the same exception when running smartcaveman's latest update, which is perhaps due to a similar mistake.Writing a custom Zip which takes three arguments removes the need of the anonymous type. Writing the Zip is really easy, as documented by Jon Skeet.public static T CreateCompatibleDelegate<T>( object instance, MethodInfo method ){ MethodInfo delegateInfo = MethodInfoFromDelegateType( typeof( T ) ); var methodTypes = method.GetParameters().Select( m => m.ParameterType ); var delegateTypes = delegateInfo.GetParameters().Select( d => d.ParameterType ); var delegateArguments = delegateTypes.Select( Expression.Parameter ).ToArray(); // Convert the arguments from the delegate argument type // to the method argument type when necessary. var convertedArguments = methodTypes.Zip( delegateTypes, delegateArguments, ( methodType, delegateType, delegateArgument ) => methodType != delegateType ? (Expression)Expression.Convert( delegateArgument, methodType ) : delegateArgument ); // Create method call. MethodCallExpression methodCall = Expression.Call( instance == null ? null : Expression.Constant( instance ), method, convertedArguments ); // Convert return type when necessary. Expression convertedMethodCall = delegateInfo.ReturnType == method.ReturnType ? (Expression)methodCall : Expression.Convert( methodCall, delegateInfo.ReturnType ); return Expression.Lambda<T>( convertedMethodCall, delegateArguments ).Compile();} |
_codereview.61590 | This is my solution to this SO question, which can formulated astake the sequence A002260, i.e., 1, 1, 2, 1, 2, 3, ...concatenate all its digitsfind the digit at a given position (1-based)]What bothers me is that my solution is rather complicated and fails near Long.MAX_VALUE due to overflow. I also wonder if this could be done in an error-proof way, since I ran through quite some off by one errors.There's the code, a test and a demo.public class Ogen { /** The length of the number {@code n} (in decimal representation) */ int length(long n) { return LongMath.log10(n, RoundingMode.DOWN) + 1; } /** * The total number of digits in the sequence {@code 1, 2, ..., n}, i.e., * the sum of {@code length(i)} of all positive {@code i} up to and including {@code n}. * */ long cumulativeLength(long n) { if (n==0) return 0; long result = 0; final int maxLength = length(n); for (int numberLength=1; numberLength<=maxLength; ++numberLength) { // all numbers between min and max have the length numberLength final long min = LongMath.pow(10, numberLength-1); // 1, 10, 100, ... highest power of 10 not greater than n final long max = Math.min(10*min - 1, n); // 9, 99, 999, ..., n final long countOfDifferentNumbers = max - min + 1; result += numberLength * countOfDifferentNumbers * 1; } return result; } /** * The total number of digits in the sequence {@code 1, 1, 2, 1, 2, 3, ..., 1, ..., n}, i.e., * the sum of {@code cumulativeLength(i)} of all positive {@code i} up to and including {@code n}. */ long doublyCumulativeLength(long n) { if (n==0) return 0; long result = 0; final int maxLength = length(n); for (int numberLength=1; numberLength<=maxLength; ++numberLength) { // all numbers between min and max have the length numberLength final long min = LongMath.pow(10, numberLength-1); // 1, 10, 100, ... highest power of 10 not greater than n final long max = Math.min(10*min - 1, n); // 9, 99, 999, ..., n final double avg = 0.5 * (min+max); final double averageNumberOfOccurrences = n - avg + 1; final long countOfDifferentNumbers = max - min + 1; result += numberLength * countOfDifferentNumbers * averageNumberOfOccurrences; } return result; } /** * The biggest number {@code n} such that the sequence {@code 1, 1, 2, 1, 2, 3, ..., 1, ..., n} ends before * position {@code pos}, i.e., such that {@code doublyCumulativeLength(n) < pos}. */ long fullSequenceBefore(long pos) { long lo = 0; // find upper bound long hi = (long) (Math.sqrt(pos)) / 2; while (doublyCumulativeLength(hi) < pos) { lo = hi; hi += 1 + (hi >> 4); } // binary search while (hi>lo+1) { final long mid = (hi+lo) / 2; if (doublyCumulativeLength(mid) >= pos) { hi = mid; } else { lo = mid; } } assert doublyCumulativeLength(lo) < pos; assert doublyCumulativeLength(lo+1) >= pos; return lo; } public char digitAt(long pos) { pos -= doublyCumulativeLength(fullSequenceBefore(pos)); long lo = 0; long hi = pos; while (hi>lo+1) { final long mid = (hi+lo) / 2; if (cumulativeLength(mid) >= pos) { hi = mid; } else { lo = mid; } } pos -= cumulativeLength(lo); return String.valueOf(lo+1).charAt((int) pos - 1); }} | Determining a digit on a given position in the A002260 sequence | java | Frankly I have been staring at the code for ... 20 minutes, and I can't figure out your algorithm. I can't even throw out a good guess as to whether the result is right, or not.There are some style-related issues that do not help:Cumulative is not spelled with 2 m's, and no e as you have it in doublyCummulativLengthThe self-referential comments are not useful if you can't figure out where the logic/code should start from. Building up on the algorithm would be more possible if the right starting point was given. In other words, your comments assume too much about what people reaing your code will know (or otherwise I am too dumb to see the obvious stuff so the comments are not helping me).You reference the class LongMath but that class is not included in the code.Your comments mention things like: // ... and occur on the average count2/2 times What does that mean? How can you be accurate to an exact digit with reasoning like that?Code like: final long count2 = 2*n - (min+max) + 2; result += i * (max-min+1) * count2 / 2;makes little, or no sense to me. count2? What does that mean? max and min are not great either. Lots of constants too.In general, the code is not primed for a sight-unseen review. I would need you sitting beside me so I can ask questions as I go through. That is not really suitable for Code review.As an aside, I believe having a class that represents the sequence that is being used would make a really big difference for this code. You need to extract out the class, and iterate it to find 'the spot'.I played around with this problem, and specifically targetted an overflow-safe solution, so that digitAt(Long.MAX_VALUE) will work. This is the code I have.Note that I use a class, which allows me to keep a state, and then add to the state.On my computer the test for digitAt(Long.MAX_VALUE) returns 4 in less than 2.5 seconds. I do not know if this is a good result, or not.Also, I compared my results with a naive implementation for relatively small values.Make of this what you will:import static org.junit.Assert.*;import org.junit.Test;public class Seq2260 { public static char digitAt(final long index) { if (index < 1) { throw new IllegalArgumentException(No such position + index); } Seq2260 sequence = new Seq2260(); sequence.incrementPast(index); // OK, spans have been added until the current span contains the index. // locate the actual digit in the current span. return sequence.seekChar(index - sequence.nextOffset); } // SCALES indicate the number of digits in each scale, and the value where the scale changes too. // for example, SCALES[1] are 1-digit values, and when you hit the value 10, you are no longer // in SCALES[1]. // SCALES[0] is only there to make the indexes line up. // The Long.MAX_VALUE is only there to make the range end. // Note that only Scales up to SCALES[9] will actually be used. // by the time you reach SCALES[10] (10,000,000,000) each number is 10 digits long // and the cumulative effect means that the index is now huge. private static final long[] SCALES = {0L, 10L, 100L, 1_000L, 10_000L, 100_000L, 1_000_000L, 10_000_000L, 100_000_000L, 1_000_000_000L, 10_000_000_000L, 100_000_000_000L, 1_000_000_000_000L, 10_000_000_000_000L, 100_000_000_000_000L, 1_000_000_000_000_000L, 10_000_000_000_000_000L, 100_000_000_000_000_000L, 1_000_000_000_000_000_000L, Long.MAX_VALUE }; //number of digits in a number private int scale = 1; // how far along the next span will start // start at 1 to be 1-based private long nextOffset=1; // how long the current span is. private long length = 0; // the last value in the span private long span = 0; private void incrementPast(final long index) { // this is an overflow-safe compare // nextOffset could hypothetically be a very small negative number (wrapped). The math // here is safe though, because a very large number subtract a very negative number // will overflow again and still be less than length. while (index - nextOffset >= length) { extendSpan(); } } private void extendSpan() { if (nextOffset < 0) { // we have previously overflowed our limit. We only support a single overflow. throw new IllegalStateException(Attempt to extend mapping beyond Long.MAX_VALUE); } span++; if (span == SCALES[scale]) { scale++; if (span == Long.MAX_VALUE) { throw new IllegalStateException(Overflowed Long in a span....); } } // for large values, this will overflow. That is the limit of where we can map to. // we can handle one overflow (a negative offset). After that, we fail. nextOffset += length; length += scale; } private char seekChar(long seek) { int sc = 1; long pos = 0; long val = 0; while (pos <= seek) { val++; if (val == SCALES[sc]) { sc++; } pos += sc; } // OK, so val includes the char, and it is.... int charfromright = (int)(pos - seek); String value = String.valueOf(val); return value.charAt(value.length() - charfromright); } public static void main(String[] args) { System.out.printf(Confirm %s is %s%n, Seq2260.digitAt(1000), + smallGet(1000)); System.out.printf(Confirm %s is %s%n, Seq2260.digitAt(10000), + smallGet(10000)); } @Test public void testNaieveMatch() { for (int i = 3; i < 64 * 1024; i += 19) { assertTrue(smallGet(i) == Seq2260.digitAt(i)); } } @Test public void testNaieveSequential() { for (int i = 1; i < 4 * 1024; i++) { assertTrue(smallGet(i) == Seq2260.digitAt(i)); } } private static char smallGet(int i) { StringBuilder sb = new StringBuilder(i + 10); sb.append(-); int oldmax = 1; int current = 0; while (sb.length() <= i) { current++; sb.append(current); if (current == oldmax) { current = 0; oldmax++; } } return sb.charAt(i); } @Test public void testGetDigitAt() { assertEquals('1', Seq2260.digitAt(1)); assertEquals('1', Seq2260.digitAt(2)); assertEquals('2', Seq2260.digitAt(3)); assertEquals('1', Seq2260.digitAt(4)); assertEquals('2', Seq2260.digitAt(5)); assertEquals('3', Seq2260.digitAt(6)); assertEquals('1', Seq2260.digitAt(7)); assertEquals('2', Seq2260.digitAt(8)); assertEquals('3', Seq2260.digitAt(9)); assertEquals('4', Seq2260.digitAt(10)); assertEquals('5', Seq2260.digitAt(20)); assertEquals('5', Seq2260.digitAt(33)); assertEquals('9', Seq2260.digitAt(54)); assertEquals('1', Seq2260.digitAt(55)); assertEquals('0', Seq2260.digitAt(56)); assertEquals('0', Seq2260.digitAt(67)); assertEquals('2', Seq2260.digitAt(99)); } @Test public void testLongMax() { assertEquals('4', Seq2260.digitAt(Long.MAX_VALUE)); }} |
_codereview.105531 | Here is an updated version of my Caesar Cipher script. I am looking for ways to improve it, make it more succinct, and expand it's features.I would eventually like to add text import and export features. Here it is with comments galore! ####Collin's Caesar Cipher: A Caesar Cipher by Word Length (V.2)#To import the lowercase alphabetimport string#Simple line break functiondef line_break(x): print -*x#setting up some variablesans = plainText = cipherText= alphabet = string.ascii_lowercase#Welcome User, Explain what script doesline_break(20)print Welcome to Caesar Cipher by Word LengthThis script takes words and phrasesand codes them by moving each individualletter up in the alphabet.\nThe amount the letters move is dependenton the length of the word.\nIf the word is three (3) letters longthen each letter is bumped up by three spaces.So the word \cat\ becomes \fdw\\nThis script can encrypt and decrypt messagesbased on this rule.line_break(20)#Short Pauseprint Press return to continueraw_input(> )#Set a Function to receive and lowercase user inputdef get_user_input(x): x = raw_input(> ).lower() return x#Set a Function to ask user what they would like to dodef do_what(y): print What would you like to do?Press \e\ to Encrypt a messagePress \d\ to Decrypt a messagePress \q\ to quit y = get_user_input(y) return y#Ask user if they would like to Encrypt, Decrypt, or Quitans = do_what(ans)while ans != 'q': #If they choose Encrypt: if ans == e: #Get users input to decipher print What is the message you would like to encrypt? plainText = get_user_input(plainText) #Translate it using Caesar Cipher by Length #Sets up a for loop for each word (split by spaces) for word in plainText.split(): #newWord variable to be filled newWord= #Loop for each character in a single word for char in word: #If the character is in the lowercase alphabet... if char in alphabet: #finds the characters position in the alphabet pos = alphabet.index(char) #Takes that position number and adds the length of the word. #%26 is so that any letter past 'z' goes to the beginning newPos = ((pos + len(word))%26) #The new position is used in the alphabet to find a new character newChar = alphabet[newPos] #The new character is added to a word newWord += newChar else: #This is for any non-alphabetical character (!,.' etc.) newWord += char #adds the new word to the output followed by a space (to separate the words) cipherText += newWord + #Print out the Translation line_break(20) print %r turns into:\n%r % (plainText, cipherText) line_break(20) print Press return to continue raw_input(> ) #initializes output text cipherText= #Ask user if they would like to Encrypt, Decrypt, or Quit ans = do_what(ans) #If they choose Decrypt: elif ans == d: #Get users input to decipher print What is the message you would like to decrypt? plainText = get_user_input(plainText) #Translate it using Caesar Cipher #Very similar to the code for encrypting for word in plainText.split(): newWord= for char in word: if char in alphabet: pos = alphabet.index(char) #This time it subtracts the length of the word from the position #%26 is so that any word below 'a' goes to the end of the alphabet newPos = ((pos - len(word))%26) newChar = alphabet[newPos] newWord += newChar else: newWord += char cipherText += newWord + #Print out the Translation line_break(20) print %r turns into:\n%r % (plainText, cipherText) line_break(20) print Press return to continue raw_input(> ) cipherText= #Ask user if they would like to Encrypt, Decrypt, or Quit ans = do_what(ans) #If they choose anything else else: #Print an error code print Command not recognized #Ask them to try again print Please Try Again #Ask if they would like to Encrypt, Decrypt, or Quit ans = do_what(ans)#If they choose Quit if ans == 'q': #Say Goodbye print Goodbye #End scriptAny feedback is appreciated! | Ceasar Cipher by Word Length V.2 | python;python 2.7;caesar cipher | #To import the lowercase alphabetimport string# ...alphabet = string.ascii_lowercaseThe same can be accomplished withfrom string import ascii_lowercase as alphabetwhich also makes the comment unnecessary.print ...So the word \cat\ becomes \fdw\\nThis script can encrypt and decrypt messagesbased on this rule.You do not need to escape quotes inside a triple quoted string. And you can write line breaks just as literal linebreaks:print ...So the word cat becomes fdwThis script can encrypt and decrypt messagesbased on this rule.#Set a Function to receive and lowercase user inputdef get_user_input(x): x = raw_input(> ).lower() return xYou are not using the x argument of the function. Just writedef get_user_input(): x = raw_input(> ).lower() return xor evendef get_user_input(): return raw_input(> ).lower()#Set a Function to ask user what they would like to dodef do_what(y): print ... y = get_user_input(y) return ySince now get_user_input does not take a parameter, do_what doesn't need one, either:def do_what(): print ... return get_user_input()#setting up some variablesans = plainText = Since ans is not required as an argument for do_what, it doesn't need to be initialized as an empty string. The same goes for plainText.while ans != 'q': if ans == e: # encrypt ... ans = do_what(ans) elif ans == d: # decrypt ... ans = do_what(ans) else: # error ... ans = do_what(ans)A new value for ans is fetched in any case at the end of each iteration of the loop, so you can just write it once outside the if-else block.while ans != 'q': if ans == e: # encrypt ... elif ans == d: # decrypt ... else: # error ... ans = do_what()ans = do_what()while ans != q: # do something ans = do_what()if ans == 'q': # quitYou can only exit the loop when ans gets q at some point. So you don't need to check that again after the loop!I suggest the following overall structure for the control flow, which requires writing ans = do_what() only once in the whole script:while True: ans = do_what() if ans == 'q': break # do something# quitif ans == e: # encryptelif ans == d: # decryptelse: # errorRight now, where I put those placeholder comments, there is a lot of code. It would be cool if these blocks of code were contained in functions like do_encryption, do_decryption and print_error, so you could literally write:if ans == e: do_encryption()elif ans == d: do_decryption()else: print_error()Then it would also be possible to use a dictionary as a lookup table to map the letter to the action to be performed:{'e': do_encryption, 'd': do_decryption}.get(ans, print_error)() |
_unix.184288 | I've been working on a Routing Protocol and looking at legacy code for different routing protocols. I constantly find different macros where I it is very hard to find it in the header files because they include ~20-50 headers. Besides looking up the macro on the Internet is there any way by finding their definitions in the man pages?For instance: INADDR_ALLHOSTS_GROUP macro which I eventually found in netinet/in.h but the man page never discussed the macro. Is there a way to use the man pages when you are trying to search for such things or would I need to go another way? | How to find documentation about macros in the manpages? | man;documentation;system programming | I posed this question to my mentor and he said to use grep, so I tried it out and I succeeded. Grep is an absolutely amazing tool! The code I used to find the macro was grep -rl INADDR_ALLHOSTS_GROUP * and I ran it from the /usr/include directory. |
_cs.66243 | I'm into designing a recommender system for movie database and for effective optimization.I suggested the idea of using particle swamp optimization ,but my professors need recent algorithms,can any one suggest recent nature inspired algorithms for optimization.(After Cuckoo Search Optimization). | what is the Recent Nature Inspired Algorithm for Optimization? | algorithm analysis;bio inspired computing | This paper[[1]] recommends the following Swarm Intelligence algorithms:Ant colony optimizationBat algorithmCuckoo searchFirefly algorithmParticle swarm optimization[1]: A Brief Review of Nature-Inspired Algorithms for Optimization |
_codereview.135840 | I have an associative array with data (let's say language codes and descriptions) and a second array with allowed keys (lang codes). I want to filter the data array by these allowed keys. The problem is I'm bound to PHP 5.5 and I can't use ARRAY_FILTER_USE_KEY flag.I came up with the following solution:$langs = [ 'en' => English, 'de' => German, 'fr' => French, 'ru' => Russian,];$allowed_langs = ['en','de'];var_export( array_map( function($lang) use($langs) {return $langs[$lang];} , array_combine($allowed_langs, $allowed_langs)));/* Output as expected:array ( 'en' => 'English', 'de' => 'German',)*/I wonder is there a more elegant and shorter solution to this task? | Filtering array by list of keys in PHP 5.5 | php;array | I always believe that you should use built in functions wherever possible, as opposed to recreating PHP functionality with loops etc. The main reasons for saying this are that:We should trust that PHP functions achieve their desired result in an efficient manner, and:If they are improved in future versions your code doesn't need to change, but just gets better.That being said, why not something like this:$matches = array_intersect_key($langs, array_flip($allowed_langs));var_export($matches); |
_webmaster.28733 | I have a php web application that allows file uploads to a specific directory.I would like to prevent the execution of any file that is uploaded into that directory whether it is ASP, PHP, or anything else that may be supported by IIS. I'm already blocking the upload of asp and php files at the application layer, but as a measure of defense in depth against a possible error in that validation code I would like to add a configuration to IIS to prevent execution of these files.Is there a way to do that in IIS? | prevent IIS from executing scripts in a specific directory | security;iis7;windows | First of all -- this really depends on your server configuration -- if such modifications are allowed to be performed on directory level (section is not locked on parent/server level).In order to disable execution of specific file extension yo need to know the handler name that is responsible for this. On each system this name can be different, especially for PHP, since it is not standard handler (created by user with admin rights). For example (web.config that needs to be placed in such folder): <?xml version=1.0 encoding=UTF-8?><configuration> <system.webServer> <handlers> <remove name=PHP 5 /> </handlers> </system.webServer></configuration>The above will remove handler named PHP 5 that is responsible for handling *.php files on my PC. With *.asp handler this should be easier since it has standard name, but it can easily be changed if required.Another approach -- remove ALL handlers altogether. In this case you do not need to know handler names. This has one serious drawback -- you will not be able to serve anything from this folder and subfolders, even static files.<?xml version=1.0 encoding=UTF-8?><configuration> <system.webServer> <handlers> <clear /> </handlers> </system.webServer></configuration>To bypass this drawback you can create URL rewriting rule and forward all requests to such files to your special script that will actually serve those files (script will have access to those files, so no problems here). The downside -- it can be quite complex (depends on number of file types it will be handling) + will produce a bit of unnecessary processing overhead (how big -- depends on your script, how you will code it).3rd approach seems to be more optimal (really depends on your other requirements) -- we will remove ALL handlers and will add the one that serves static files back .. so images/html/css/js etc should still work if requested from such folder:<?xml version=1.0 encoding=UTF-8?><configuration> <system.webServer> <handlers> <clear /> <add name=StaticFile path=* verb=* modules=StaticFileModule,DefaultDocumentModule,DirectoryListingModule resourceType=Either requireAccess=Read /> </handlers> </system.webServer></configuration>If you still require some other standard handlers to be available in this folder .. then you will have to add them back in a similar manner. |
_softwareengineering.101844 | I invested most my time and resources in programming, and now I think it's time I should invest some time in learning about user interface design, user experience, and usability.What are some good resources about usability and designing user interfaces? I'm mainly looking for more theoretical topics, such as color theory and color physiology and how they affect users, along with information about best practices. | How can I improve my user interface and usability design skills? | self improvement;books;user interface;usability;user experience | Start by bookmarking https://ux.stackexchange.com/ If you are concerned about UI design then start by creating some custom controls. Think of something that you think is not possible on one platform (like an awesome looking control on WinForms) and try to design it yourself. I've learned a lot this way. More you experience more you learn. I also recommend reading any or all of the following books:Rocket Surgery Made Easy => From the author who wrote Don't Make Me ThinkDesigning Interfaces => This book is a big one and covers the design patters for UI. There is a chapter on psychological aspect too.Visualize This => I just started reading it and it is awesome. It is mostly about using statistics to visualize your data but is a great book on cool looking visualization. |
_webapps.73994 | In order to allow Facebook users to log in to our (Android) Mobile App - I need to create an App Id on Facebook.Ideally I do not want to use my personal Facebook account to create the App Id.I would rather use a generic account which the company owns, and not individual.Does Facebook allow a generic account that a company can use for this purpose?What is the best practice for this? | Creating an Application on Facebook | facebook;facebook apps | null |
_webmaster.69886 | My website has lots of links that are linking to it from different websites, but I don't see any visitors from China or Japan.Would translating my website help to start seeing new visitors from those countries? | Would translating my website help to get more traffic from China or Japan? | seo;translation | Yes, The problem of not much traffic from China and Japan is mainly because of the language barriers.If you have a localized website, it definitely will help.But content is always the king.You will get more traffic from China if more of your website pages could be indexed by Baidu, Baidu is working quite different from Google. |
_webmaster.19626 | Possible Duplicate:Is there any way to find out how often a certain query is sent to a search engine? How can i find keywords or phrase which fetch less than 100 or even no results, without manually doing it?I know it will take time for any person to go manually research.Any tool paid or free.Time is money | How can i find keywords or phrase which fetch less than 100 or even no results, without manually doing it? | google;google search console;google search;research | null |
_softwareengineering.7516 | If I would like to quickly set up a modern website, what programming language + framework has best support for this? E.g. short and easy to understand code for a beginner and a framework with support for modern features. Disregard my current knowledge, I'm more interested in the capacity of web programming languages and frameworks.Some requirements:Readable URIs: http://example.com/category/id/page-title similar to the urls here on Programmers.ORM. A framework that has good database support and provide ORM or maybe a NoSQL-database.Good support for RESTful WebServices.Good support for testing and unit testing, to make sure the site is working as planned.Preferably a site that is ready to scale with an increasing number of users. | What programming language and framework has best support for agile web development? | web development;agile;frameworks | I have now started to use Play Framework with Scala and Java. It's inspired by Ruby on Rails and it has a very short development cycle where you just save the Scala/Java files and then update the web browser. It's also easy to understand and has good performance. But the IDE's doesn't have very good support for e.g. the template files yet. |
_softwareengineering.41301 | I am looking to learn how to properly use, and implement, HTTP headers. What is the best resource or set of guidelines that I can use? ( especially ranges to detect download managers, etc) ? | Where can I learn and understand the complete workings of HTTP headers, so I can implement my own? | specifications;http | null |
_cs.40500 | I am writing a paper in which the worst-case analysis of a certain randomized algorithm is correct with probability $1-1/n$ (where $n$ is the size of the problem). I find myself writing, time after time, the following sentence: With high probability, in the worst case, the performance of phase A is at most X.The worst-case is with relation to the inputs; the high probability is with relation to the randomization of the algorithm. I.e, there is an adversary that choose the worst possible inputs, but then I do a lottery on which the adversary has no effect.Since there are many phases, this sentence appears many times throughout the paper and it looks cumbersome. I tried to make it shorter by writing:In the worst case (WHP), the performance of phase A is at most... This still looks cumbersome... Is there a more common way to express this meaning? | Shortcut for in the worst-case, with high probability? | terminology | Your second example looks fine to me. In the worst case, phase A takes time/space X whp is even shorter. |
_unix.119725 | I am setting up a new NFS client on a LAN that has a working NFS server (Ubuntu 12.04) running nfs4. The other clients all work as expected.On this new client I'm running ChrUbuntu with kernel 3.4.0 (Kubuntu 12.04) on an Acer Chromebook. I installed nfs-common. However, the mount command returns the error mount.nfs4 no such device. And # modprobe nfs returns Fatal: module nfs not found. Google didn't offer me any solutions.The mount command is like:sudo mount -t nfs4 -o _netdev,noatime,auto,rw myserver:/home/user/shared /home/user/mountpointThe modprobe command is:sudo modprobe nfsAnd nfs-common is the latest version from this release's repo: 1:1.2.5-3ubuntu3.1 | Fatal: module nfs not found | nfs;modprobe;chrubuntu | modprobe is looking in /lib/modules to know whether a module is present. So you should check first if the current version of your running kernel has nfs module:ls -l /lib/modules/$(uname -r)/kernel/fsif you don't see nfs folder, it means the nfs module is not compiled for your running kernel. You can recompile kernel to make it use nfs module. However, you should upgrade your kernel first:sudo apt-get updatesudo apt-get dist-upgradesudo init 6 |
_softwareengineering.20080 | Over on stackoverflow, I see this issue crop up all the time: E_NOTICE ?== E_DEBUG, avoiding isset() and @ with more sophisticated error_handler How to set PHP not to check undefind index for $_GET when E_NOTICE is on? How to stop PHP from logging PHP Notice errors How do I turn off such PHP 5.3 Notices ? Even Pekka (who offers a lot of solid PHP advice) has bumped against the dreaded E_NOTICE monster and hoped for a better solution than using isset(): isset() and empty() make code ugly Personally, I use isset() and empty() in many places to manage the flow of my applications. For example:public function do_something($optional_parameter = NULL) { if (!empty($optional_parameter)) { // do optional stuff with the contents of $optional_parameter } // do mandatory stuff} Even a simple snippet like this:if (!isset($_REQUEST['form_var'])) { // something's missing, do something about it.}seems very logical to me. It doesn't look like bloat, it looks like stable code. But a lot of developers fire up their applications with E_NOTICE's enabled, discover a lot of frustrating uninitialized array index notices, and then grimace at the prospect of checking for defined variables and littering their code with isset().I assume other languages handle things differently. Speaking from experience, JavaScript isn't as polite as PHP. An undefined variable will typically halt the execution of the script. Also, (speaking from inexperience) I'm sure languages like C/C++ would simply refuse to compile.So, are PHP devs just lazy? (not talking about you, Pekka, I know you were refactoring an old application.) Or do other languages handle undefined variables more gracefully than requiring the programmer to first check if they are defined?(I know there are other E_NOTICE messages besides undefined variables, but those seem to be the ones that cause the most chagrin)AddendumFrom the answers so far, I'm not the only one who thinks isset() is not code bloat. So, I'm wondering now, are there issues with programmers in other languages that echo this one? Or is this solely a PHP culture issue? | Why do many PHP Devs hate using isset() and/or any of PHP's similarly defensive functions like empty()? | php;error messages | I code to E_STRICT and nothing else. Using empty and isset checks does not make your code ugly, it makes your code more verbose. In my mind what is the absolute worst thing that can happen from using them? I type a few more characters.Verses the consequences of not using them, at the very least warnings. |
_datascience.17193 | I've build a CNN in Tensorflow with 2 conv layers, 1 pool layer and 2 FC layers. When I don't use dropout I get 98% accuracy on training dataset and 90% on test dataset. But, when I do use dropout, I get 62% accuracy on training dataset and 83% on test dataset.I use 25 labels when each label has between 500-1200 samples.What could be the problem?UPDATE1BUILD NETWORKbatch_size = 50conv1_kernel_size = 3conv1_num_kernels = 16conv2_kernel_size = 3conv2_num_kernels = 16num_hidden = 64num_channels = 1image_size = 32with tf.Graph().as_default() as graph: # input data tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size, image_size, num_channels)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) tf_test_dataset = tf.constant(test_dataset) tf_test_single_data = tf.placeholder(tf.float32, shape=(1, image_size, image_size, num_channels)) conv1_weights = tf.Variable(tf.truncated_normal([conv1_kernel_size, conv1_kernel_size, num_channels, conv1_num_kernels]), name='conv1_weights') conv1_biases = tf.Variable(tf.zeros([conv1_num_kernels]), name='conv1_biases') conv2_weights = tf.Variable(tf.truncated_normal([conv2_kernel_size, conv2_kernel_size, conv1_num_kernels, conv2_num_kernels]), name='conv2_weights') conv2_biases = tf.Variable(tf.constant(1.0, shape=[conv2_num_kernels]), name='conv2_biases') fc1_weights = tf.Variable(tf.truncated_normal([image_size // 2 * image_size // 2 * conv2_num_kernels, num_hidden], stddev=0.1), name='fc1_weights') fc1_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]), name='fc1_biases') fc2_weights = tf.Variable(tf.truncated_normal([num_hidden, num_labels], stddev=0.1), 'fc2_weights') fc2_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]), 'fc2_biases') keep_prob = tf.placeholder(tf.float32) # model def model(data): conv1 = tf.nn.conv2d(data, conv1_weights, strides=[1, 1, 1, 1], padding='SAME') conv1_hidden = tf.nn.relu(conv1 + conv1_biases) conv2 = tf.nn.conv2d(conv1_hidden, conv2_weights, strides=[1, 1, 1, 1], padding='SAME') conv2_hidden = tf.nn.relu(conv2 + conv2_biases) pool_conv2_hidden = tf.nn.max_pool(conv2_hidden, ksize=[1,2,2,1], strides=[1, 2, 2, 1], padding='SAME') pool_conv2_hidden_shape = pool_conv2_hidden.get_shape().as_list() fc1 = tf.reshape(pool_conv2_hidden, [pool_conv2_hidden_shape[0], pool_conv2_hidden_shape[1] * pool_conv2_hidden_shape[2] * pool_conv2_hidden_shape[3]]) fc1_hidden = tf.nn.relu(tf.matmul(fc1, fc1_weights) + fc1_biases) fc1_drop_hidden = tf.nn.dropout(fc1_hidden, keep_prob) fc2 = tf.matmul(fc1_drop_hidden, fc2_weights) + fc2_biases return fc2 # training computation logits = model(tf_train_dataset) loss_cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf_train_labels)) optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss_cross_entropy) # predictions train_prediction = tf.nn.softmax(logits) test_prediction = tf.nn.softmax(model(tf_test_dataset))RUN NETWORKnum_steps = 20000with tf.Session(graph=graph) as session: tf.global_variables_initializer().run() print('Initialized') for step in range(num_steps): offset = (step * batch_size) % (train_labels.shape[0] - batch_size) batch_data = train_dataset[offset:(offset + batch_size), :, :, :] batch_labels = train_labels[offset:(offset + batch_size), :] feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob : 1.0} _, loss, predictions = session.run([optimizer, loss_cross_entropy, train_prediction], feed_dict=feed_dict) train_acc = accuracy(predictions, batch_labels) if (step % 50 == 0): epoch = (step * batch_size) // (train_labels.shape[0] - batch_size) print('Epoch-%d - Minibatch loss at step %d: %f' % (epoch, step, loss)) print('Epoch-%d - Minibatch train accuracy: %.1f%%' % (epoch, train_acc)) print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(feed_dict={keep_prob : 1.0}), test_labels)) | Why does dropout ruin my accuracy in CNN? | neural network;tensorflow;regularization;dropout | null |
_webmaster.89816 | We recently encountered an issue where we added a JavaScript variable (e.g. var GLOBAL_VAR = true;) to an HTML page (e.g. /Search/Index) and updated the separate JS file (e.g. /Scripts/search/index.js) to access and use that JS variable. After publishing these changes live to the web, we began getting JS errors generated by Googlebot that are sent to us by our window.onerror function. The errors are like:Uncaught ReferenceError: GLOBAL_VAR is not definedLine #: 1http://example.com/Scripts/search/index.jsWhen I visit the /Search/Index page on our site, I clearly see the new JS variable is there and defined.It's almost as if when Googlebot is crawling our site, it isn't detecting that the HTML page changed. So that means it is using old, cached HTML that doesn't include the setting of the GLOBAL_VAR variable, which causes the JS error.We published the HTML/JS changes on 2/6, and we are still getting JS errors as of 2/10. I would have thought Googlebot would recognize the HTML changes by now. We've never experienced this problem in the past.Why would Googlebot not update their cache if the HTML of a page changes? Most importantly, how can we get Googlebot to detect the HTML changes and update their cache, so we stop getting these JS errors? | Googlebot encountering JavaScript errors due to rendering outdated HTML files with newer JS files | javascript;web crawlers;googlebot | null |
_softwareengineering.104816 | With popular software out today like Node.js, Celery, Twisted, and others boasting about being asynchronous, what does it mean? I've gone through the basic Node.js tutorials and written a few Node.js scripts, but still don't feel comfortable with the topic. Please note that I haven't had I had any formal introduction to the topic. How exactly does asynchronous software work? What are the pros and cons?What are callbacks?Lastly, how does a synchronous web server perform vs. an asynchronous web server? | What does it mean for software, libraries, and languages to be asynchronous? | web development;javascript;node.js | Wikipedia might be a good place to start with some general concepts and basic information.This quote from that page sums it up but probably needs a bit of knowledge to fully understand it.In programming, asynchronous events are those occurring independently of the main program flow. Asynchronous actions are actions executed in a non-blocking scheme, allowing the main program flow to continue processing.So with synchronous programming the user initiates an action on the program but then has to wait for the operation to complete before being able to do anything else. An example might be saving a file to disk, you can't do anything else until the file is saved.With asynchronous programming the user initiates an action, but then can carry on doing other work while the operation completes. The program then notifies the user in some way that its finished. An example here might be printing a document. Here you initiate the print then (after some set up) can carry on while the document is sent to the printer. You get some sort of notification that the printing is complete.Asynchronous applications rely on multithreading or spawning child processes that do the work.Callbacks are one mechanism where the calling code can do something when the asynchronous operation is complete. You'll register the callback with the long running process in some way then when it completes the code defined by the callback will be executed. |
_webapps.31505 | I know how to change the theme in GMail and change the background. However I would like the background of my theme to change every so many minutes versus once a day. Similar to the way you can set the time in Windows for changing the desktop background. I have not seen a way to do this in GMail settings. Is this possible? | Change GMail Background every X minutes | gmail | You'll need to select a theme that changes hourly or at least based on the time of day.In Gmail Themes there are four types of backgrounds you can choose, as indicated by the icon in the lower right of the background preview image:None - Static and one image onlySun - Changes based on the weather, set by your location settingClock - Based on time of dayStrip - Depends on the day of the weekThat's the closest you'll get for now until they allow you to upload or select an album to flip through as a background wallpaper on X time increments. |
_unix.115339 | So I use Mint a lot, but wish to switch to Ubuntu due to trivial updating Ubuntu offers.Problem with Ubuntu is that a lot of neat packages (Such as right click commands for open in terminal etc) don't come pre-installed.I wish to get a list of packages to install on Ubuntu that are pre-installed on Mint, even just the GUI based ones would be great!Note: I am not trying to get Ubuntu looking like mint, just the GUI packages that make life easy. I am also not asking opinions on what are the best GUI packages out there, just what Mint has Ubuntu doesn't. | Find and install Mint's default packages into new Ubuntu install | package management;nautilus;synaptic | null |
_unix.107611 | I've installed windows 7 and linux dualboot. My partitions are:/dev/sda2: UUID=EC328C61328C329E TYPE=ntfs /dev/sda3: UUID=800E88610E8851D8 TYPE=ntfs /dev/sda4: UUID=20e7c430-bab0-4aa1-8afe-caa9d97e1de3 TYPE=ext4where sda2 is windows sda3 is shared partition and sda4 is linuxsd3 has mounting point /windowsBecause sda2 and sda4 are small partitions I created directories Music, Documents, etc. and redirected windows libraries in here.I want do the same in linux but editing ~/.config/user-dirs.dirstoXDG_DESKTOP_DIR=$HOME/PlochaXDG_DOWNLOAD_DIR=$HOME/XDG_TEMPLATES_DIR=$HOME/ablonyXDG_PUBLICSHARE_DIR=$HOME/VeejnXDG_DOCUMENTS_DIR=/windows/home/DocumentsXDG_MUSIC_DIR=/windows/home/MusicXDG_PICTURES_DIR=/windows/home/PicturesXDG_VIDEOS_DIR=/windows/home/Videoshas no effect. Folders has icons as it if works but when I click on Music in the file browser it goes to /home/myUser/Music not into/windows/home/Music.It would be great if it would work for cd ~/Music command too :) | Redirect home to shared NTFS partition | directory structure;defaults | Keep the lines as they were in original user-dirs.dirs : XDG_MUSIC_DIR=$HOME/MusicXDG_PICTURES_DIR=$HOME/PicturesXDG_VIDEOS_DIR=$HOME/VideosAnd now create symbolic links to point to your windows folders (make sure you have no important data in the three concerned folders :cd ~rm -fr Music Pictures Videosln -s /windows/home/Music ln -s /windows/home/Pictures ln -s /windows/home/Videos By the way, you would better create a swap partition. You don't mention you did it already. |
_softwareengineering.196502 | Now, when I make a programming mistake with pointers in C, I get a nice segmentation fault, my program crashes and the debugger can even tell me where it went wrong.How did they do that in the time when memory protection wasn't available? I can see a DOS programmer fiddling away and crashing the entire OS when he made a mistake. Virtualization wasn't available, so all he could do was restart and retry. Did it really go like that? | How did they debug segmentation faults before protected memory? | history;debugging;memory | I can see a DOS programmer fiddling away and crashing the entire OS when he made a mistake.Yeah, that's pretty much what happened. On most systems that had memory maps, location 0 was marked invalid, so that null pointers could be easily detected, because that was the most common case. But there were lots of other cases, and they caused havoc.At the risk of sounding like a geezer, I should point out that the current focus on debugging is not the way of the past. Much more effort was previously made to write correct programs, rather than to remove bugs from incorrect programs. Some of that was because that was our goal, but a lot was because the tools made things hard. Try writing your programs on paper or on punched cards, not in an IDE, and without the benefit of an interactive debugger. It gives you a taste for correctness. |
_webapps.105093 | I've just found that I'm following all people whom I connected to. There are two ways to connect people through LinkedIn 1. Send an invitation and 2. Accept an invitation. Either way you connect the people I think it is also considered following automatically.So, Is connecting people automatically consider following them upon connection? Can I stop it? or I've to manually manage it individually?I've found that you can also follow one without connecting. Similarly you can unfollow one whom you're connected with.What is the difference between connecting people and following people?Note that I'm talking about peoples only not about following groups or companies. | Am I automatically considered to be following one whom I connect through LinkedIn? | linkedin | LinkedIn defines a connection as a two-way relationship of trust between people who know each other. If you are connected to someone, youre following him or her by default and vice-versa.So yes, to unfollow anyone you have to manually manage it individually.Yes, you can follow anyone to get their updates on your home page. Once you follow them they will get notification about it. They will not get any update from you if they are not following you. You can unfollow anyone anytime. They will not get notification about it.See the LinkedIn Help to know about Similarities and Differences Between Following And Connecting. |
_unix.150582 | Given the scenario:Remote machine: SSH server; user does not have admin privileges;Local machine: SSH client; user has admin privileges.If user, logging in to remote from local, wishes to interact with remote using a shell not installed on remote, how can user accomplish this alone?Example: user uses fish on local, and wishes also to use it on remote, but remote only has bash and zsh installed. | Use a shell not installed on remote machine | shell;ssh;not root user | Install your favorite shell on the remote machine. You don't need any administrator privileges to do that, you can install programs in your home directory, it's just less convenient. See Installation on debian 5 32-bit without being a root, How to install program locally without sudo privileges?, Keeping track of programs and other questions.If you want to automatically log into a shell that you installed yourself instead of the default one, see Making zsh default shell without root accessIf all you want to do is manipulate remote files, you can use SSHFS to mount the remote directory tree on your local machine.mkdir ~/remote.dsshfs remote.example.com:/ ~/remote.dls ~/remote.d/fusermount -u ~/remote.dIf you have no room in your home directory or it's a shared account, you can make do with setting up a reverse SSH tunnel and mount your local directory tree on the remote machine with SSHFS, assuming that the two machines are running the same architecture (same unix variant on the same processor type). If the two machines have incompatible architectures, you can even install the programs for the remote architecture in your local home directory. This may not be very convenient as you'll have to set up paths correctly for the programs to find their libraries, configuration files and other data files.Emacs's eshell is compatible with Tramp: if you change to a remote directory in Eshell, you'll be executing commands on the remote machine. |
_unix.269464 | I am trying to set up Powerline in my xterm. Im running ArchLinux.I have followed the steps from here and I am at this point here:So basicaly it works but I just cannot make the arrows appear. This has something to do with the fonts, but I have installed PowerlineSymbols as described in the link above. How can I make the symbols display correctly in xterm? | Unable to use correctly Powerline with xterm | fonts;xterm;unicode | null |
_unix.225412 | I installed Apache using this script https://gist.github.com/Benedikt1992/e88c2114fee15422a4eb The system is a freshly installed CentOS 6.7 minimal system.After installation I can find the apache in /usr/local/apache2/ but I can't start the apache with service or enable start on boot with chkconfig. What am I missing? | How to configure Apache init scripts, after compiling and installing the sources? | centos;apache httpd | Apache 2.4 doesn't use the init scripts. As Saul Ortega said the apachectl script can be used to start the server. It can also be used as a standard SysV init script. Further informations can be found in the apache doc http://httpd.apache.org/docs/2.4/en/invoking.html |
_unix.149900 | I am using GNU parallel to run a bash function. The function just contains the bash script to restart my program. At first, the restart is ok, but when parallel exits, my program also fails. Why?#!/bin/bashfunction_A () { local module=$1 set -x cd /dir/${module}/;sh stop_${module}.sh;sh start_${module}.sh;sleep 10}export -f function_Aparallel --tag --onall --env function_A -S my_host function_A ::: my_programOutput from ps:root 12967 0.0 0.0 65960 1152 pts/1 Ss+ 16:30 0:00 bash -c echo $SHELL | egrep /t?csh > /dev/null && echo CSH/TCSH DO NOT SUPPORT newlines IN VARIABLES/FUNCTIONS && exec false;? eval `echo $SHELL | grep /t\{0,1\}csh > /dev/null && echo setenv PARALLEL_SEQ 1\; setenv PARALLEL_PID 6431 || echo PARALLEL_SEQ=1\;export PARALLEL_SEQ\; PARALLEL_PID=6431\;export PARALLEL_PID` ; tty >/dev/null && stty isig -onlcr -echo;echo $SHELL | grep /t\{0,1\}csh > /dev/null && setenv function_A \(\)\ \{\ \ local\ module=\$1\;?\ set\ -x\;?\ cd\ /dir/\$\{module\}/\;?\ sh\ test.sh\;?\ sleep\ 10?\} || export function_A=\(\)\ \{\ \ local\ module=\$1\;?\ set\ -x\;?\ cd\ /dir/\$\{module\}/\;?\ sh\ test.sh\;?\ sleep\ 10?\} && eval function_A$function_A;function_A my_program | When GNU parallel exitmy program also fail | bash;shell script;gnu parallel | null |
_webmaster.103456 | do have anyone experience with 1and1 hosting? I've tried to read over their transparent pricing.They have a configuration panel, that allows to select amount of CPU/RAM/SSD storage.(Configuration Panel)What is that configuration about? And how do autoscaling work?The configuration is per-machine and if the machine is too busy they instantiate another machine?The configuration is total hardware power divided among machines? (in that case then the only thing that scales is the price since traffic load may vary according to time of day)If I choose the most powerfull hardware combination, and I have just 1 user at any time, will I pay the full computing power? (In example the configuration is able to host 1.000.000 users, but for some reason the server is kept busy 24h/24h just by 1 user)Do I have to configure a different DB for each machine? If yes how do I assign databases Usernames/Passwords and IP adresses.Do computing power scale automatically? If yes why they mention I will be able to change configuration in 55 seconds at any time? Why do I need to change configuration if the Cloud scales?I know that are lot of questions, but in reality it is just one question: How do 1and1 Cloud hosting scales? | 1and1 Cloud hosting scaling of DB and Instances | cloud hosting;cloud;scalability | null |
_unix.287410 | The code is ;cm=$1nm=$2case $cm inout)declare -a endeclare -a infec=$(grep -n ! hw1_out_si_wire.txt)IFS=$'\n' en=($ec)lst=$((${#en[@]} -1))IFS=' ' inf=($en[$lst])echo Energy: ${inf[4]} ${inf[5]};;in) echo It's not my problem;;esacAnd I'm trying to take 7th element of $en but the output is ;[7]ergy: -1090.13343774 RyAnd the $en array is ;! total energy = -1090.13343774 Ry! total energy = -1090.20757070 Ry! total energy = -1090.24296462 Ry! total energy = -1090.25563488 Ry! total energy = -1090.27085564 Ry! total energy = -1090.27693129 Ry! total energy = -1090.28213580 Ry! total energy = -1090.29131927 RySo, what is the problem with this code ?Why is the output like this ?Note:If the informations given is not enough , please inform me. | What is wrong in this code? | bash;osx;array | The fact that something is possible to do in bash, doesn't mean that you should, or that it's a good idea. What you are trying to do is much easier in languages like awk or perl.bash arrays are a fairly advanced usage of bash and, due to limitations in the bash/sh language itself (and the awkwardness of using them), not really as useful as arrays are in other languages. They're great for passing multiple arguments to a command or a function, but of limited use beyond that.Instead of messing around with bash arrays, try awk.For example:#! /bin/shcm=$1nm=$2case $cm in out) awk -F'[[:space:]]+' ' /^!/ { c++; if (c==7) { print Energy:,$5,$6; }; };' hw1_out_si_wire.txt ;; in) echo It's not my problem ;;esacOutput: Energy: -1090.28213580 RyThe embedded awk script counts each line beginning with a !, and when it gets to the 7th line, it prints the 5th and 6th fields.The -F option sets the field separator to 1-or-more whitespace characters (spaces, tabs, newlines, carriage returns, form-feeds, and vertical tabs). The version in my comment used [\r[:blank:]]+ (which is blank characters, spaces and tabs, plus carriage-return). For your input data, it works the same.If your version of awk doesn't support regexp field-separators (e.g. mawk) then just drop the -F'[[:space:]]+' from the awk command-line. It will still work, but if the input file is a MS-DOS/Windows text file (i.e. with carriage-return and line-feed as line-ending) rather than a unix text file (with line-feed only as line-ending), it'll output a carriage-return at the end. The carriage-return will be invisible unless piped through cat -v: Energy: -1090.28213580 Ry^MIn that case, convert the file to unix format with fromdos first. |
_unix.285774 | My text file has no delimiter to specify separator just spaces, how do I cut out column 2 to output file,39 207 City and County of San Francisc REJECTED MAT = 078 412 Cases and materials on corporat REJECTED MAT = 082 431 The preparation of contracts an REJECTED MAT = 0So output I need is 207412432 | cut column 2 from text file | text processing;columns;cut | null |
_cs.49661 | The natural grammar for dangling else is ambiguous.But there exists an unambiguous version of the grammar that links the else to last uncompleted if statement.Is this version also deterministic?Is this language deterministic?Natural grammar (ambiguous):$$S \rightarrow if~expr~S | if~expr~S~else~S | cmd$$Unambiguous grammar:$$\begin{align*}S &\rightarrow U~|~F\\U &\rightarrow if~expr~S~|~if~expr~F~else~U\\F &\rightarrow if~expr~F~else~F~|~cmd\end{align*}$$ | Dangling else determinism | context free;formal grammars;nondeterminism | null |
_softwareengineering.312906 | I came across this problem of finding the shortest path with exactly k edges. After some searching, I found the code below. It uses a 3D DP. States are there for number of edges used, source vertex and destination vertex. It seems like they have used something like a Floyd Warshall algorithm here. In that case, shouldn't we use the loop order : e {a {i {j {} } } } ? Where a is the loop for the intermediate vertex. Dynamic Programming based C++ program to find shortest path with exactly k edges#include <iostream>#include <climits>using namespace std;// Define number of vertices in the graph and inifinite value#define V 4#define INF INT_MAX// A Dynamic programming based function to find the shortest path from// u to v with exactly k edges.int shortestPath(int graph[][V], int u, int v, int k){ // Table to be filled up using DP. The value sp[i][j][e] will store // weight of the shortest path from i to j with exactly k edges int sp[V][V][k+1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value sp[i][j][e] = INF; // from base cases if (e == 0 && i == j) sp[i][j][e] = 0; if (e == 1 && graph[i][j] != INF) sp[i][j][e] = graph[i][j]; //go to adjacent only when number of edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) { // There should be an edge from i to a and a // should not be same as either i or j if (graph[i][a] != INF && i != a && j!= a && sp[a][j][e-1] != INF) sp[i][j][e] = min(sp[i][j][e], graph[i][a] + sp[a][j][e-1]); } } } }}return sp[u][v][k];} | Dynamic Programming: Shortest path with exactly k edges in a directed and weighted graph | graph;dynamic programming | In a standard Floyd-Warshall implementation that order does indeed matter ( the loops need to be intermediate{source{destination}} ). This question has already been answered hereFloyd Warshall optimizes cost by trying to optimize the cost from i to j through another vertex k. so esentially it's also doing it in an ascending way in terms of the number of edges. Here however, the order does not really matter because you already have the information for e-1 edges already calculated so you have all the information you need in order to calculate the optimal cost. |
_softwareengineering.337525 | Recently, i have shifted from ASP.NET web-forms to MVC based projects. I was thinking about the state management is working for a MVC project. How the MVC page controls are able to retain the state upon any action such as click, checked etc. I was wondering, if there is any DEFAULT state management pattern for the MVC app.Please share some high level inputs. | ASP.NET MVC Default State Management | mvc;asp.net mvc | ASP.NET/MVC doesn't try to hide the nature of the web (that is, it is stateless), like WebForms does.This means it has no built-in way to manage state.That's completely up to the developer. |
_codereview.144625 | Brief summary:The vanilla GoF visitor is great for altering items within a tree of elements, but when the visitor visits an element it can only change the children of that element not the element itself. For example, a visitor altering the DOM of a webpage could search for everything that contains an image and replace it with an ascii art version of that image. However, <dim>s can contains images, <table>s can contain images, paragraphs (<p>) can contain images. When the visitor is visiting the node for <image> tag itself it cannot change the type of the image node, though you could change the content of the image node - this is just how visitors work. Instead you would have to find everything that could conceivably contain an image and then visit that - and on top of that anytime W3C added another item that could contain an image you would have to update your visitor. This isn't a perfect example - there a lots of tools for altering webpage DOMs - but hopefully it is an intuitive one.Sorry - there is a wall of text in the more complete description below. I'm trying to walk the line between brevity and fully explaining everything, but it looks like this post same out quite wordy.What I have:I have a class hierarchy that can be represented by the simplified classes below:Element is the abstract base class for all visitable classes, and has an Accept method.LeafElementA and LeafElementB are concretes that are extremely simple. They don't do anything, but just represent that there can be different types of leaves.MultiCompositeElement and BinaryCompositeElement are also concretes that can contain other Elements - either a collection, or a Left and Right (respectively). The Accept method overrides handle recursing to the contained Elements.I also have some Visitors that visit each of the Elements. All vanilla GoF visitor so far...(I'm not looking for feedback on this class hierarchy, I'm just setting the scene with a simplified version of the real classes that I am working with).What I want:I would like to use a visitor to alter the structure of the Element tree. For example, in this toy example I might want to append a LeafElementA to each composite element, and if the composite element is a BinaryCompositeElement to convert it to a MultiCompositeElement before (and also recursively visit all the children of each composite element too...).The vanilla visitor does not cope with this well. When you visit an Element you can alter the content of that Element but not return a completely different Element.I could check the children of each MultiCompositeElement and BinaryCompositeElement as I visit them to see if any of the children need to be transformed from a BinaryCompositeElement to a MultiCompositeElement. However, this would violate the DRY principle as the check would have to be in both visit methods. This would be compounded by the fact that in the 'real' implementation there are many composite type elements - not just 2.Finally the code:DotNetFiddle (sorry for the terrible ToString implementation on this one) or download csproj/zip from dropbox (no terrible ToString, just put a breakpoint in the the end of the main method).I have left out some clutter bits of code from the snippets below. There is no error checking or null checking.Base classes (I've not included IVisitor as it would also increase clutter. All of the methods on VisitorBase are on IVisitor):// Element base classpublic abstract class Element { // I am returning an Element here (different from a normal GoF implementation) internal abstract Element Accept(IVisitor visitor);}// Visitor base classpublic abstract class VisitorBase: IVisitor{ // Again, return an Element // This is so that each visitor can choose to return a different type // than the visited Element public virtual Element Visit(Element element) { element = element.Accept(this); return element; } // Another departure from vanilla visitor: Visit just this element // (and don't recurse) public virtual Element VisitNonRecursive(Element element) { return element; } // These can be individually overridden, and I have added these for transforming // one type of Element into another public virtual Element VisitNonRecursive(LeafElementA leafElementA) { return VisitNonRecursive(leafElementA as Element); } public virtual Element VisitNonRecursive(LeafElementB leafElementB) { return VisitNonRecursive(leafElementB as Element); } // ...similar methods for the other elements (removed to reduce clutter in the snippet) }Some concrete elements (I'm not including LeafElementB as it is virtually identical to LeafElementA):public class LeafElementA : Element{ internal override Element Accept(IVisitor visitor) { return visitor.VisitNonRecursive(this); }}// Implementation of Element that contains multiple other Elementspublic class CompositeElement : Element{ public CompositeElement(params Element[] containedElements) { ContainedElements = containedElements.ToList(); } public ICollection<Element> ContainedElements { get; private set; } internal override Element Accept(IVisitor visitor) { ContainedElements = ContainedElements // Recursively visit each child .Select(visitor.Visit) .ToList(); // And non-recursively visit this return visitor.VisitNonRecursive(this); }}// Implementation of Element that contains exactly two other Elementspublic class BinaryElement : Element{ public BinaryElement(Element left, Element right) { Left = left; Right = right; } public Element Left { get; private set; } public Element Right { get; private set; } internal override Element Accept(IVisitor visitor) { // Recursively visit the children Left = visitor.Visit(Left); Right = visitor.Visit(Right); // And non-recursively visit this return visitor.VisitNonRecursive(this); }}And the concrete visitor:// Implementation of Visitor that adds a LeafElementA to any composite elementpublic class AddOneMoreVisitor : VisitorBase{ public override Element VisitNonRecursive(MultiCompositeElement multiCompositeElement) { multiCompositeElement.ContainedElements.Add(new LeafElementA()); return multiCompositeElement; } public override Element VisitNonRecursive(BinaryCompositeElement binaryCompositeElement) { // Here we are able to change the returned type from the visitor var result = new MultiCompositeElement( binaryCompositeElement.Left, binaryCompositeElement.Right, new LeafElementA() ); return result; } // The rest of the recursion-based visiting can be delegated to the base}So, did you actually have a question?Yes, I did. Firstly, is there a name for this variant of the visitor pattern? I assume that I will not be the first person in the whole world to think of or implement this. And I assume that with the collective wisdom of all those who have gone before that this class can be done better. Secondly, if this is not the case, then is there a way I can do this better? Doubling up the visit methods seems wasteful, but I always get stack overflow exceptions when I try an implementation without it.Thirdly, I am concerned about type safety. In the toy example all the composites contain base Elements. In the real-life code most Elements that contain another hold a derived type. Is there a way of making the visitor type safe so that no upcasting is needed? I couldn't find one - but that does not mean that it doesn't exists. And if not, is there a way to make it easier for a developer to write correct code. This looks like a powerful pattern and as Uncle Ben* said: With great power comes great responsibility. If it is not possible to make it provably typesafe according to the compiler, then the code should not get in the way of writing correct code. *The Spiderman uncle, not the rice uncle | Visitor that changes the structure of the objects it visits | c#;visitor pattern | null |
_cs.9049 | First, I have tried to build a DFA over the alphabet $\sum = \{0,\dots, 9\}$ that accepts all decimal representations of natural numbers divisible by 3, which is quite easy because of the digit sum. For this I choose the states $Q = \mathbb{Z}/3\mathbb{Z}\cup\{q_0\}$ ($q_0$ to avoid the empty word), start state $q_0$, accept states $\{[0]_3\}$ and $\delta(q, w) =\begin{cases} [w]_3 &\mbox{if } q = q_0 \\[q + w]_3 & \mbox{else } \end{cases}$Of course, it doesn't work that way for natural numbers divisible by 43. For 43 itself, I would end in $[7]_{43}$, which wouldn't be an accepting state. Is there any way I can add something there or do you have other suggestions on how to do this? Thanks. | DFA that accepts decimal representations of a natural number divisible by 43 | formal languages;regular languages;finite automata | null |
_webmaster.97032 | I've had a software development portfolio/ blog for a few years with Google Analytics installed on it. I'm not really that bothered about how much traffic the site gets, but nevertheless it's interesting to see some usage data.I noticed something odd recently with a drop in traffic on the website, which I'm hoping someone might be able to explain.Here's the situation:Before February 11th 2016, my most recent post was on September 26th 2014. I hadn't posted in around a year and a half and traffic since around July 2014 was averaging ~70 sessions a day (> 95% from organic search). On February 11th I updated my portfolio with a new blog post and added a single CSS property. From the day after (February 12th) until circa June 13th my traffic severely dropped to approximately 10 sessions a day.Here's an image depicting the above description (hopefully will show the general trend):It's started picking up again now but I find it odd that the drop coincided with a new blog post. Is this a coincidence? Again, I'm not bothered about the traffic levels; I'm more interested in the cause and whether there's something I'm not understanding about SEO/ Google Analytics. Perhaps they changed something in their algorithm, or was my website blacklisted for some reason?Thanks! | Unusual drop in traffic | google analytics;google index;traffic | This sounds to me like a Google Penalty issue.A sharp decline such as what you have shown that has lasted for 4 months the way your graph shows, in combination with your assertion that greater than 95% of your traffic comes from organic searches backs up that statement.There are two main penalties that you can get. The first is a manual action from the Google Spam team, and the only way to check this is to go to Google Webmaster Tools and see if you have any notification. An example of thew notification you may see could be...The other option is an algorithmic penalty which is harder to diagnose. By using a site such as https://moz.com/google-algorithm-change you can see when algorithmic changes have been applied and how the relate to your drop in traffic. Based on the above report I can not see any algorithmic change that may have affected you but that is not to say that your recent change didn't trigger an algorithm alarm.Backlinks can also cause substantial issues including backlimks from...Sites that are penalized or banned from GoogleWebsites with duplicate contentWebsites unrelated to your nicheSpammy comments and forum profilesSites with thin contentSite wide back linksOver 95% of Google Penalties are related to a websites backlinks.From what you have said it has started to pick up again and so it could be a temporary ranking issue that has resolved it.There is the possibility that due to the sites inactivity for such a long time the ranking reduced automatically and that it coincidentally reduced so substantially the day after you posted a new article, but I do not believe that is what happened as the rank increase from fresh content would not take months to apply as has been the case here, this does seem more to do with a penalty. |
_unix.52289 | I am using find . -name '*.[cCHh][cC]' -exec grep -nHr $1 {} ';'find . -name '*.[cCHh]' -exec grep -nHr $1 {} ';'to search for a string in all files ending with .c, .C, .h, .H, .cc and .CC listed in all subdirectories. But since this includes two commands this feels inefficient.How do I write a regex to include .c,.C,.h,.H,.cc and .CC files using one single regex?EDIT: I am running this on bash on a Linux machine. | Compacting `find` name patterns | find;efficiency;regular expression | As you (incorrectly what you used is a shell pattern) mentioned it in the subject, you should use regular expressions:find . -iregex '.*\.[ch]+'The above is lazy approach, which will also find .ch, .hh and alike, if there exists. For exact matches you still have to enumerate what you want, but that is still easier with regular expressions:find . -regex '.*\.\(c\|C\|cc\|CC\|h\|H\)' |
_webmaster.22966 | What is the process to copy an entire .NET website from one server to another server? Both sites are running Windows Server 2008, IIS7, and SQL 2008?The base site is the live siteThe new site is going to be used as a development siteThe server hosting the development site has other, existing sites in IISThe servers are on different networks and have different internet domain namesPart of this is easily done, such as copying the database and restoring it. The same can be said for the copying of the directory of files the IIS site gets pointed to -- no help needed for those tasks.After the database and files are copied over, what are the necessary steps to make the site functional on the second server? | How to move IIS7 site from one server to another | iis7;webserver;administration | Web Deployment Tool is currently the Microsoft recommended way of copying and synchronizing web applications across IIS servers.Read more here: http://learn.iis.net/page.aspx/446/synchronize-iis/I noticed you didn't want to use MSDeploy but you didn't mention why. |
_unix.6220 | I've installed chromium, but it deeply sucks that it uses my mother tongue (german) in its UI and for websites by default. I want the english back, like firefox did. I'm using archlinux's default packages. I looked into the settings dialogs, but I found nothing useful. | How can I change the language in chromium? | chrome;i18n | I use version 6.0.472.63 and I found Change font and language settings under Customize and control Chromium --> Options --> Under the hood. |
_unix.305939 | When I type msfconsole in my terminal i got something like this:bash: /usr/bin/msfconsole: /usr/share/metasploit-framework/ruby: bad interpreter:Please help me.After ls -l /usr/share/metasploit-framework/ruby I got:total 276drwxr-xr-x 9 root root 4096 Aug 24 13:10 2.2.0drwxr-xr-x 12 root root 4096 Aug 26 03:55 2.3.0drwxr-xr-x 2 root root 4096 Aug 24 14:19 backward-rw-r--r-- 1 root root 6252 Apr 14 08:16 changelog.gz-rw-r--r-- 1 root root 3036 Apr 14 08:16 copyright-rw-r--r-- 1 root root 4232 Apr 25 19:06 debug.h-rw-r--r-- 1 root root 5785 Apr 25 19:06 defines.h-rw-r--r-- 1 root root 1316 Jun 18 01:28 digest.h-rw-r--r-- 1 root root 17849 Apr 25 19:06 encoding.h-rw-r--r-- 1 root root 36172 Apr 25 19:06 intern.h-rw-r--r-- 1 root root 5200 Apr 25 19:06 io.h-rw-r--r-- 1 root root 4953 Apr 25 19:06 missing.h-rw-r--r-- 1 root root 318 Apr 14 08:16 NEWS.Debian.gz-rw-r--r-- 1 root root 37881 Apr 25 19:06 oniguruma.h-rw-r--r-- 1 root root 1191 Apr 14 08:16 README.Debian-rw-r--r-- 1 root root 777 Apr 25 19:06 regex.h-rw-r--r-- 1 root root 1465 Apr 25 19:06 re.h-rw-r--r-- 1 root root 69536 Apr 25 19:06 ruby.h-rw-r--r-- 1 root root 5339 Apr 25 19:06 st.h-rw-r--r-- 1 root root 374 Apr 25 19:06 subst.h-rw-r--r-- 1 root root 996 Apr 25 19:06 thread.h-rw-r--r-- 1 root root 1333 Apr 25 19:06 thread_native.h-rw-r--r-- 1 root root 2050 Apr 25 19:06 util.hdrwxr-xr-x 4 root root 4096 Aug 24 14:18 vendor_ruby-rw-r--r-- 1 root root 1854 Apr 25 19:06 version.h-rw-r--r-- 1 root root 1677 Apr 25 19:06 vm.h | Msfconsole-metasploit framework bad ruby interpreter | kali linux | null |
_reverseengineering.13904 | I'm quite confused with the movsx(move with sign extension)I'm trying to convert assembly code to C. but stuck with movsx part. this is the code I got so far. #include <stdio.h>#include <windows.h>int main(){ char str[24] = Aegisone security;//17+1 char *a; a = &str[24]-24; char a2 = -*(a+6); //str[32] = *(a+6); //char str2[4]=a; MessageBox(0,Hello,reversing,0); return 0;}can you help show me some example to usage of movsx thing in c code?the part I troubled isMOVSX EDX , BYTE PTR DS:[ECX+6]MOV DWORD PTR SS: [EBP-20],EDX'I need some more detail explanation about this partmy C-code above showing little bit different MOVESX EDX,BYTE PTR DS:[ECX+6]NEG EDXMOV BYTE PTR SS:[EBP-20],DL | move with sign extension in c code | disassembly;assembly;decompilation;c | null |
_unix.341615 | I want to display a dialog at startup after the user log in?How would you suggest to do automatically launch a dialog at startup?Example of dialogue:zenity --question | How to start a dialog at startup after login in? | startup;init.d;rc;xinit | null |
_webapps.107950 | I created a document in Google Docs, downloaded in Open Document Format, edited with LibreOffice Writer, then uploaded the edited document back to Google Docs. In the new document:There exists a table which causes the following text to be pushed onto the next page, rather than immediately after the table.If new tables are inserted after the first table, they stay on the same page rather than being pushed onto the next page like the ordinary text is.If the table is deleted the text flows properly again.If a new table is inserted the problem comes back.If enough of the following text is deleted the problem also goes away.These problems don't exist in the original document.Here is a copy of the problem document, with the text before the problem area removed | Table forces following text onto next page after editing in LibreOffice | google documents | null |
_unix.317925 | Need to do exactly as asked in question. Ubuntu 14.04 Trusty Tahr.Suppose I have directory called 'testmag' which may contain 100s of xml files and directories which in turn contain many xml files as well. I don't know names of any xml files but I know 1 of them contains tag <dbname>....</dbname>.Now how to find the file containing the aforementioned tag and grep the tag's value as output in terminal | Search all xml files recursively in directory for a specific tag and grep the tag's value | command line;grep;terminal;find;xml | Here is a solution with find that will also output the filenames of files containing a match:find . -name *.xml -exec grep '<dbname>' {} \; \ -exec echo -e {}\n \; \ | sed 's/<dbname>\(.*\)<\/dbname>/\1/g'Explanationfind . -name *.xml find all xml files recursively from current directory-exec grep '<dbname>' {} \; on each file search for pattern <dbname>-exec echo -e {}\n \; echo filename + new line (-e option makes echo interpret \n)| sed 's/<dbname>\(.*\)<\/dbname>/\1/g' pipe output to sed to print only the field contained between the <dbname></dbname> tags.NOTE1: you can format output in your echo -e ... to have results for each file clearly laid out, e.g. by adding new lines, or lines of underscore, whatever suits your need.NOTE2: path to each file will be given relatively to . (e.g. ./subfolder1/file.xml). If you want absolute path, go for find $PWD -name .... |
_reverseengineering.1463 | I know there are tools for identifying common ciphers and hash algorithms in code, but are there any similar scripts / tools / plugins for common compression algorithms such as gzip, deflate, etc? Primarily aimed at x86 and Windows, but answers for other platforms are welcomed too.Note that I'm looking to find code, not data. | Are there any tools or scripts for identifying compression algorithms in executables? | tools;windows;x86 | signsrch by Luigi Auriemma has signatures for tables used in common compression libraries (zlib etc.). It has been ported as plugins for ImmDbg and IDA.He also has the offzip tool which tries to identify and unpack compressed streams inside a binary. |
_webmaster.62884 | I want to advertise on Google Adwords AND Linked-In. However I want to know which is more successful at getting a conversion.I'm not really sure how to set things up so that I can do this? I have installed Google Analytics. And I have a campaign running but yeah no idea really. Do I just set up a goal and then GA will tell me where the referral came from? | How do I track where a conversion 'came from'? | google analytics;google adwords;linkedin | Yes, first you need to define a conversion. Easiest way to do it without custom programming is to define URL Conversions. For this, you must have unique URLs which only happen when conversion is made (e.g. a special URL on a thank-you page which is shown only after conversion is made).When you have conversions setup, there are reports which allow you to see the referrals for conversions. |
_cs.12781 | As I remember:A decision problem is a problem that has the answer yes or no.An algorithm (in the context of automata theory) answers yes or no; it halts on all inputs, accepted or not.A TM represents an algorithm. The TM accepts an input string and executes with that input. If the machine ends up in an accept state, the answer is yes, otherwise no.How does a yes/no problem relate to general algorithms we are doing that have more than yes/no problems? Or is that every problem can be thought as a yes/no problem, i.e. is this a function f produce 5 (or whatever input) with input 2 (or whatever output)? | How a TM can represent any algorithm? | computability;turing machines | Don't forget that the final content of the tape can be treated like the output of the algorithm that the TM computes; in other words, a TM is able to compute a function: there is no reject state but only an accept state and the function result is the content of the tape at the end of the computation.But if you want to learn more on the relation between decision problems and function problems , (quickly) read the Decision Problem - Equivalence with functions problems entry on Wikipedia, and then search some lectures online on the subject. |
_unix.44863 | I want to setup a new TLD (foo.) for my the private network so that I can host some child domains which will be accessible from within the network. For this purpose I have setup a DNS server (172.16.100.1) for foo.. For this I created a zone file foo-zonedb.rr with the following records:$ORIGIN foo.$TTL 100@ IN SOA ns1.tld.foo. hostmaster.tld.foo ( 2012030701 900 300 300 600 )@ 300 IN NS ns1.tld.foo.@ 300 IN A 172.16.143.197ns1.tld.foo. 300 IN A 172.16.143.197And also I have added the following entries in /etc/named.confzone foo. { type master; file foo-zonedb.rr; notify explicit; };Now suppose every machine on the network uses 172.16.1.1 as their DNS server. What configuration should I have to do on 172.16.1.1 so that it won't redirect DNS request for foo. domain to root DNS servers? | Creating a new TLD for private network | dns;bind | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.