A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier. These are declarations:
extern int bar; extern int g(int, int); double f(int, double); // extern can be omitted for function declarations class foo; // no extern allowed for type declarations
A definition actually instantiates/implements this identifier. It's what the linker needs in order to link references to those entities. These are definitions corresponding to the above declarations:
int bar; int g(int lhs, int rhs) {return lhs*rhs;} double f(int i, double d) {return i+d;} class foo {};
A definition can be used in the place of a declaration.
An identifier can be declared as often as you want. Thus, the following is legal in C and C++:
double f(int, double); double f(int, double); extern double f(int, double); // the same as the two above extern double f(int, double);
However, it must be defined exactly once. If you forget to define something that's been declared and referenced somewhere, then the linker doesn't know what to link references to and complains about a missing symbols. If you define something more than once, then the linker doesn't know which of the definitions to link references to and complains about duplicated symbols.
/>
Since the debate what is a class declaration vs. a class definition in C++ keeps coming up (in answers and comments to other questions) , I'll paste a quote from the C++ standard here. At 3.1/2, C++03 says:
A declaration is a definition unless it [...] is a class name declaration [...].
3.1/3 then gives a few examples. Amongst them:
[Example: [...] struct S { int a; int b; }; // defines S, S::a, and S::b [...] struct S; // declares S —end example
To sum it up: The C++ standard considers struct x; to be a declaration and struct x {}; a definition. (In other words, "forward declaration" a misnomer, since there are no other forms of class declarations in C++.)
Thanks to href="https://stackoverflow.com/users/34509/johannes-schaub-litb">litb (Johannes Schaub) who dug out the actual chapter and verse in one of his answers.
I wrote a dll project in c#. I added a service reference. A app.config was automatically generated. In the same solution I have an asp.net project.
If I copy paste the relevant configuration from the app.config to the web.config and change the client url - will it override the service url in the app.config?
The funny thing is that everything works OK even without copying this section to the web.config. How come?
TIA
Answer
The config schema is the same for web and app.config. There are some sections that will only make sense for web apps, but generally not the other way around. You should be just fine copy-pasting your configuration.
The web project only looks at Web.config, so you will need to copy the configuration to your web.config.
I want to display a dialog/popup window with a message to the user that shows "Are you sure you want to delete this entry?" with one button that says 'Delete'. When Delete is touched, it should delete that entry, otherwise nothing.
I have written a click listener for those buttons, but how do I invoke a dialog or popup and its functionality?
I have an variable called data, and it has today's date as in this format: Thu May 24 13:14:41 BRT 2018. Then I format it to MySQL's Date type format, which is yyyy-MM-dd. This code does it:
String dataFormatada = new SimpleDateFormat("yyyy-MM-dd").format(data);
What I want to do is to bring it back to Date type. I've tried somethings but they didn't work. The main solution is to do as discribed in this other href="https://stackoverflow.com/questions/4496359/how-to-parse-date-string-to-date"> questioin, and with a little mod I got to what's suposely what I want:
String target = "Thu Sep 28 20:29:30 JST 2000"; DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); Date result = df.parse(target);
System.out.println(result);
But it doesn't work as I get this error when trying to parse:
So I cannot just reformat the data variable, and I cannot bring dataFormatada back to Date format. How do I bring dataFormatada to Date type formatted as yyyy-MM-dd?
itemprop="text">
class="normal">Answer
Your target String format is in EEE MMM dd HH:mm:ss zzz yyyy format. So you need to use EEE MMM dd HH:mm:ss zzz yyyy as pattern instead of yyyy-MM-dd.
String target = "Thu Sep 28 20:29:30 JST 2000"; DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); Date result = df.parse(target);
System.out.println(result);
And if you want convert Date object i.e result to yyyy-MM-dd then please use the below code.
DateFormat dfDateToStr = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
So I found this href="https://stackoverflow.com/questions/4851075/universally-compiler-independent-way-of-implementing-an-unused-macro-in-c-c/4851173#4851173">macro on SO:
#define UNUSED(x) (void)(sizeof((x), 0))
and this (still) produces the following warning:
main.c:11:36: warning: left-hand operand of comma expression has no effect [-Wunused-value]
#define UNUSED(x) (void)(sizeof((x), 0))
Whereas the simpler version, a normal void cast: #define UNUSED(x) (void)(x) is warning-free.
What could be the reason behind it? In general warnings are a sign of high-risk situations. Is here the given warning really useful?
I am interested in C-explanation.
itemprop="text">
class="normal">Answer
This macro seems inappropriate for your compiler at the current warning level.
You could use this simpler version:
#define UNUSED(x) (void)(sizeof(x))
x will not be evaluated either but is used so the compiler should not complain about x being unused, not about the left hand side of the , operator being unused in the expression.
I am using Python trying to figure out a key word and I see the word, "kwargs", which I know is some kind of argument in the called function but I can not find what it means or stands for anywhere.
For example, this entry in the Python documents says...
I was having a chat this morning about jury duty and I thought of a scene from a film.
The set up is that whoever is being tried in this case has the jury paid off, and the prosecutor or cops involved discover this just as the trial is about to start.
They go talk to the judge, and he comes back in looking all shaken and orders the bailiff to swap the jury with a jury in another trial which is just about to start.
When asked how they got him to do the swap the prosecutor or cops say something like we showed him a list of names paid off, and the his (the judge) was on the list.
Can someone tell me what movie this is from?
itemprop="text">
class="normal">Answer
This is from href="http://www.imdb.com/title/tt0094226/">The Untouchables. Kevin Costner (Eliot Ness) shows the list to the judge at the beginning of the trial of Al Capone.
I am alittle confuse about CSS Selectors, I understand that we can group multiple css selectors with a comma if they share similar attributes, but what about multiple css selectors without commas e.g like this:
I am making some matrix multiplication benchmarking, as previously mentioned in href="https://stackoverflow.com/questions/6058139/why-is-matlab-so-fast-in-matrix-multiplication">Why is MATLAB so fast in matrix multiplication?
Now I've got another issue, when multiplying two 2048x2048 matrices, there is a big difference between C# and others. When I try multiply only 2047x2047 matrices, it seems normal. Added some others for comparsion too.
1024x1024 - 10 seconds.
1027x1027 - 10 seconds.
2047x2047 - 90 seconds.
2048x2048 - 300 seconds.
2049x2049 - 91 seconds. (update)
2500x2500 - 166 seconds
That is three and a half minute difference for the 2k by 2k case.
using 2dim arrays
//Array init like this int rozmer = 2048; float[,] matice = new float[rozmer, rozmer];
//Main multiply code for(int j = 0; j < rozmer; j++) { for (int k = 0; k < rozmer; k++)
{ float temp = 0; for (int m = 0; m < rozmer; m++)
{ temp = temp + matice1[j,m] * matice2[m,k];
} matice3[j, k] = temp; }
}
itemprop="text">
class="normal">Answer
This probably has do with conflicts in your L2 cache.
Cache misses on matice1 are not the problem because they are accessed sequentially. However for matice2 if a full column fits in L2 (i.e when you access matice2[0, 0], matice2[1, 0], matice2[2, 0] ... etc, nothing gets evicted) than there is no problem with cache misses with matice2 either.
Now to go deeper in how caches works, if byte address of your variable is X, than the cache line for it would be (X >> 6) & (L - 1). Where L is total number of cache lines in your cache. L is always power of 2. The six comes from fact that 2^6 == 64 bytes is standard size of cache line.
Now what does this mean? Well it means that if I have address X and address Y and (X >> 6) - (Y >> 6) is divisible by L (i.e. some large power of 2), they will be stored in the same cacheline.
Now to go back to your problem what is the difference between 2048 and 2049,
when 2048 is your size:
if you take &matice2[x, k] and &matice2[y, k] the difference (&matice2[x, k] >> 6) - (&matice2[y,k] >> 6) will be divisible by 2048 * 4 (size of float). So a large power of 2.
Thus depending on size of your L2 you will have a lot of cache line conflicts, and only utilize small portion of your L2 to store a column, thus you wont actually be able to store full column in your cache, thus you will get bad performance.
When size is 2049, then the difference is 2049 * 4 which is not power of 2 thus you will have less conflicts and your column will safely fit into your cache.
Now to test this theory there are couple things you can do:
Allocate your array matice2 array like this matice2 [razmor, 4096], and run with razmor = 1024, 1025 or any size, and you should see very bad performance compared to what you had before. This is because you forcefully align all columns to conflict with each other.
Then try matice2 [razmor, 4097] and run it with any size and you should see much better performance.
I would like to generate string matching my regexes using Python 3. For this I am using handy library called href="https://bitbucket.org/leapfrogdevelopment/rstr/" rel="nofollow noreferrer">rstr.
^[abc]+.
[a-z]+
I must find a generic way, how to create string that would match both my regexes.
Modify both regexes or join them in any way. This I consider as ineffective solution, especially in the case if incompatible regexes:
import re import rstr
regex1 = re.compile(r'^[abc]+.')
regex2 = re.compile(r'[a-z]+')
for index in range(0, 1000):
generated_string = rstr.xeger(regex1) if re.fullmatch(regex2, generated_string): break; else: raise Exception('Regexes are probably incompatibile.')
print('String matching both regexes is: {}'.format(generated_string))
Is there any workaround or any magical library that can handle this? Any insights appreciated.
Asker already has the string, which he just want to check against multiple regexes in the most elegant way. In my case we need to generate string in a smart way that would match regexes.
Answer
I solved this using a little alternative approach. Notice second regex is basically insurance so only lowercase letters are generated in our new string.
I used Google's python package sre_yield which allows charset limitation. Package is also available on PyPi. My code:
I'm trying to develop a html5 mobile web application using the sencha touch. I need to save client's data in browser storage for a long time. At first i used a localstorage to save them. But my colleague recommended to use cookies instead of the localstorage. I need to warn you that i don't use user's data in server-side and size of data is small. What should i use localstorage or cookies in this case?
Answer
I think in this situation local Storage would do better,because
Cookies are used by server side and you said ,you don't use users's data in server side.
Your data size is small and you need to store it for long time,cookie has expiration date,but with local storage there is no such,either you have remove it programmatic-ally using java script or by clearing browser cache.
I am trying to add a object to a ArrayList and its throwing ArrayIndexOutOfBoundsException Following is the code
private void populateInboxResultHolder(List inboxErrors){ inboxList = new ArrayList(); try{ inboxHolder = new InboxResultHolder(); //Lots of Code
inboxList.add(inboxHolder);
}catch(Exception e){
e.printStackTrace();
} }
And the exception is
[3/7/12 15:41:26:715 UTC] 00000045 SystemErr R java.lang.ArrayIndexOutOfBoundsException [3/7/12 15:41:26:721 UTC] 00000045 SystemErr R at java.util.ArrayList.add(ArrayList.java:378)
[3/7/12 15:41:26:721 UTC] 00000045 SystemErr R at com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.populateInboxResultHolder(InboxSearchBean.java:388)
[3/7/12 15:41:26:721 UTC] 00000045 SystemErr R at com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.searchInboxErrors(InboxSearchBean.java:197) [3/7/12 15:41:26:721 UTC] 00000045 SystemErr R at com.ml.fusion.ui.common.web.bean.inbox.InboxSearchBean.viewInbox(InboxSearchBean.java:207)
But according to the signature of ArrayList.add it should not throw this exception. Please help.
file = open("Exported.txt", "w") file.write("Text to write to file") file.close() #This close() is important
Another way to do so would to be:
with open('Exported.txt', 'w') as file: file.write("Text to write to file")
This is a program I made to write a txt file:
import os.path
def start():
print("What do you want to do?") print(" Type a to write a file") print(" Type b to read a file") choice = input(" -") if choice == "a": create() elif choice == "b":
read()
else: print("Incorrect spelling of a or b\n\n") start()
def create():
print() filename = input("What do you want the file to be called?\n") if os.path.isfile(filename):
print("This file already exists") print("Are you sure you would like to overwrite?") overwrite = input("y or n") if overwrite == "y": print("File has been overwritten") write(filename)
else: print("I will restart the program for you") elif not os.path.isfile(filename): print("The file has not yet been created")
write(filename) else:
print("Error")
def write(filename): print()
print("What would you like the word to end writing to be?") keyword = input() print("What would you like in your file?") text = "" filename = open(filename, 'w') while text != keyword: filename.write(text)
filename.write("\n") text = input()
def read():
print() print("You are now in the reading area") filename = input("Please enter your file name: -") if os.path.isfile(filename): filename = open(filename, 'r')
print(filename.read()) elif not os.path.isfile(filename):
I have a template from where I want to navigate to a next state
data-ng-click="openDialog()">open ME!
ui-sref="secondState">click here
but as soon I click this anchor tag it navigates me back to home page. ie not to the state I intend to go. The main issue is URL(i guess) any help will be appreciated.
A fair amount of the second act of The Dark Knight Rises has a class warfare plotline. This is foreshadowed in the trailers with Selina Kyle's "there's a storm coming" monologue. Some of the verbiage and themes of this portion of the film seem to mirror the href="http://en.wikipedia.org/wiki/Occupy_movement">Occupy Movement, and I wanted to know if this was on purpose.
Did the writers of The Dark Knight Rises purposefully model this plotline on the Occupy Movement, or were they pulling from some other source?
Answer
In an interview with Rolling Stone, director href="http://www.rollingstone.com/movies/news/christopher-nolan-dark-knight-rises-isn-t-political-20120720">Christopher Nolan insists his film is apolitical:
In the new movie, you have Bane more or less trick Gotham's 99 percent into rising up against the rich – is that intended as an anti-Occupy
Wall Street statement?
I've had as many conversations with people who have seen the film the other way round. We throw a lot of things against the wall to see if it sticks. We put a lot of interesting questions in the air, but that's simply a backdrop for the story. What we're really trying to do is show the cracks of society, show the conflicts that somebody would try to wedge open. We're going to get wildly different interpretations of what the film is supporting and not supporting, but it's not doing any of those things. It's just
telling a story. If you're saying, “Have you made a film that's supposed to be criticizing the Occupy Wall Street movement?” – well, obviously, that's not true.
But the movie certainly suggests that there's a great danger of populist movements being pushed too far.
If the populist movement is
manipulated by somebody who is evil, that surely is a criticism of the evil person. You could also say the conditions the evil person is
exploiting are problematic and should be addressed.
The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation:
col_name COLLATE latin1_general_cs LIKE 'a%' col_name LIKE 'a%' COLLATE latin1_general_cs col_name COLLATE latin1_bin LIKE 'a%' col_name LIKE 'a%' COLLATE latin1_bin
If you want a column always to be treated in case-sensitive fashion, declare it with a case sensitive or binary collation.
Consider the following spin_lock() implementation, originally from href="https://stackoverflow.com/a/32658335/3169754">this answer:
void spin_lock(volatile bool* lock) { for (;;) { // inserts an acquire memory barrier and a compiler barrier if (!__atomic_test_and_set(lock, __ATOMIC_ACQUIRE)) return;
while (*lock) // no barriers; is it OK?
cpu_relax();
} }
What I already know:
volatile prevents compiler from optimizing out *lock re-read on each iteration of the while loop;
volatile href="https://stackoverflow.com/questions/26307071/does-the-c-volatile-keyword-introduce-a-memory-fence">inserts neither memory nor compiler barriers;
such an implementation actually works in GCC for x86 (e.g. in Linux kernel) and some other architectures;
at least one memory and compiler barrier href="https://jfdube.wordpress.com/2012/03/08/understanding-memory-ordering/" rel="nofollow noreferrer">is required in spin_lock() implementation for a generic architecture; this example inserts them in href="https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html" rel="nofollow noreferrer">__atomic_test_and_set().
Questions:
Is volatile enough here or are there any architectures or compilers where memory or compiler barrier or atomic operation is required in the while loop?
1.1 According to C++ standards?
1.2 In practice, for known architectures and compilers, specifically for GCC and platforms it supports?
Is this implementation safe on all architectures supported by GCC and Linux? (It is at least inefficient on some architectures, right?)
Is the while loop safe according to C++11 and its memory model?
/>
There are several related questions, but I was unable to construct an explicit and unambiguous answer from them:
class="post-text" itemprop="text">
class="normal">Answer
Is volatile enough here or are there any architectures or compilers where memory or compiler barrier or atomic operation is required in the while loop?
will the volatile code see the change. Yes, but not necessarily as quickly as if there was a memory barrier. At some point, some form of synchronization will occur, and the new state will be read from the variable, but there are no guarantees on how much has happened elsewhere in the code.
It is the memory model and memory order which defines the generalized hardware that the code needs to work on. For a message to pass between threads of execution, an inter-thread-happens-before relationship needs to occur. This requires either...
A synchronizes-with B
A has a std::atomic operation before B
A indirectly synchronizes with B (through X).
A is sequenced before X which inter-thread happens before B
A interthread happens before X and X interthread happens before B.
As you are not performing any of those cases there will be forms of your program where on some current hardware, it may fail.
In practice, the end of a time-slice will cause the memory to become coherent, or any form of barrier on the non-spinlock thread will ensure that the caches are flushed.
Not sure on the causes of the volatile read getting the "current value".
1.2 In practice, for known architectures and compilers, specifically for GCC and platforms it supports?
As the code is not consistent with the generalized CPU, from C++11 then it is likely this code will fail to perform with versions of C++ which try to adhere to the standard.
From href="http://en.cppreference.com/w/cpp/language/cv" rel="nofollow noreferrer">cppreference : const volatile qualifiers Volatile access stops optimizations from moving work from before it to after it, and from after it to before it.
"This makes volatile objects suitable for communication with a signal handler, but not with another thread of execution"
So an implementation has to ensure that instructions are read from the memory location rather than any local copy. But it does not have to ensure that the volatile write is flushed through the caches to produce a coherent view across all the CPUs. In this sense, there is no time boundary on how long after a write into a volatile variable will become visible to another thread.
Also see href="https://www.kernel.org/doc/html/v4.11/process/volatile-considered-harmful.html" rel="nofollow noreferrer">kernel.org why volatile is nearly always wrong in kernel
Is this implementation safe on all architectures supported by GCC and Linux? (It is at least inefficient on some architectures, right?)
There is no guarantee the volatile message gets out of the thread which sets it. So not really safe. On linux it may be safe.
Is the while loop safe according to C++11 and its memory model?
No - as it doesn't create any of the inter-thread messaging primitives.
I've been doing some pure Java development recently, and I'm using an external lib that exposes a small number of methods, each of which have the possibility of throwing an Exception.
Eclipse won't let me compile my program unless I wrap each of those calls in a try-catch block. So far, no big deal.
Then I noticed some things, like ArrayList.add(), which throws IndexOutOfBoundsException. How is it that I can call something like this without needing to wrap it in a try..catch? Obv, in this particular case, it would be incredibly irritating if you had to do it each time, but how and why is try-catch enforced in some situations, but not others?
itemprop="text">
class="normal">Answer
href="http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html" rel="noreferrer">Unchecked exceptions (subclasses of Error or RuntimeException) need no try..catch block, and when there is no try...catch, the method need not to declare itself to be throws (you can, of course, and some consider declaring throws to be a good practice) . On the other hand, checked ones do need the try...catch, or declares throws.
I am confused by the usage of brackets, parentheses, curly braces in Bash, as well as the difference between their double or single forms. Is there a clear explanation?
Answer
In Bash, test and [ are shell builtins.
The href="http://mywiki.wooledge.org/BashFAQ/031" rel="noreferrer">double bracket, which is a shell keyword, enables additional functionality. For example, you can use && and || instead of -a and -o and there's a regular expression matching operator =~.
Also, in a simple test, double square brackets seem to evaluate quite a lot quicker than single ones.
$ time for ((i=0; i<10000000; i++)); do [[ "$i" = 1000 ]]; done
real 0m24.548s user 0m24.337s
sys 0m0.036s $ time for ((i=0; i<10000000; i++)); do [ "$i" = 1000 ]; done
real 0m33.478s user 0m33.478s sys 0m0.000s
The braces, in addition to delimiting a variable name are used for href="http://tiswww.case.edu/php/chet/bash/bashref.html#Brace-Expansion" rel="noreferrer">parameter expansion so you can do things like:
I was reading the comments on an answer and saw href="https://stackoverflow.com/questions/15667093/how-to-understand-closure-in-javascript/15667314#comment22237952_15667362">this comment:
[the closure] doesn't persist the state of foo so much as creates a special scope containing (1) the returned function and (2) all the external variables referenced at the time of the return. This special scope is called a closure.
OK, so far so good. Now here is the interesting part that I didn't know about:
Case in point... if you had another var defined in foo that was not referenced in the return function, it would not exist in the closure scope.
I guess that makes sense, but what implications does this have other than memory use / perfomance?
Question -- If all variables in scope were included in the closure, what would that allow me to do that I cannot do with the current model?
class="post-text" itemprop="text">
class="normal">Answer
I think you're taking that comment too literally. The comment is just saying that you can't access it outside the function scope (it's not publicly accessible), not that its not available at all within the function. The returned function will have access to all of the outer functions scope no matter what. You just can't access that scope outside the outer function if the inner function doesn't provide a way of accessing it.
For instance, this expression evaluates to 4:
function testClosure(){ var x = 2; return function(y){
So x is available despite not being directly referenced
Further research
It appears that chrome and firefox at least do attempt to optimize this in the sense that if you're not providing ANY way to reference the x variable, it doesn't show up as being available in the debugger. Running this with a breakpoint inside a closure shows x as unavailable on Chrome 26 and Firefox 18.
But thats just a memory management detail, not a relevant property of the language. If there is any possible way that you could reference the variable, it is passed, and my suspicion is that other browsers may not optimize this in the same way. Its always better to code to the spec than to an implementation. In this case though the rule really is: "if there's any possible way for you to access it, it will be available". And also, don't use eval because it really will keep your code from optimizing anything.
set.cpp: In function ‘void printSet(std::set, std::allocator<_CharT> >)’: set.cpp:7: error: expected `;' before ‘it’ set.cpp: In function ‘void printSet(std::set, std::allocator<_CharT> >) [with T = int]’: set.cpp:12: instantiated from here set.cpp:7: error: dependent-name ‘std::set,std::allocator<_CharT> >::iterator’ is parsed as a non-type, but instantiation yields a type set.cpp:7: note: say ‘typename std::set,std::allocator<_CharT> >::iterator’ if a type is meant
What did I do wrong? I feel like I've hardly written anything, and already C++ gives me this scary message.
In case it is helpful, it looks like, if I comment out the line with the iterator, there are no errors. However, all the examples I've seen online so far seem to declare iterators this way. I think.
Answer
Precede your declaration with the keyword typename, thusly:
typename set::iterator it;
You need to do this whenever you refer to a type that is dependent upon a template argument. In this case, iterator is dependent on T. Otherwise, the compiler has difficulty trying to figure out what iterator is, whether it's a type, or a static member or something else. (well, technically, it doesn't try to figure it out, its decision is already made, it just happens to be wrong)
Note that if you have a concrete type, for example:
I have a python file with the class A defined in it in a different directory than the one I am working in. I want to import a module from that class in my script. I wrote something like this in jupyter:
import os parent_dir = 'path/to/class' os.chdir(parent_dir) from A import a
It works perfectly fine and I get to execute the program. However when I run the script in the same directory from the terminal, I get this error:
ModuleNotFoundError: No module named 'a'
I put a os.getcwd() before the error to make sure it is in the same directory, and when I go to that directory from the terminal and import the module directly there are no errors. I wonder why I get this error when running the script.
style="font-weight: bold;">
Answer
Don't use os.chdir, because it changes a global state, that can lead to unexpected behaviour somewhere else.
I have a small shiny app for annotating text files.
The UI provides fileInput to select .txt files. One of the files is the default when the app is launched.
Next, Previous buttons allow user to display the contents of the file, one sentence at a time.
User may select any text within a sentence and click the Add Markup button to annotate the sentence. The Action Button triggers javascript function addMarkup().
The sentence is displayed after being marked up.
I am only posting the shiny app code here. Complete code of the app is available on href="https://github.com/beyond2013/dynamicContent" rel="nofollow noreferrer">github repository
My question is how can I persist the sentences to a file after they have been annotated?
href="https://i.stack.imgur.com/2hfTF.png" rel="nofollow noreferrer"> src="https://i.stack.imgur.com/2hfTF.png" alt="screenshot of the app">
Update: I have gone through href="https://shiny.rstudio.com/articles/persistent-data-storage.html" rel="nofollow noreferrer">Persistent data storage in Shiny apps, and hope that I will be able to follow along the documentation regarding persistent storage. However I am still unsure how to capture the sentence after it has been marked up.
Answer
You have two issues here - persisting the changes, and then saving the output. I solved the problem using a bit of JS and a bit of R code. I'll do a pull request on Github to submit the broader code. However, here's the core of it.
In your Javascript that you use to select things, you can use Shiny.onInputChange() to update an element of the input vector. Doing this, you can create a reactiveValues item for the corpus, and then update it with inputs from your interface.
Below, you'll notice that I switched from using a textnode to using just the inner HTML. Using a node, and firstChild, as you had it before, you end up truncating the sentence after the first annotation (since it only picks the stuff before . Doing it this way seems to work better.
Next, I've tried to simplify your server.R code. You were using a reactive context to pull from another reactive context (sourceData into corpus), which seemed unnecessary. So, I tried to refactor it a bit.
writeLines(text = values$corpus, con = file, sep = "\n")
}) }
Now, the code has a few changes. The loading from file is basically the same. I was right about my skepticism on isolate - replacing it with an observe accomplishes what I wanted to do, whereas isolate would only give you the initial load. Anyway, we use observe to load the corpus values into the reactiveValues object you created - this is to give us a place to propagate changes to the data.
We keep the remaining logic for moving forward and backward. However, we change the way the output is rendered so that it looks at the reactiveValues object. Then, we create an observer that updates the reactiveValues object with the input from our updated Javascript. When this happens, the data gets stored permanently, and you can also mark more than one sequence in the string (though I have not done anything with nested marking or with removing marks). Finally, a save function is added - the resulting strings are saved out with used to show the marked areas.
If you load a previously marked file, the marks will show up again.
I know what self::staticFunctionName() and parent::staticFunctionName() are, and how they are different from each other and from $this->functionName.
But what is static::staticFunctionName()?
Answer
It's the keyword used in PHP 5.3+ to invoke late static bindings. Read all about it in the manual: href="http://php.net/manual/en/language.oop5.late-static-bindings.php" rel="noreferrer">http://php.net/manual/en/language.oop5.late-static-bindings.php
/>
In summary, static::foo() works like a dynamic self::foo().
class A { static function foo() { // This will be executed.
} static function bar() { self::foo();
}
}
class B extends A { static function foo() { // This will not be executed. // The above self::foo() refers to A::foo().
} }
B::bar();
static solves this problem:
class A { static function foo() { // This is overridden in the child class. } static function bar() {
static::foo();
} }
class B extends A { static function foo() { // This will be executed.
// static::foo() is bound late.
} }
B::bar();
static as a keyword for this behavior is kind of confusing, since it's all but. :)
I'm using the mail function on php to send a confirmation email. It actually works, but just for some mails. For example, if you recieve that on a gmail it's fine, but on a college mail it appears ? instead of special characters. The problem is that that mail includes a validation link,which looks like www.myweb.com/confirmation.php?passkey=(passkey) and if the mail and the special characters aren't send properly this link is also wrong (the = doesn't appear).
I've already tried writting
iconv_set_encoding("internal_encoding", "UTF-8");
on top of the mail function, but it doesn't work. What can it be?
Relates to the film by Orson Welles concerning the life of a newspaper owner, politician and magnate as presented through the eyes of an investigative reporter.
readability="17">
There is no tag wiki for this tag … yet!
Tag wikis help introduce newcomers to the tag. They contain an overview of the topic defined by the tag, along with guidelines on its usage.
All registered users may propose new tag wikis.
(Note that if you have less than 20000 reputation, your tag wiki will be peer reviewed before it is published.)
When looking beyond the href="https://en.wikipedia.org/wiki/Rapid_application_development" rel="noreferrer">RAD (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called rel="noreferrer">Model-View-Controller, href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter" rel="noreferrer">Model-View-Presenter and href="http://en.wikipedia.org/wiki/Model_View_ViewModel" rel="noreferrer">Model-View-ViewModel. My question has three parts to it:
What issues do these patterns address?
How are they similar?
How are they different?
class="post-text" itemprop="text">
class="normal">Answer
Model-View-Presenter
In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.
MVP tends to be a very natural pattern for achieving separated presentation in Web Forms. The reason is that the View is always created first by the ASP.NET runtime. You can href="http://www.codeplex.com/websf/Wiki/View.aspx?title=MVPDocumentation&referringTitle=bundles" rel="noreferrer">find out more about both variants.
Two primary variations
Passive View: The View is as dumb as possible and contains almost zero logic. The Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead the View exposes setter properties which the Presenter uses to set the data. All state is managed in the Presenter and not the View.
Pro: maximum testability surface; clean separation of the View and Model
Con: more work (for example all the setter properties) as you are doing all the data binding yourself.
Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.
Pro: by leveraging databinding the amount of code is reduced.
Con: there's less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.
Model-View-Controller
In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:
Action in the View -> Call to Controller -> Controller Logic
-> Controller returns the View.
One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders, and is completely stateless. In implementations of MVC the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.
Presentation Model
One other pattern to look at is the Presentation Model pattern. In this pattern there is no Presenter. Instead the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model, and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behaviour for the view. This pattern is a very strong candidate for use in WPF applications and is also called href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx" rel="noreferrer">Model-View-ViewModel.
There is a rel="noreferrer">MSDN article about the Presentation Model and a section in the rel="noreferrer">Composite Application Guidance for WPF (former Prism) about rel="noreferrer">Separated Presentation Patterns
I'm trying to find the proper way to define some components which could be used in a generic way:
value="2">
There is a logic going on for rendering between parent and children components of course, you can imagine and as an example of this logic.
This is a dummy implementation for the purpose of the question:
var Parent = React.createClass({ doSomething: function(value) {
}, render: function() {
return (
{this.props.children}
);
} });
var Child = React.createClass({ onClick: function() { this.props.doSomething(this.props.value); // doSomething is undefined }, render: function() { return ( onClick={this.onClick}>
);
} });
The question is whenever you use {this.props.children} to define a wrapper component, how do you pass down some property to all its children?
Answer
Cloning children with new props
You can use href="https://reactjs.org/docs/react-api.html#reactchildren" rel="noreferrer">React.Children to iterate over the children, and then clone each element with new props (shallow merged) using href="https://reactjs.org/docs/react-api.html#cloneelement" rel="noreferrer">React.cloneElement e.g:
const Child = ({ doSomething, value }) => (
doSomething(value)}>Click Me
);
class Parent extends React.PureComponent { doSomething = value => {
console.log('doSomething called by child with value:', value);
You can also pass props to children with rel="noreferrer">render props. In this approach the children (which can be children or any other prop name) is a function which can accept any arguments you want to pass and returns the children:
const Child = ({ doSomething, value }) => (
doSomething(value)}>Click Me
);
class Parent extends React.PureComponent { doSomething = value => {
console.log('doSomething called by child with value:', value);
}
render() { return
{this.props.children(this.doSomething)}
} };
ReactDOM.render(
{doSomething => (
/>
)} ,
document.getElementById('container') );
Instead of or simply <> you can also return an array if you prefer.
I have a limited exposure to DB and have only used DB as an application programmer. I want to know about Clustered and Non clustered indexes. I googled and what I found was :
A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A nonclustered index is a
special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a
nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.
What I found in SO was href="https://stackoverflow.com/questions/91688/what-are-the-differencespros-cons-between-clustered-and-non-clustered-indexes">What are the differences between a clustered and a non-clustered index?.
Can someone explain this in plain English?
itemprop="text">
class="normal">Answer
With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.
With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indices, although each new index will increase the time it takes to write new records.
It is generally faster to read from a clustered index if you want to get back all the columns. You do not have to go first to the index and then to the table.
Writing to a table with a clustered index can be slower, if there is a need to rearrange the data.
I want to turn off PHP's magic quotes. I don't have access to php.ini.
When I tried to add php_flag magic_quotes_gpc off to my .htaccess file, I get a 500 internal server error. This is what my .htaccess file looks like:
AddType x-mapp-php5 .php
php_flag magic_quotes_gpc off
Then I tried to use ini_set('magic_quotes_gpc', 'O'), but that had no effect.
How do I turn magic quotes off?
Answer
As per href="http://php.net/manual/security.magicquotes.disabling.php#82777" rel="noreferrer">the manual you can often install a custom php.ini on shared hosting, where mod_php isn't used and the php_value directive thus leads to an error. For suexec/FastCGI setups it is quite common to have a per-webspace php.ini in any case.
--
I don't think O (uppercase letter o) is a valid value to set an ini flag. You need to use a true/false, 1/0, or "on"/"off" value.
ini_set( 'magic_quotes_gpc', 0 ); // doesn't work
EDIT
After checking the list of ini settings, I see that magic_quotes_gpc is a PHP_INI_PERDIR setting (after 4.2.3), which means you can't change it with ini_set() (only PHP_INI_ALL settings can be changed with ini_set())
What this means is you have to use an .htaccess file to do this - OR - implement a script to reverse the effects of magic quotes. Something like this