I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.
I was looking at the new APIs introduced in Android 4.2. While looking at the UserManager class I came across the following method:
public boolean isUserAGoat()
Used to determine whether the user making this call is subject to teleportations.
Returns whether the user making this call is a goat.
How and when should this be used?
Answer
From their source, the method used to return false until it was changed in API 21.
/** * Used to determine whether the user making this call is subject to * teleportations. * @return whether the user making this call is a goat */ public boolean isUserAGoat() { return false;
}
It looks like the method has no real use for us as developers. Someone has previously stated that it might be an Easter egg.
In API 21 the implementation was changed to check if there is an installed app with the package com.coffeestainstudios.goatsimulator
/** * Used to determine whether the user making this call is subject to * teleportations.
* *
As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can * now automatically identify goats using advanced goat recognition technology.
* * @return Returns true if the user making this call is a goat. */ public boolean isUserAGoat() { return mContext.getPackageManager() .isPackageAvailable("com.coffeestainstudios.goatsimulator"); }
I'm struggling to wrap my head around the concept of async and promises in js. I can't figure out why the code below doesn't print anything on my console.
I'm assuming it's because the code inside my Promise is not asynchronous, but isn't that the point of a promise: to make something synchronous become asynchronous?
If that's not the case, how could I truly "transform" a sync code into async without using any built in js functions (setTimeOut,etc)?
function countdown(seconds) { return new Promise(function(resolve, reject) { for (let i = seconds; i >= 0; i--) { if (i > 0) console.log(i + '...'); else resolve(console.log("GO!")); }
how could I truly "transform" a sync code into async without using any built in js functions (setTimeOut,etc)?
By it's nature, javascript code is synchronous(waits for howls of protest to abate) ...
Every (non-native) function that is asynchronous is due to that function, either
directly calling one of those native asynchronous functions, or
calling other functions that call functions etc that eventually call one of these asynchronous functions directly
the only way to transform some code from synchronous to asynchronous is to use one of the many "native" functions that are asynchronous in nature (again, either directly, or indirectly via other functions that eventually will have to call one of these asynchronous functions directly)
I'm trying to make some text on a webpage look like a page from Gopherspace. In other words, monospace font with a maximum of 80 columns. I figured that if the font is monospace and I set the width of the containing element to 80em, that would constrain it to a perfect 80 columns since every character should be the same width in a monospace font.
The colors I've added are just to make it easier to tell where line breaks occur.
In case this works on some browsers/computers and not others, here's what I see on my computer, which is running Firefox 65.0.1 on Mac OS 10.14.3.
Why is this div almost twice the size of 80 columns of text and how can I fix it?
The font size of a element (measured in em) is the height of the font, not the width. (Originally, the word "em" refers to the width of the M, but not many fonts have an M exactly the width of 1em any more.)
The solution is to use ch as a unit for the width. In monospace fonts, 1ch is the width of a character. In variable-width fonts, 1ch is the width of the 0 (zero) character. See the official definition at the W3C or the more readable MDN version.
I've looked at other answers to this question, as there have been similar ones before, but I just can't get it work. I'm new to javascript, so please be kind.
From the body of an email, I need to find a phrase that will end with "number:" followed by a number.
e.g. Sample Email Body:
... customer reference number: 123456 or site reference number : 827893
...
then that reference number '123456' or whatever it is, needs to be a variable/value I'll use elsewhere.
I don't want anything before the number, and I don't want anything after the number (eg. the next lines).
Tried this:
var str = "reference number: 1234";
var RefStr = str.match(/number\:\s+(\d+)$/i)
But it returns number: 1234.
I think regex is not the best solution for me.
Edit, I couldn't respond to my own question, and comments don't let me format nicely.
Thanks, even though this worked in a regex checker, trying to use it in the context of the database, didn't work. I'm still working on that.
var str = email.body_text; var refStr = str.match((/number\:\s+(\d+)$/i)[1]); externalReferenceNumberCreate(current.sys_id, 'Client reference number',refStr,'Ref number');
I know line 1 and 3 are correct, so perhaps I've messed the syntax for line 2? As
I understand that this is probably a product specific query, and perhaps more complicated than I thought.
Answer
Alex already gave you the answer: str.match(/number\:\s+(\d+)$/i)[1], which means the result at the index of 1. That index in the array is generated by the usage of the () in your regex. The first index (0) is the answer you've been getting.
func main() { var newfunc func(int) //explicit declaration newfunc = func(i int) { fmt.Println(i) } run(newfunc, 10) //works just fine, even though types seem to differ }
Now, I'm not complaining because it saves me having to explicitly cast newfunc to type MyFunc, as I would have to do in the first example; it just seems inconsistent. I'm sure there is a good reason for it; can anyone enlighten me?
The reason I ask is mainly because I would like to shorten some of my rather long function types in this way, but I want to make sure it's expected and acceptable to do this :)
Answer
Turns out, this is a misunderstanding that I had about how Go dealt with types, which can be resolved by reading the relevant part of the spec:
The relevant distinction that I was unaware of was that of named and unnamed types.
Named types are types with a name, such as int, int64, float, string, bool. In addition, any type you create using 'type' is a named type.
Unnamed types are those such as []string, map[string]string, [4]int. They have no name, simply a description corresponding to how they are to be structured.
If you compare two named types, the names must match in order for them to be interchangeable. If you compare a named and an unnamed type, then as long as the underlying representation matches, you're good to go!
e.g. given the following types:
type MyInt int type MyMap map[int]int type MySlice []int type MyFunc func(int)
the following is invalid:
var i int = 2 var i2 MyInt = 4
i = i2 //both named (int and MyInt) and names don't match, so invalid
the following is fine:
is := make([]int) m := make(map[int]int) f := func(i int){}
//OK: comparing named and unnamed type, and underlying representation
//is the same: func doSlice(input MySlice){...} doSlice(is)
func doMap(input MyMap){...} doMap(m)
func doFunc(input MyFunc){...} doFunc(f)
I'm a bit gutted I didn't know that sooner, so I hope that clarifies the type lark a little for someone else! And means much less casting than I at first thought :)
Edit 1: I've been using chrome --disable-web-security, but now want things to actually work.
Edit 2: Answer:
So, solution for me django-cors-headers config:
CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000' # Here was the problem indeed and it has to be http://localhost:3000, not http://localhost:3000/ )
Answer
This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions :
I'm not very experienced in web programming, and I haven't actually coded anything in Node.js yet, just curious about the event-driven approach. It does seems good.
The article explains some bad things that could happen when we use a thread-based approach to handle requests, and should opt for a event-driven approach instead. In thread-based, the cashier/thread is stuck with us until our food/resource is ready. While in event-driven, the cashier send us somewhere out of the request queue so we don't block other requests while waiting for our food. To scale the blocking thread-based, you need to increase the number of threads. To me this seems like a bad excuse for not using threads/threadpools properly.
Couldn't that be properly handled using IHttpAsyncHandler? ASP.Net receives a request, uses the ThreadPool and runs the handler (BeginProcessRequest), and then inside it we load the file/database with a callback. That Thread should then be free to handle other requests. Once the file-reading is done, the ThreadPool is called into action again and executes the remaining response. Not so different for me, so why is that not as scalable?
One of the disadvantages of the thread-based that I do know is, using threads needs more memory. But only with these, you can enjoy the benefits of multiple cores. I doubt Node.js is not using any threads/cores at all.
So, based on just the event-driven vs thread-based (don't bring the "because it's Javascript and every browser..." argument), can someone point me out what is the actual benefit of using Node.js instead of the existing technology?
That was a long question. Thanks :)
Answer
First of all, Node.js is not multi-threaded. This is important. You have to be a very talented programmer to design programs that work perfectly in a threaded environment. Threads are just hard.
You have to be a god to maintain a threaded project where it wasn't designed properly. There are just so many problems that can be hard to avoid in very large projects.
Secondly, the whole platform was designed to be run asynchronously. Have you see any ASP.NET project where every single IO interaction was asynchronous? simply put, ASP.NET was not designed to be event-driven.
Then, there's the memory footprint due to the fact that we have one thread per open-connection and the whole scaling issue. Correct me if I'm wrong but I don't know how you would avoid creating a new thread for each connection in ASP.NET.
Another issue is that a Node.js request is idle when it's not being used or when it's waiting for IO. On the other hand, a C# thread sleeps. Now, there is a limit to the number of these threads that can sleep. In Node.js, you can easily handle 10k clients at the same time in parallel on one development machine. You try handling 10k threads in parallel on one development machine.
JavaScript itself as a language makes asynchronous coding easier. If you're still in C# 2.0, then the asynchronous syntax is a real pain. A lot of developers will simply get confused if you're defining Action<> and Function<> all over the place and using callbacks. An ASP.NET project written in an evented way is just not maintainable by an average ASP.NET developer.
As for threads and cores. Node.js is single-threaded and scales by creating multiple-node processes. If you have a 16 core then you run 16 instances of your node.js server and have a single Node.js load balancer in front of it. (Maybe a nginx load balancer if you want).
This was all written into the platform at a very low-level right from the beginning. This was not some functionality bolted on later down the line.
Other advantages
Node.js has a lot more to it then above. Above is only why Node.js' way of handling the event loop is better than doing it with asynchronous capabilities in ASP.NET.
Performance. It's fast. Real fast.
One big advantage of Node.js is its low-level API. You have a lot of control.
You have the entire HTTP server integrated directly into your code then outsourced to IIS.
You have the entire nginx vs Apache comparison.
The entire C10K challenge is handled well by node but not by IIS
AJAX and JSON communication feels natural and easy.
Real-time communication is one of the great things about Node.js. It was made for it.
Plays nicely with document-based nosql databases.
Can run a TCP server as well. Can do file-writing access, can run any unix console command on the server.
You query your database in javascript using, for example, CouchDB and map/reduce. You write your client in JavaScript. There are no context switches whilst developing on your web stack.
Rich set of community-driven open-source modules. Everything in node.js is open source.
Small footprint and almost no dependencies. You can build the node.js source yourself.
Disadvantages of Node.js
It's hard. It's young. As a skilled JavaScript developer, I face difficulty writing a website with Node.js just because of its low-level nature and the level of control I have. It feels just like C. A lot of flexibility and power either to be used for me or to hang me.
The API is not frozen. It's changing rapidly. I can imagine having to rewrite a large website completely in 5 years because of the amount Node.js will be changed by then. It is do-able, you just have to be aware that maintenance on node.js websites is not cheap.
I have a select menu that updates a graph .on('change') using d3.
I am trying to get the select menu to have a default text value 'Select from me'.
But when the .on('change') is triggered I don't want this value to update the graph. The way I have it now when you choose to select the default text 'Select from me' it tries to update the graph based on this value.
So is there a way to disable this from acting as an option?
D3 CODE
var select = d3.select('#select').append('select');
I am trying to read a bmp file into a character buffer and transfer it across processes using inter process communication. I accomplished this using following code:
This was working perfectly for me before. But now my program crashes at ImageFile.seekg(0,ios::end) and I cant figure out why. The file opens fine and even the ifstream::good() returns true. Following is my call stack:
StorageTree.exe!std::use_facet >(const std::locale & _Loc) Line 586 C++ msvcp110d.dll!std::basic_istream >::_Sentry_base::_Sentry_base(std::basic_istream > & _Istr) Line 103 C++ msvcp110d.dll!std::basic_istream >::sentry::sentry(std::basic_istream > & _Istr, bool _Noskip) Line 123 C++ msvcp110d.dll!std::basic_istream >::seekg(__int64 _Off, int _Way) Line 876 C++
Pls guide me in the right direction.
Answer
Found the solution to my problem. There wasn't any problem in the code, I had added some more code to the app and hadn't initialised some of my variables thus affecting the entry points and data locations.
I just finished listening to the Software Engineering radio podcast interview with Scott Meyers regarding C++0x. Most of the new features made sense to me, and I am actually excited about C++0x now, with the exception of one. I still don't get move semantics... What is it exactly?
Answer
I find it easiest to understand move semantics with example code. Let's start with a very simple string class which only holds a pointer to a heap-allocated block of memory:
#include #include
class string {
char* data;
public:
string(const char* p) { size_t size = std::strlen(p) + 1; data = new char[size]; std::memcpy(data, p, size); }
Since we chose to manage the memory ourselves, we need to follow the rule of three. I am going to defer writing the assignment operator and only implement the destructor and the copy constructor for now:
~string() { delete[] data; }
string(const string& that)
{ size_t size = std::strlen(that.data) + 1; data = new char[size]; std::memcpy(data, that.data, size); }
The copy constructor defines what it means to copy string objects. The parameter const string& that binds to all expressions of type string which allows you to make copies in the following examples:
string a(x); // Line 1
string b(x + y); // Line 2 string c(some_function_returning_a_string()); // Line 3
Now comes the key insight into move semantics. Note that only in the first line where we copy x is this deep copy really necessary, because we might want to inspect x later and would be very surprised if x had changed somehow. Did you notice how I just said x three times (four times if you include this sentence) and meant the exact same object every time? We call expressions such as x "lvalues".
The arguments in lines 2 and 3 are not lvalues, but rvalues, because the underlying string objects have no names, so the client has no way to inspect them again at a later point in time. rvalues denote temporary objects which are destroyed at the next semicolon (to be more precise: at the end of the full-expression that lexically contains the rvalue). This is important because during the initialization of b and c, we could do whatever we wanted with the source string, and the client couldn't tell a difference!
C++0x introduces a new mechanism called "rvalue reference" which, among other things,
allows us to detect rvalue arguments via function overloading. All we have to do is write a constructor with an rvalue reference parameter. Inside that constructor we can do anything we want with the source, as long as we leave it in some valid state:
string(string&& that) // string&& is an rvalue reference to a string { data = that.data; that.data = nullptr; }
What have we done here? Instead of deeply copying the heap data, we have just copied the pointer and then set the original pointer to null (to prevent 'delete[]' from source object's destructor from releasing our 'just stolen data'). In effect, we have "stolen" the data that originally belonged to the source string. Again, the key insight is that under no circumstance could the client detect that the source had been modified. Since we don't really do a copy here, we call this constructor a "move constructor". Its job is to move resources from one object to another instead of copying them.
Congratulations, you now understand the basics of move semantics! Let's continue by implementing the assignment operator. If you're unfamiliar with the copy and swap idiom, learn it and come back, because it's an awesome C++ idiom related to exception safety.
Huh, that's it? "Where's the rvalue reference?" you might ask. "We don't need it here!" is my answer :)
Note that we pass the parameter thatby value, so that has to be initialized just like any other string object. Exactly how is that going to be initialized? In the olden days of C++98, the answer would have been "by the copy constructor". In C++0x, the compiler chooses between the copy constructor and the move constructor based on whether the argument to the assignment operator is an lvalue or an rvalue.
So if you say a = b, the copy constructor will initialize that (because the expression b is an lvalue), and the assignment operator swaps the contents with a freshly created, deep copy. That is the very definition of the copy and swap idiom -- make a copy, swap the contents with the copy, and then get rid of the copy by leaving the scope. Nothing new here.
But if you say a = x + y, the move constructor will initialize that (because the expression x + y is an rvalue), so there is no deep copy involved, only an efficient move. that is still an independent object from the argument, but its construction was trivial, since the heap data didn't have to be copied, just moved. It wasn't necessary to copy it because x + y is an rvalue, and again, it is okay to move from string objects denoted by rvalues.
To summarize, the copy constructor makes a deep copy, because the source must remain untouched. The move constructor, on the other hand, can just copy the pointer and then set the pointer in the source to null. It is okay to "nullify" the source object in this manner, because the client has no way of inspecting the object again.
I hope this example got the main point across. There is a lot more to rvalue references and move semantics which I intentionally left out to keep it simple. If you want more details please see my supplementary answer.
How can I determine whether a variable is a string or something else in JavaScript?
Answer
You can use typeof operator:
var booleanValue = true; var numericalValue = 354; var stringValue = "This is a String"; var stringObject = new String( "This is a String Object" ); alert(typeof booleanValue) // displays "boolean" alert(typeof numericalValue) // displays "number" alert(typeof stringValue) // displays "string" alert(typeof stringObject) // displays "object"
Example from this webpage. (Example was slightly modified though).
This won't work as expected in the case of strings created with new String(), but this is seldom used and recommended against[1][2]. See the other answers for how to handle these, if you so desire.
I'm on Windows and sometimes edit files with Notepad, which likes to put a BOM at the start of the file (EF BB BF). It's easy overlook this in the diff and commit to Git a Python file with such a BOM, which I've found will not work on Mac.
I want to create a commit trigger that removes the BOM before committing. Or at least rejects the commit.
The best I've come up with is the script below which I put in 'pre-commit'. It removes any BOM but only after the commit, so then I have to make a second commit.
#!/bin/sh
git diff --cached --diff-filter=ACMR --name-only -z *.py | xargs -0 -n 1 sh -c ' for FILE; do sed -b -i -e "1s/^\xEF\xBB\xBF//" "$FILE" done ' sh
I tried to use commands and 'q' like this so the exit code would be 1 if it matched, but it doesn't work.
#!/bin/sh
git diff --cached --diff-filter=ACMR --name-only -z *.py | xargs -0 -n 1 sh -c ' for FILE; do sed -b -i -e "1 /^\xEF\xBB\xBF/ {s/^\xEF\xBB\xBF//;q1};q0" "$FILE" done ' sh
Can someone help fix it?
Answer
You're on the right track.
A good general rule for a pre-commit hook is not to modify the index contents (i.e., "don't change the commit or work dir, nor even try") but rather just to fail the commit, so your second block of code is probably closer—but you're still modifying the files. You can do this if you want, and you can even git add them as well if you really want. It's just generally not a great idea: it tends to be too surprising, and it does unexpected things with carefully staged versions that deliberately differ from the work-directory versions (as produced by git add -p for instance).
You also have two options here: you could inspect only new and modified files (which is what your --diff-filter is for); or you could inspect every file in the index. If you'd like to allow any existing (but unmodified) file to retain an existing Unicode-BOM you definitely want the new-and-modified-only method, so let's stick with that. I'll retain the *.py as well, but we want to protect it from the shell so that it uses git's idea of files whose name ends with .py, not the shell's. In particular, that means that if some .py files exist in the index—and will therefore be committed, if the commit proceeds—but are not in the work directory, they will get checked.
We can simplify the diff filter a bit, by adding --no-renames to the diff command so that R status cannot occur. We also know that C should not occur since we did not supply any -C or --find-copies-harder options. Thus, we start with:
I've taken out the -z: -z is good if we can use xargs -0, but I'm planning to read the file names one at a time instead, since most of these commands really only work on one file at a time. (It's possible to do that with xargs too, but if none of your file names contains a newline, we'll be OK without it.) The -- separates diff options from paths (this seems like it should not be required, but see comments below; and it's generally a good idea anyway).
This produces a list of files to be inspected, so now let's inspect (but not edit) them. If you're on Windows, you may need to modify the below to use whatever limited tools you have; since I'm always on a Linux or Unix box I use head -1 to get the first line, and grep to check for the BOM:
#! /bin/sh git diff --cached --no-renames --diff-filter=AM --name-only -- '*.py' | (status=0; while IFS= read path; do if git show ":$path" | head -1 | grep $'^\xEF\xBB\xBF' >/dev/null; then echo "Error: file '$path' starts with Unicode BOM.'" status=1
fi done exit $status)
Here are the various tricks:
We set IFS to nothing during the read, to allow other kinds of white space. (For methods that work with -z, and hence handle newlines too, see Etan Reisner's comments below.)
We use git show ":$path" to extract the version of the file that's in the index. This may (as with git add -p, for instance) differ from the version of the file in the work-directory.
We use head -1 to discard all but the first line.
We use grep to check for the BOM, which we make with a shell string expansion ($'...'), with grep's output directed to /dev/null so that it doesn't show up (grep -q also works but only if that particular grep supports -q).
We go on to check all listed files, even if some have a BOM.
To work around the shell's subshell-action with pipes (cmd | while ... runs the while in a sub-shell), we set the status in an explicit (parenthesized) sub-shell and exit that sub-shell with that status. That propagates the sub-shell's status—success if no BOMs, failure if some—up to the main shell, where it can become the result of the git hook.
Note: the above is not tested as a complete hook (though I believe it's correct).
Because 0.7 does not have an exact representation as a float or a double: it is not an exact sum of negative powers of 2.
It happens that the closest representation of 0.7 as a is float approximately 0.69999998807907104492, while the closest double representation is 0.69999999999999995559. As you can see, double is slightly greater, which explains the behavior of your program.
Here is a small demo that you could run to see the values on your system:
The takeaway lesson here is that you should not expect double and float representations of mathematically equal numbers to compare for equality correctly. Only a small subset of fractional numbers are representable in floating point system as exact numbers.
Since the overwhelming majority of fractions would be approximated, it is a good idea to do the comparisons with some level of tolerance. For example, instead of writing if (a == 0.7) you should write if (abs(a - 0.7) < 1E-8)
I've been using document.GetElementById succesfully but from some time on I can't make it work again. Old pages in which I used it still work but things as simple as this:
no title
Are giving me "document.getElementById("parsedOutput") is null" all the time now. It doesnt matter if I use Firefox or Chrome or which extensions i have enabled or what headers I use for the html, it's always null and I can't find what could be wrong.
Fatal error: Can't use function return value in write context in C:\xampp\htdocs\requestaccess\index.php on line 51
Answer
empty is not a function -- it's a "language construct" that prior to PHP 5.5 can only be used to evaluate variables, not the results of arbitrary expressions.
If you wanted to use empty in exactly this manner (which is meaningless) you would have to store the result in an intermediate variable:
But you don't need to do anything like this: strlen will always return an integer, so empty will effectively be reduced to checking for zero. You don't need empty for that; zero converts to boolean false automatically, so a saner option is
I am getting the following error message that unable me to continue
Failed to load https://site/data.json: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. localhost/:1 Uncaught (in promise) TypeError: Failed to fetch
I am trying to enable CORS in my react js file but I was not able to get the expected result. I have installed a chrome extension and it work. But to use this in production site, I need to enable it inside my code. How should I properly arrange the code to enable the CORS.
What I want to do is to control the min value too. For example, to have random generated values from 50 to 100. Not starting from zero(0) as other posts do
Answer
As mentioned in mozilla developer you can generate random number between max and min as shown in bottom
Math.floor(Math.random() * (max - min + 1)) + min;
So your code should changed to
var change_price = $('#myprice'); animationTimer = setInterval(function() {
I'm watching Taken (2008) again, and I'm at the infamous "particular set of skills" speech. I just realized he says "...I can tell you I don't have money...".
His wife's new husband is portrayed as an obvious millionaire and this guy just blew the chance that he could get his daughter back by offering them the husband's money.
Can anyone think of any sort of logic or reasoning behind this?
I have a simple class that uses an enum for "status". When I use the getStatus member function, it does indeed return "Busy" but when I print the value, it shows a "1". How can I print "Busy" instead of 1?
C++ does not have the concept of a stack or heap, it is an implementation detail as far as the language is concerned.
That being said, every implementation I know of uses the stack to manage the lifetime of local variables. However, many local variables may end up living entirely within registers and never touch the stack, and some local variables may be optimised out completely. Just because you declare an automatic variable doesn't mean that it will be put on the stack.
e.g.
int main() { int x = rand(); int y = 2; cout << x << y << endl; return 0; }
In this code, with optimisations on, the variable y will almost certainly be removed completely and variable x will probably be given its own register. It's unlikely that either of those variables will ever exist on the stack.
Note: The answers were given in a specific order, but since many users sort answers according to votes, rather than the time they were given, here's an index of the answers in the order in which they make most sense:
(Note: This is meant to be an entry to C++ FAQ. If you want to critique the idea of providing an FAQ in this form, then the posting on meta that started all this would be the place to do that. Answers to that question are monitored in the C++ chatroom, where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.)
I want to pause input in a shell script, and prompt the user for choices. The standard 'Yes, No, or Cancel' type question. How do I accomplish this in a typical bash prompt?
Answer
The simplest and most widely available method to get user input at a shell prompt is the read command. The best way to illustrate its use is a simple demonstration:
while true; do read -p "Do you wish to install this program?" yn case $yn in
[Yy]* ) make install; break;; [Nn]* ) exit;; * ) echo "Please answer yes or no.";; esac done
select yn in "Yes" "No"; do case $yn in Yes ) make install; break;; No ) exit;; esac done
With select you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a while true loop to retry if they give invalid input.
Also, Léa Gris demonstrated a way to make the request language agnostic in her answer. Adapting my first example to better serve multiple languages might look like this:
set -- $(locale LC_MESSAGES) yesptrn="$1"; noptrn="$2"; yesword="$3"; noword="$4"
while true; do read -p "Install (${yesword} / ${noword})? " yn case $yn in ${yesptrn##^} ) make install; break;; ${noptrn##^} ) exit;;
Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.
I have written an app where I need to retrieve the currently logged in user's info when the application runs, before routing is handled. I use ui-router to support multiple/nested views and provide richer, stateful routing.
When a user logs in, they may store a cookie representing their auth token. I include that token with a call to a service to retrieve the user's info, which includes what groups they belong to. The resulting identity is then set in a service, where it can be retrieved and used in the rest of the application. More importantly, the router will use that identity to make sure they are logged in and belong to the appropriate group before transitioning them to the requested state.
$rootScope.$on('$stateChangeStart', function (event, toState) { // listen for when trying to transition states... var isAuthenticated = principal.isAuthenticated(); // check if the user is logged in
if (!toState.data.roles || toState.data.roles.length == 0) return; // short circuit if the state has no role restrictions
if (!principal.isInAnyRole(toState.data.roles)) { // checks to see what roles the principal is a member of
event.preventDefault(); // role check failed, so... if (isAuthenticated) $state.go('account.accessdenied'); // tell them they are accessing restricted feature else $state.go('account.signin'); // or they simply aren't logged in yet } });
$http.get('/svc/account/identity') // now, looks up the current principal .success(function(data) { authority.authorize(data); // and then stores the principal in the service (which can be injected by requiring "principal" dependency, seen above) }); // this does its job, but I need it to finish before responding to any routes/states
}]);
It all works as expected if I log in, navigate around, log out, etc. The issue is that if I refresh or drop on a URL while I am logged in, I get sent to the signin screen because the identity service call has not finished before the state changes. After that call completes, though, I could feasibly continue working as expected if there is a link or something to- for example- the main state, so I'm almost there.
I am aware that you can make states wait to resolve parameters before transitioning, but I'm not sure how to proceed.
Answer
OK, after much hair pulling, here is what I figured out.
As you might expect, resolve is the appropriate place to initiate any async calls and ensure they complete before the state is transitioned to.
You will want to make an abstract parent state for all states that ensures your resolve takes place, that way if someone refreshes the browser, your async resolution still happens and your authentication works properly. You can use the parent property on a state to make another state that would otherwise not be inherited by naming/dot notation. This helps in preventing your state names from becoming unmanageable.
While you can inject whatever services you need into your resolve, you can't access the toState or toStateParams of the state it is trying to transition to. However, the $stateChangeStart event will happen before your resolve is resolved. So, you can copy toState and toStateParams from the event args to your $rootScope, and inject $rootScope into your resolve function. Now you can access the state and params it is trying to transition to.
Once you have resolved your resource(s), you can use promises to do your authorization check, and if it fails, use $state.go() to send them to the login page, or do whatever you need to do. There is a caveat to that, of course.
Once resolve is done in the parent state, ui-router won't resolve it again. That means your security check won't occur! Argh! The solution to this is to have a two-part check. Once in resolve as we've already discussed. The second time is in the $stateChangeStart event. The key here is to check and see if the resource(s) are resolved. If they are, do the same security check you did in resolve but in the event. if the resource(s) are not resolved, then the check in resolve will pick it up. To pull this off, you need to manage your resources within a service so you can appropriately manage state.
Some other misc. notes:
Don't bother trying to cram all of the authz logic into $stateChangeStart. While you can prevent the event and do your async resolution (which effectively stops the change until you are ready), and then try and resume the state change in your promise success handler, there are some issues preventing that from working properly.
You can't change states in the current state's onEnter method.
I am writing a simple reverse proxy in java. So, I have access to all Http requests and responses exchanged between client and server. Sitting at the proxy I am trying to detect SQL Injection Attack.
The Web Server module doesn't parse the parameters for you like PHP does it. You would need to do this yourself.
server.listen(9090, function(request, response) { // parse url property to get the GET parameters console.log('URL: ' + request.url); console.log(" " + JSON.stringify(parseGET(request.url), undefined, 4)); // pretty print
// parse post property to get the POST parameters (message body) console.log('BODY: ' + request.post); };
function parseGET(url){ // adapted from http://stackoverflow.com/a/8486188 var query = url.substr(url.indexOf("?")+1); var result = {}; query.split("&").forEach(function(part) { var e = part.indexOf("=") var key = part.substr(0, e); var value = part.substr(e+1); result[key] = decodeURIComponent(value); });
return result; }
The complete documentation this can be found here.
I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:
var obj1 = { food: 'pizza', car: 'ford' } var obj2 = { animal: 'dog' }
obj1.merge(obj2);
//obj1 now has three properties: food, car, and animal
Does anyone have a script for this or know of a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.
I understand why this happens, and I also know that I could get rid of that space by removing the white-space between the SPAN elements in the HTML source code, like so:
Foo Bar
However, I was hoping for a CSS solution that doesn't require the HTML source code to be tampered with.
I know how to solve this with JavaScript - by removing the text nodes from the container element (the paragraph), like so:
Since this answer has become rather popular, I'm rewriting it significantly.
Let's not forget the actual question that was asked:
How to remove the space between inline-block elements? I was hoping for a CSS solution that doesn't require the HTML source code to be tampered with. Can this issue be solved with CSS alone?
It is possible to solve this problem with CSS alone, but there are no completely robust CSS fixes.
The solution I had in my initial answer was to add font-size: 0 to the parent element, and then declare a sensible font-size on the children.
This works in recent versions of all modern browsers. It works in IE8. It does not work in Safari 5, but it does work in Safari 6. Safari 5 is nearly a dead browser (0.33%, August 2015).
Most of the possible issues with relative font sizes are not complicated to fix.
However, while this is a reasonable solution if you specifically need a CSS only fix, it's not what I recommend if you're free to change your HTML (as most of us are).
This is what I, as a reasonably experienced web developer, actually do to solve this problem:
FooBar
Yes, that's right. I remove the whitespace in the HTML between the inline-block elements.
It's easy. It's simple. It works everywhere. It's the pragmatic solution.
You do sometimes have to carefully consider where whitespace will come from. Will appending another element with JavaScript add whitespace? No, not if you do it properly.
Let's go on a magical journey of different ways to remove the whitespace, with some new HTML:
Or, you can even skip certain closing tags entirely (all browsers are fine with this):
Item 1
Item 2
Item 3
Now that I've gone and bored you to death with "one thousand different ways to remove whitespace, by thirtydot", hopefully you've forgotten all about font-size: 0.
I'm a bit confused about how Java generics handle inheritance / polymorphism.
Assume the following hierarchy -
Animal (Parent)
Dog - Cat (Children)
So suppose I have a method doSomething(List animals). By all the rules of inheritance and polymorphism, I would assume that a Listis a List and a Listis a List - and so either one could be passed to this method. Not so. If I want to achieve this behavior, I have to explicitly tell the method to accept a list of any subclass of Animal by saying doSomething(List animals).
I understand that this is Java's behavior. My question is why? Why is polymorphism generally implicit, but when it comes to generics it must be specified?
Answer
No, a List is not a List. Consider what you can do with a List - you can add any animal to it... including a cat. Now, can you logically add a cat to a litter of puppies? Absolutely not.
// Illegal code - because otherwise life would be Bad List dogs = new ArrayList(); // ArrayList implements List List animals = dogs; // Awooga awooga animals.add(new Cat()); Dog dog = dogs.get(0); // This should be safe, right?
Suddenly you have a very confused cat.
Now, you can't add a Cat to a List because you don't know it's a List. You can retrieve a value and know that it will be an Animal, but you can't add arbitrary animals. The reverse is true for List - in that case you can add an Animal to it safely, but you don't know anything about what might be retrieved from it, because it could be a List