Monday, August 5, 2019

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV



In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This particular scene was quite strange and confused me pretty badly, because she's a mammoth, why did she hang on the tree like that?




Further, I've only watched the Ice Age3 and Ice Age4. Did I miss anything? Did they show any scene towards Peaches' mom's strange behavior in the previous parts?


Answer



In Ice Age 2, when Elle was first introduced, she thought she was a possum, thus hanging upside down in a tree to sleep. Some of her habits were taught to Peaches, thus the girl sleeping upside down.



In Ice Age 4, there was a line of dialogue from Peaches about being half possum. this came from the idea that Elle still believes herself to be a possum, but that Peaches' dad is a mammoth.


Sunday, August 4, 2019

Delete /n at end of a String (Python)





How can I delete a /n linebreak at the end of a String ?



I´m trying to read two strings from an .txt file and want to format them with os.path.join() method after I "cleared" the string.



Here you can see my try with dummy data:



content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']

for string in content:
print(string)

if string.endswith('\\\n'):
string = string[0:-2]

print(content)

Answer



You can not update a string like you are trying to. Python strings are immutable. Every time you change a string, new instance is created. But, your list still refers to the old object. So, you can create a new list to hold updated strings. And to strip newlines you can use rstrip function. Have a look at the code below,



content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']
updated = []

for string in content:
print(string)
updated.append(string.rstrip())

print(updated)

java - How to sort a map

For starters, you will need to be using an instance of SortedMap. If the map doesn't implement that interface, then it has an undefined/arbitrary iteration order and you can't control it. (Generally this is the case, since a map is a way of associating values with keys; ordering is an auxiliary concern.)


So I'll assume you're using TreeMap, which is the canonical sorted map implementation. This sorts its keys according to a Comparator which you can supply in the constructor. So if you can write such a comparator that determines which is the "lower" of two arbitrary keys (spoiler alert: you can), this will be straightforward to implement.


This will, however, only work when sorting by key. I don't know if it makes much sense to sort a map by value, and I'm not aware of any straightforward way to do this. The best I can think of is to write a Comparator that sorts on values, call Map.getEntrySet and push all the entries into a list, then call Collections.sort on the list. It's not very elegant or efficient but it should get the job done if performance isn't your primary concern.


(Note also that if your keys aren't immutable, you will run into a lot of trouble, as they won't be resorted when externally changed.

plot explanation - Why did the girl try to kill herself in the 2009 Sherlock Holmes film?

In the beginning of Sherlock Holmes (2009), Lord Blackwood attempts to kill a young woman during some sort of dark ritual and is thwarted just in time by Holmes and Watson. Blackwood himself was not going to do it, instead he put her in some sort of "spell", causing the girl to attempt to stab herself.


woman in a white dress laying on a slab with a black hooded figure standing at the head of the slab


Given that the "supernatural powers" of Lord Blackwood were revealed as nothing more than "conjuring tricks", why did the girl try to stab herself at the direction of Blackwood?


Answer


I never saw a definitive explanation, but there are three theories:



  1. Hypnotism (a person with Blackwood's personality and charisma is likely to be a good hypnotist). This is somewhat confirmed by the script (after Holmes stops Blackwood):



    The girl has snapped out of her trance, and is backing away from them as best she can



  2. Somewhat related to the first possibility, please note that the cult members frequently allow the cult leader to exercise nearly total control, up to suicide (see Jim Jones for one of the more dramatic examples, that gave name to the "drinking cool-aid" expression).


    Also, while extremely rare in actuality, sacrifice has happened on the more extreme end of BDSM circles and is an unexpectedly popular thing for many in BDSM as a fantasy.


  3. The "victim" was an actress who was supposed to act like she was about to kill herself, considering that Blackwood pretty much arranged for his own arrest.



AWK print next line of match between matches

Let's presume I have file test.txt with following data:



.0

41
0.0
42
0.0
43
0.0
44
0.0
45
0.0

46
0.0
START
90
34
17
34
10
100
20

2056
30
0.0
10
53
20
2345
30
0.0
10

45
20
875
30
0.0
END
0.0
48
0.0
49

0.0
140
0.0


With AWK how would I print the lines after 10 and 20 between START and END.
So the output would be.



100
2056

53
2345
45
875


I was able to get the lines with 10 and 20 with



awk '/START/,/END/ {if($0==10 || $0==20) print $0}' test.txt 



but how would I get the next lines?

mysql - How to restrict update or insert more than once by navigating back to referring page in php?




I am developing a web application where I want to restrict update or insert more than once by navigating back to referring page. Let me present you three model files in the order of flow so that I can raise the zone where I am stuck.




  • register.html



            
    ...






    ...


  • process.php



                    echo "Welcome ".$_GET['para'];
    ?>


  • success.php



                    if(isset($_POST['Submit']))
    {
    $name = $_POST['name'];

    // some database update here ...


    echo "Done. Click to go next";
    unset($_POST['Submit']);
    }else{
    echo "Error in submission";
    }
    ?>



The above three files are very simple. Here the update part has nothing to do when the user hits the back button after landing on page success.php because of unset($_POST['Submit']);. But when the user goes back further by hitting the back button again it reaches register.html and can again come up with the $_POST['Submit'] set and may do the update part which is sometimes vulnerable. I know there is Post/Redirect/Get to solve this issue, but I want some other alternatives so that the part gatekeepering the update part may be made so efficient that it would not allow the same anymore by clicking the back button.



Answer



If you are getting duplicate records inserted.




  1. You may try INSERT IGNORE

  2. ADD UNIQUE INDEX to your table to prevent this happening



    you may choose any one of INSERT IGNORE and REPLACE according to the duplicate-handling behavior





Refer https://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html




  1. Lastly you may like simple php with mysqli_num_rows()



    $sql = "SELECT id FROM table-name WHERE column-name1 = ? AND column-name2 = ? ;
    $mq = mysqli_query($sql);

    if (mysqli_num_rows($mq) < 1) {
    $sql = "UPDATE table-name SET (colum-names) VALUES (...)";

    mysqli_query($sql);
    else {
    echo "Record already updated";
    }
    }


sharedpreferences - How to delete shared preferences data from App in Android

None of the answers work for me since I have many shared preferences keys.



Let's say you are running an Android Test instead of a unit test.



It is working for me loop and delete through all the shared_prefs files.




@BeforeClass will run before all the tests and ActivityTestRule





@BeforeClass
public static void setUp() {
Context context = InstrumentationRegistry.getTargetContext();

File root = context.getFilesDir().getParentFile();
String[] sharedPreferencesFileNames = new File(root, "shared_prefs").list();
for (String fileName : sharedPreferencesFileNames) {
context.getSharedPreferences(fileName.replace(".xml", ""), Context.MODE_PRIVATE).edit().clear().commit();
}

}

Hot Linked Questions

How does C handle EOF? [duplicate]



#include

int main()
{
FILE* f=fopen("book2.txt","r");
char a[200];
while(!feof(f))

{
fscanf(f,"%s",a);
printf("%s ",a);
printf("%d\n",ftell(f));...





Reset Excel VBA password




I forgets password of one VBA automation developed by me and now I have to update the VBA code but I am unable do that. And also please make note that I don't have permissions to download any application.


Answer



The only way that you can achieve this is by using third party software downloaded from internet, but if you are not allowed to download applications. I say there is no easy way you can crack that vba password without application.



But if you're interested on cracking it. You could try this article:
http://datapigtechnologies.com/blog/index.php/hack-into-password-protected-vba-projects/
See if it helps.



php - Connect MySQL workbench to MAMP using socket/path on windows

i am trying to connect to mysql workbench to MAMP with socket/path on windows 10



my problem :



1 I don't have mysql.sock file



2 I am trying to find a resource to find a solution but i only get OSX solutions which is /Applications/MAMP/tmp/mysql/mysql.sock.



I don't have TMP file and my sql.sock



Is there any solution to my problem or i have to use an alternative of MAMP ?

plot explanation - Why did Hendricks jump from the parking structure at the end of the fight scene in MI4?

In Mission:Impossible-Ghost Protocol, at the last fight scene, Ethan and Hendricks were in a parking structure and Ethan was trying to get that briefcase which contains the Satellite launch terminal.


In the end of the fight scene, Hendricks jumps from the middle of the building and dies. But it surprised me because he was a nuclear strategist, why did he die like that? As a sane man he might have known, if he jumped from the middle of the building he would definitely be killed and obviously Ethan will get the briefcase and press the abort button.


Can someone explain to me why Hendricks jumped from the parking structure at the end of the fight scene in MI4?


python - [] and {} vs list() and dict(), which is better?



I understand that they are both essentially the same thing, but in terms of style, which is the better (more Pythonic) one to use to create an empty list or dict?



Answer



In terms of speed, it's no competition for empty lists/dicts:



>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718
>>> timeit("{}")
0.033620194745424214

>>> timeit("dict()")
0.1821558326547077


and for non-empty:



>>> timeit("[1,2,3]")
0.24316302770330367
>>> timeit("list((1,2,3))")
0.44744206316727286

>>> timeit("list(foo)", setup="foo=(1,2,3)")
0.446036018543964
>>> timeit("{'a':1, 'b':2, 'c':3}")
0.20868602015059423
>>> timeit("dict(a=1, b=2, c=3)")
0.47635635255323905
>>> timeit("dict(bar)", setup="bar=[('a', 1), ('b', 2), ('c', 3)]")
0.9028228448029267



Also, using the bracket notation lets you use list and dictionary comprehensions, which may be reason enough.


Changing Fonts for Graphs in R



In my study I am generating various graphs using R. I see that most of the graphs come up with a Sans Serif type font with various sizes.



How to I change all the text in a graph (x-label, y-label, title, legend etc.) into a uniform font e.g. Times New Roman, 12pt, Bold?


Answer



You can use the extrafont package.




install.packages("extrafont")
library(extrafont)
font_import()
loadfonts(device="win") #Register fonts for Windows bitmap output
fonts() #vector of font family names
## [1] "Andale Mono" "AppleMyungjo"
## [3] "Arial Black" "Arial"
## [5] "Arial Narrow" "Arial Rounded MT Bold"


library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme_bw() +
theme(text=element_text(family="Times New Roman", face="bold", size=12)) #Times New Roman, 12pt, Bold
#example taken from the Github project page



enter image description here



Note: Using the extrafont package, you can also embed these fonts in PDF and EPS files (make plots in R and export to PDF/EPS). You can also directly create math symbols (see math equation in plot below), usually created using TeX. More information here and here. Also look at the github project page.



enter image description here



Also look at this answer which describes creating xkcd style graphs using the extrafont package.



enter image description here


c++ - Using __thread in c++0x



I read that there was a new keyword in C++: it's __thread from what I've read.



All I know is that it's a keyword to be used like the static keyword but I know nothing else. Does this keyword just mean that, for instance, if a variable were declared like so:



__thread int foo;



then anything to do with that variable will be executed with a new thread?


Answer



It's thread_local, not __thread. It's used to define variables which has storage duration of the thread.



thread_local is a new storage duration specifier added in C++0x. There are other storage duration : static, automatic and dynamic.



From this link:





thread local storage duration (C++11 feature). The variable is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the variable. Only variables declared thread_local have this storage duration.







I think the introduction of this keyword was made possible by introducing a standardized memory model in C++0x:




android - What is the purpose of Looper and how to use it?



I am new to Android. I want to know what the Looper class does and also how to use it. I have read the Android Looper class documentation but I am unable to completely understand it.
I have seen it in a lot of places but unable to understand its purpose. Can anyone help me by defining the purpose of Looper and also by giving a simple example if possible?


Answer




What is Looper?



Looper is a class which is used to execute the Messages(Runnables) in a queue. Normal threads have no such queue, e.g. simple thread does not have any queue. It executes once and after method execution finishes, the thread will not run another Message(Runnable).



Where we can use Looper class?



If someone wants to execute multiple messages(Runnables) then he should use the Looper class which is responsible for creating a queue in the thread.
For example, while writing an application that downloads files from the internet, we can use Looper class to put files to be downloaded in the queue.



How it works?




There is prepare() method to prepare the Looper. Then you can use loop() method to create a message loop in the current thread and now your Looper is ready to execute the requests in the queue until you quit the loop.



Here is the code by which you can prepare the Looper.



class LooperThread extends Thread {
public Handler mHandler;

@Override
public void run() {

Looper.prepare();

mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// process incoming messages here
}
};

Looper.loop();

}
}

c# - Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on

I couldn't find an answer for this:




"Cross-thread operation not valid: Control 'progressBar1' accessed

from a thread other than the thread it was created on."




This is my code:



        private void buttonStart_Click(object sender, EventArgs e)
{
ClassCopy cb = new ClassCopy();
cb.startCopy(textBoxSrc.Text, textBoxDest.Text, true);


th = new Thread(loading);
th.Start();

}

private loading()
{
for (int i = 0; i < 100; i++)
{
if (progressBar1.InvokeRequired)

progressBar1.Invoke(new Action(loading));
else
progressBar1.Value = i;
}
}

r faq - How to make a great R reproducible example




When discussing performance with colleagues, teaching, sending a bug report or searching for guidance on mailing lists and here on Stack Overflow, a reproducible example is often asked and always helpful.




What are your tips for creating an excellent example? How do you paste data structures from in a text format? What other information should you include?



Are there other tricks in addition to using dput(), dump() or structure()? When should you include library() or require() statements? Which reserved words should one avoid, in addition to c, df, data, etc.?



How does one make a great reproducible example?


Answer



A minimal reproducible example consists of the following items:





  • a minimal dataset, necessary to demonstrate the problem

  • the minimal runnable code necessary to reproduce the error, which can be run on the given dataset

  • the necessary information on the used packages, R version, and system it is run on.

  • in the case of random processes, a seed (set by set.seed()) for reproducibility1



For examples of good minimal reproducible examples, see the help files of the function you are using. In general, all the code given there fulfills the requirements of a minimal reproducible example: data is provided, minimal code is provided, and everything is runnable. Also look at questions on with lots of upvotes.



Producing a minimal dataset




For most cases, this can be easily done by just providing a vector/data frame with some values. Or you can use one of the built-in datasets, which are provided with most packages.
A comprehensive list of built-in datasets can be seen with library(help = "datasets"). There is a short description to every dataset and more information can be obtained for example with ?mtcars where 'mtcars' is one of the datasets in the list. Other packages might contain additional datasets.



Making a vector is easy. Sometimes it is necessary to add some randomness to it, and there are a whole number of functions to make that. sample() can randomize a vector, or give a random vector with only a few values. letters is a useful vector containing the alphabet. This can be used for making factors.



A few examples :




  • random values : x <- rnorm(10) for normal distribution, x <- runif(10) for uniform distribution, ...

  • a permutation of some values : x <- sample(1:10) for vector 1:10 in random order.

  • a random factor : x <- sample(letters[1:4], 20, replace = TRUE)




For matrices, one can use matrix(), eg :



matrix(1:10, ncol = 2)


Making data frames can be done using data.frame(). One should pay attention to name the entries in the data frame, and to not make it overly complicated.



An example :




set.seed(1)
Data <- data.frame(
X = sample(1:10),
Y = sample(c("yes", "no"), 10, replace = TRUE)
)


For some questions, specific formats can be needed. For these, one can use any of the provided as.someType functions : as.factor, as.Date, as.xts, ... These in combination with the vector and/or data frame tricks.




Copy your data



If you have some data that would be too difficult to construct using these tips, then you can always make a subset of your original data, using head(), subset() or the indices. Then use dput() to give us something that can be put in R immediately :



> dput(iris[1:4, ]) # first four rows of the iris data set
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5,
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2,
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = c("setosa",
"versicolor", "virginica"), class = "factor")), .Names = c("Sepal.Length",
"Sepal.Width", "Petal.Length", "Petal.Width", "Species"), row.names = c(NA,

4L), class = "data.frame")


If your data frame has a factor with many levels, the dput output can be unwieldy because it will still list all the possible factor levels even if they aren't present in the the subset of your data. To solve this issue, you can use the droplevels() function. Notice below how species is a factor with only one level:



> dput(droplevels(iris[1:4, ]))
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5,
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2,
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = "setosa",
class = "factor")), .Names = c("Sepal.Length", "Sepal.Width",

"Petal.Length", "Petal.Width", "Species"), row.names = c(NA,
4L), class = "data.frame")


When using dput, you may also want to include only relevant columns:



> dput(mtcars[1:3, c(2, 5, 6)]) # first three rows of columns 2, 5, and 6
structure(list(cyl = c(6, 6, 4), drat = c(3.9, 3.9, 3.85), wt = c(2.62,
2.875, 2.32)), row.names = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710"
), class = "data.frame")



One other caveat for dput is that it will not work for keyed data.table objects or for grouped tbl_df (class grouped_df) from dplyr. In these cases you can convert back to a regular data frame before sharing, dput(as.data.frame(my_data)).



Worst case scenario, you can give a text representation that can be read in using the text parameter of read.table :



zz <- "Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa

4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa"

Data <- read.table(text=zz, header = TRUE)


Producing minimal code



This should be the easy part but often isn't. What you should not do, is:





  • add all kind of data conversions. Make sure the provided data is already in the correct format (unless that is the problem of course)

  • copy-paste a whole function/chunk of code that gives an error. First, try to locate which lines exactly result in the error. More often than not you'll find out what the problem is yourself.



What you should do, is:




  • add which packages should be used if you use any (using library())


  • if you open connections or create files, add some code to close them or delete the files (using unlink())

  • if you change options, make sure the code contains a statement to revert them back to the original ones. (eg op <- par(mfrow=c(1,2)) ...some code... par(op) )

  • test run your code in a new, empty R session to make sure the code is runnable. People should be able to just copy-paste your data and your code in the console and get exactly the same as you have.



Give extra information



In most cases, just the R version and the operating system will suffice. When conflicts arise with packages, giving the output of sessionInfo() can really help. When talking about connections to other applications (be it through ODBC or anything else), one should also provide version numbers for those, and if possible also the necessary information on the setup.



If you are running R in R Studio using rstudioapi::versionInfo() can be helpful to report your RStudio version.




If you have a problem with a specific package you may want to provide the version of the package by giving the output of packageVersion("name of the package").






1 Note: The output of set.seed() differs between R >3.6.0 and previous versions. Do specify which R version you used for the random process, and don't be surprised if you get slightly different results when following old questions. To get the same result in such cases, you can use the RNGversion()-function before set.seed() (e.g.: RNGversion("3.5.2")).


go - Why is it illegal to assign pointer to pointer for type definitions involving pointers?



I have the following code:



package main

type Vertex struct {
X, Y float64

}

type VertexPointer *Vertex

func main() {
v := Vertex{3, 4}
v_ptr := &v

var test_1 *Vertex = &v
var test_2 **Vertex = &v_ptr


var test_3 VertexPointer = &v
var test_4 *VertexPointer = &v_ptr
}


When I try and run it (I'm using Go 1.6.2) I get the following error:



# command-line-arguments
./pointers.go:17: cannot use &v_ptr (type **Vertex) as type *VertexPointer in assignment



I'm confused why the assignment involving test_3works but not test_4. Based on what I've been reading, my understanding is that either both assignments should work or neither of them should work. Isn't the described behaviour a bit inconsistent?


Answer



This is all "governed" by Spec: Assignability. Assigning to test_3 is covered by this:




A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:







And none of the assignability rules cover test_4, so it's not allowed.



The underlying type is detailed in Spec: Types:




Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.





In case of test_3:



var test_3 VertexPointer = &v


Type of test_3 is VertexPointer (explicitly specified), type of &v is *Vertex. Underlying type for both are *Vertex, and type of &v (which is *Vertex) is an unnamed type, so the assignment is OK. Vertex is a named type, but derived types such as *Vertex or []Vertex are unnamed types.



In case of test_4:



var test_4 *VertexPointer = &v_ptr



Type of test_4 is *VertexPointer, type of &v_ptr is **Vertex because type of v_ptr is *Vertex, not VertexPointer. Underlying type of test_4 is *VertexPoitner, underlying type of &v_ptr is **Vertex. The underlying types do not match. So there is no assignability rule that applies, so this assignment is not OK.



See similar question: Custom type passed to function as a parameter


regex - Regular expression to search for Gadaffi



I'm trying to search for the word Gadaffi. What's the best regular expression to search for this?



My best attempt so far is:



\b[KG]h?add?af?fi$\b



But I still seem to be missing some journals. Any suggestions?



Update: I found a pretty extensive list here: http://blogs.abcnews.com/theworldnewser/2009/09/how-many-different-ways-can-you-spell-gaddafi.html



The answer below matches all the 30 variants:




Gadaffi

Gadafi
Gadafy
Gaddafi
Gaddafy
Gaddhafi
Gadhafi
Gathafi
Ghadaffi
Ghadafi
Ghaddafi

Ghaddafy
Gheddafi
Kadaffi
Kadafi
Kaddafi
Kadhafi
Kazzafi
Khadaffy
Khadafy
Khaddafi

Qadafi
Qaddafi
Qadhafi
Qadhdhafi
Qadthafi
Qathafi
Quathafi
Qudhafi
Kad'afi


Answer



\b[KGQ]h?add?h?af?fi\b



Arabic transcription is (Wiki says) "Qaḏḏāfī", so maybe adding a Q. And one H ("Gadhafi", as the article (see below) mentions).



Btw, why is there a $ at the end of the regex?






Btw, nice article on the topic:




Gaddafi, Kadafi, or Qaddafi? Why is the Libyan leader’s name spelled so many different ways?.






EDIT



To match all the names in the article you've mentioned later, this should match them all. Let's just hope it won't match a lot of other stuff :D



\b(Kh?|Gh?|Qu?)[aeu](d['dt]?|t|zz|dhd)h?aff?[iy]\b


Saturday, August 3, 2019

c - What is the difference between a definition and a declaration?



The meaning of both eludes me.


Answer



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 litb (Johannes Schaub) who dug out the actual chapter and verse in one of his answers.


Regex match for HTML tag containing "on" JS trigger




I want to check if an HTML tag (potentially split across multiple lines) contains an "on" JS trigger. The actual HTML tag and the Javascript are of no consequence. For example:



    onblur="foo()"/>Other stuff


I've got most of this to work using the pattern:



    <\w+([^>])+?(on\w+)+[\s\S]+?>


However, this also matches:




    

Other stuff



I modified the original pattern to:



    <\w+([^>])+?(\s)+(on\w+)+[\s\S]+?>


but this matches only if the JS trigger keyword is preceded by 2 or more whitespace characters. A nudge in the right direction would be appreciated.


Answer



Might work <\w+(?=\s)[^>]*?\s(on\w+)[\s\S]+?>



iphone - Problem with inserting data into a table



sqlite3 *database;
sqlite3_stmt *statement;
NSString *dPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"UserData.sqlite"];

const char *dbpath = [dPath UTF8String];
// NSLog(@"%@",dbpath);
//UserArray = [[NSMutableArray alloc]init];



if(sqlite3_open(dbpath, &database) == SQLITE_OK)
{

NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO User (UserName,FullName,Email,PhoneNo) VALUES (\"%@\", \"%@\", \"%@\" ,\"%@\")",txtUserName.text,txtFullName.text ,txtEmail.text , txtPhoneNo.text];

const char *insert_stmt = [insertSQL UTF8String];


sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL);

if(sqlite3_step(statement)==SQLITE_DONE)
{
txtUserName.text=@"";
txtFullName.text=@"";
txtEmail.text=@"";
txtPhoneNo.text=@"";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add Record" message:@"Contact Added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alert show];
[alert release];
alert=nil;

}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"record" message:@"record not created" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

alert=nil;
}


// Release the compiled statement from memory
sqlite3_finalize(statement);

sqlite3_close(database);
}



->> i am trying to insert data into table. the code execute properly but the record is not added into the table. so please help me or this problem..thank's for your response.


Answer



try executing commit, so setting the db to autocommit



// COMMIT
const char *sql2 = "COMMIT TRANSACTION";
sqlite3_stmt *commit_statement;
if (sqlite3_prepare_v2(database, sql2, -1, &commit_statement, NULL) != SQLITE_OK) {
NSAssert1(0, @"Error Message: '%s'.", sqlite3_errmsg(database));

}
success = sqlite3_step(commit_statement);
if (success != SQLITE_DONE) {
NSAssert1(0, @"Error Message: '%s'.", sqlite3_errmsg(database));
}
}

visual c++ - Failure during conversion to COFF: file invalid or corrupt

When I try building just a simple program into VS2010, compiling succeeds yet when I try to build the solution it gives me this error:




LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt


What am I doing wrong?

realism - Is the electric track the tour vehicles follow on in Jurassic Park actually possible?

Jurassic Park tour vehicle


Based on the image above and examination while viewing Jurassic Park, it appears there is no physical connection between truck and track (though there may be).


Is the proposed method of moving the tour vehicles - having them follow a track that moves them along with electricity - actually a viable method of moving a vehicle?




To clarify, what @Shufler realizes in his comment:



I just understood the difference between the JP SUVs and electric trains (and OP's original question) -- that the SUVs don't appear to contact the track, where as subways and other electric trains have physical contact with a "third rail" or wire.



This is what I was getting at - I am familiar with monorails and how they work. What I was hoping to learn was whether or not a a track could propel a car without (discernible) contact electrically - which @wbogacz addresses.


Answer


I think the question is whether an autonomous car technology exists. The answer is yes.

The movie displays electronics that depended on communication on a short range of 1-2 ft. The current vision is to include communications to drive cars from 'such techniques as laser, radar, lidar, GPS and computer vision.'

People have been talking about autonomous cars and driverless highways since the 40's (corrected from 70's), and I met people during my job in the 90's who were hired to design such systems.

Also, the technology is independent of the power needed to propel the car. Gasoline/electric power - the technology makes no distinction. I think the movie made the car electric because it could be easily disabled for the plot.

UPDATE: While reviewing the relevant movie section, I hear Samuel Jackson specifically mentions the car batteries, leading me to think the track supplies no energy.

When the kids and the scientists jump out of the car to aid the Triceratops, the central computer says something to the effect 'Stopping park vehicles...'.

When Nedry (Newmann) sets the power to fail so he can escape, the track data flow fails to the vehicles bringing them to a halt right next to the T-Rex cage. T-Rex is no longer contained by 10k volts.


php - Looping through query results multiple times with mysqli_fetch_array?



Does the mysqli_fetch_array() function remove each value as it returns it? If not, how can I go back to the top of the array when I've finished looping through it?



I need to loop through the list several times, as I'm using it to generate unique usernames (by adding numbers to the end if it's already taken).



$uniqueName = true;

while($row = mysqli_fetch_array($namesList)) {
if ($row['Username'] == $UserBase) {

$uniqueName = false;
}
}

$number = 0;
if ($uniqueName == true) {
$User = $UserBase;
}
else {
while ($uniqueName == false) {

$uniqueName = true;
$number++;
$tempList = $namesList2;
while($row = mysqli_fetch_array($tempList)) {
if ($row['Username'] == $UserBase . $number) {
$uniqueName = false;
}
}
}
$User = $UserBase . $number;

}


$namesList is a list of all usernames in the database so far. Basically, $UserBase is the forename and surname of the user added together. What happens at the moment is that $User becomes $Userbase with a 1 on the end, even when it should be 2. However, if it's the first instance of the name then it doesn't add anything (which is working as intended).


Answer



a magic



$data = array();
while ($row = mysqli_fetch_array($res))
{

$data[] = $row;
}

foreach ($data as $row) echo $row['name'];
foreach ($data as $row) echo $row['name'];
foreach ($data as $row) echo $row['name'];
foreach ($data as $row) echo $row['name'];
foreach ($data as $row) echo $row['name'];
foreach ($data as $row) echo $row['name'];


php - How to force UTF-8 encoding in browser?



I have page which encoding is declared with







But when I enter the page another encoding (ISO) is chosen in browser. I have tried to set encoding by PHP method



header('Content-type: text/html; charset=utf-8');


But it also didn't help. All source files are encoded in UTF-8 without BOM. The only solution which I tried and it had worked was setting encoding in .htaccess file by adding AddDefaultCharset UTF-8 line, but then another pages on the server were not displayed correctly. How can I solve this problem?



Answer



Disable default charset:



AddDefaultCharset Off

Where to place the 'assets' folder in Android Studio?



I am confused about the assets folder. It doesn't come auto-created in Android Studio, and almost all the forums in which this is discussed talk about Eclipse.



How can the Assets directory be configured in Android Studio?


Answer



Since Android Studio uses the new Gradle-based build system, you should be putting assets/ inside of the source sets (e.g., src/main/assets/).



In a typical Android Studio project, you will have an app/ module, with a main/ sourceset (app/src/main/ off of the project root), and so your primary assets would go in app/src/main/assets/. However:




  • If you need assets specific to a build, such as debug versus release, you can create sourcesets for those roles (e.g,. app/src/release/assets/)


  • Your product flavors can also have sourcesets with assets (e.g., app/src/googleplay/assets/)


  • Your instrumentation tests can have an androidTest sourceset with custom assets (e.g., app/src/androidTest/assets/), though be sure to ask the InstrumentationRegistry for getContext(), not getTargetContext(), to access those assets




Also, a quick reminder: assets are read-only at runtime. Use internal storage, external storage, or the Storage Access Framework for read/write content.


android - java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference




I am trying to save player's name in shared preference and make it display in another activity by getting it again in shared preference but my app crash.



FATAL EXCEPTION: main



 Process: plp.cs4b.thesis.drawitapp, PID: 1970
java.lang.RuntimeException: Unable to start activity ComponentInfo{plp.cs4b.thesis.drawitapp/plp.cs4b.thesis.drawitapp.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Player.getName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String plp.cs4b.thesis.drawitapp.Player.getName()' on a null object reference
at plp.cs4b.thesis.drawitapp.PlayGame.onCreate(PlayGame.java:20)

at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more


Codes:



Player.java




public class Player {

private Context context;
private SharedPreferences prefSettingsU;
private SharedPreferences.Editor prefEditorU;
private static final int PREFERENCE_MODE_PRIVATE = 0;
private static final String MY_UNIQUE_PREF_FILE = "DrawItApp";

public Player(Context context, String name) {
this.context = context;

saveName(name);
}

public void saveName(String n) {
prefSettingsU = context.getSharedPreferences(MY_UNIQUE_PREF_FILE, PREFERENCE_MODE_PRIVATE);
prefEditorU = prefSettingsU.edit();
prefEditorU.putString("keyName", n);
prefEditorU.commit();
}


public String getName(Context ctx) {
prefSettingsU = ctx.getSharedPreferences(MY_UNIQUE_PREF_FILE, PREFERENCE_MODE_PRIVATE);
String name = prefSettingsU.getString("keyName", "ANONYMOUS");
return name;
}


PlayGame.java



public class PlayGame extends Activity {


private TextView welcomePlayer;
private ListView createdGames;
private Player mPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_game);


welcomePlayer = (TextView) findViewById (R.id.tvPlayerName);
welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

createdGames = (ListView) findViewById (R.id.listCreatedGames);
// adapter etc
createdGames.setEmptyView(findViewById (R.id.tvNoGames));


}



PlayerName.java



public class PlayerName extends Activity {

private EditText playerName;
private Player mPlayer;
public static Context context;

@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_name);
context = this;
playerName = (EditText) findViewById (R.id.etName);

}

public void onC_Confirm(View btnclick) {
mPlayer = new Player(context, String.valueOf(playerName.getText()));

//mPlayer.saveName();
Intent intent = new Intent(PlayerName.this, PlayGame.class);
startActivity(intent);
}

public void onC_testShPref(View btnclick) {
Intent intent = new Intent(PlayerName.this, PlayGame.class);
startActivity(intent);
}


Answer



Your app crash is at:



welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");


because mPlayer=null.



You forgot to initialize Player mPlayer in your PlayGame Activity.




mPlayer = new Player(context,"");

analysis - Did Tyler Durden forget his name? - Movies & TV




Ed Norton plays the Narrator or Jack ( due to reading a book that described someone called Jack's body parts from a 1st person perspective). Meanwhile Brad Pitt is introduced as Tyler Durden. Later on we find out that they are the same person.



So is Tyler Durden the new name he has chosen which he went and made an ID for and got various part-time jobs under or is it his original name and he somehow keeps blanking it out when he needs to tell police (things like his apartment exploded, or that other things will explode) or when he sees it on his checks from work or his work documents Id and many other things that would have his name on them?


Answer



In addition to Orion's answer, I'd add that while it's not specifically stated in the movie, I think it's implied well enough that the Narrator's name is not Tyler Durden. Tyler says at one point that the Narrator is "slowly letting himself become Tyler Durden." If his name was actually Tyler, this line wouldn't make any sense.



I suspect the movie avoids telling us his real name as a clue that he and Tyler are the same person. It was very clever indeed.



I still remember the first time I watched it and Marla is asking him his name, "What's your name? It's not on your card. Is it Radith? Corneleus? Any of the stupid names you give each night?" The bus passes in front of her, ending the scene so we don't get to hear the Narrator's answer . . . and it didn't phase me one bit. It just seemed like a neat way to end the scene.




Fight Club is definitely one of my top ten movies of all time.


php - Whit what is yeild different from echo

What is the difference between them and this two examples:



function result($r){
for($i=0; $i<$r; $i++){
yield $i;
}
}

foreach(result(15) as $r){

echo $r;
};


And one with echo only:



function result($r){
for($i=0; $i<$r; $i++){
echo $i;
}

}

result(15);


I am sure there is some but what is it? Couldn't answer myself after some googling, sorry.

A Java collection of value pairs? (tuples?)




I like how Java has a Map where you can define the types of each entry in the map, for example .



What I'm looking for is a type of collection where each element in the collection is a pair of values. Each value in the pair can have its own type (like the String and Integer example above), which is defined at declaration time.



The collection will maintain its given order and will not treat one of the values as a unique key (as in a map).



Essentially I want to be able to define an ARRAY of type or any other 2 types.



I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose.




I also realize that I could use a 2D array, but because of the different types I need to use, I'd have to make them arrays of OBJECT, and then I'd have to cast all the time.



I only need to store pairs in the collection, so I only need two values per entry. Does something like this exist without going the class route? Thanks!


Answer



The Pair class is one of those "gimme" generics examples that is easy enough to write on your own. For example, off the top of my head:



public class Pair {

private final L left;
private final R right;


public Pair(L left, R right) {
this.left = left;
this.right = right;
}

public L getLeft() { return left; }
public R getRight() { return right; }

@Override

public int hashCode() { return left.hashCode() ^ right.hashCode(); }

@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}


}


And yes, this exists in multiple places on the Net, with varying degrees of completeness and feature. (My example above is intended to be immutable.)


star wars - How were R2D2 and C3PO made in the original trilogy? - Movies & TV




I know they used a lot of mechanics back then, but were R2D2 and C3PO mechanical, a costume, or something else?


Answer



For c-3po, it was a costume, Anthony Daniels played c-3po:



Anthony Daniels as c3po



For R2-D2, It was a costume and a remote controlled robot. CGI was also used in the prequel trilogy. So, they had Kenny Baker to play him :
Kenny Baker inside R2-D2




And from Portrayal section of wookieepedia article on R2-D2 :




Baker performed the role of R2-D2 inside a standing unit of the droid, wearing a specially-made suit and manipulating the droid's lights and appendages, turning his head, rocking his body back and forth, and moving his eye with a rod. In addition to Baker's unit, every Star Wars film has made use of a number of remote control units, as Baker's was largely immobile.
[...]
A computer-generated R2-D2 was also used in many scenes of the prequel trilogy, including a scene in Episode II where the character walks up a staircase. Baker has stated that he would never have been able to do that in his costume.



Codeigniter - Cannot modify header information - headers already sent by

A PHP Error was encountered
Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /home/aphotel/public_html/application/config/config.php:1)

Filename: libraries/Session.php


Line Number: 366


#

Weird part of it, there is no session.php file in libraries folder

Newest linked questions

How Can I solve the logical error in the flowing code?




No value is being printed inside if condition block.
Where is the logical error?
Thanks.

#include
using namespace std;

int fx[]= {-1,-1,-1,0,1,1,1,0};
int fy[]= {-1,0,1,1,1,0,-1,...






How to handle incoming real time data with python pandas

Which is the most recommended/pythonic way of handling live incoming data with pandas?



Every few seconds I'm receiving a data point in the format below:



{'time' :'2013-01-01 00:00:00', 'stock' : 'BLAH',
'high' : 4.0, 'low' : 3.0, 'open' : 2.0, 'close' : 1.0}


I would like to append it to an existing DataFrame and then run some analysis on it.



The problem is, just appending rows with DataFrame.append can lead to performance issues with all that copying.



Things I've tried:



A few people suggested preallocating a big DataFrame and updating it as data comes in:



In [1]: index = pd.DatetimeIndex(start='2013-01-01 00:00:00', freq='S', periods=5)

In [2]: columns = ['high', 'low', 'open', 'close']

In [3]: df = pd.DataFrame(index=t, columns=columns)

In [4]: df
Out[4]:
high low open close
2013-01-01 00:00:00 NaN NaN NaN NaN
2013-01-01 00:00:01 NaN NaN NaN NaN
2013-01-01 00:00:02 NaN NaN NaN NaN
2013-01-01 00:00:03 NaN NaN NaN NaN
2013-01-01 00:00:04 NaN NaN NaN NaN

In [5]: data = {'time' :'2013-01-01 00:00:02', 'stock' : 'BLAH', 'high' : 4.0, 'low' : 3.0, 'open' : 2.0, 'close' : 1.0}

In [6]: data_ = pd.Series(data)

In [7]: df.loc[data['time']] = data_

In [8]: df
Out[8]:
high low open close
2013-01-01 00:00:00 NaN NaN NaN NaN
2013-01-01 00:00:01 NaN NaN NaN NaN
2013-01-01 00:00:02 4 3 2 1
2013-01-01 00:00:03 NaN NaN NaN NaN
2013-01-01 00:00:04 NaN NaN NaN NaN


The other alternative is building a list of dicts. Simply appending the incoming data to a list and slicing it into smaller DataFrames to do the work.



In [9]: ls = []

In [10]: for n in range(5):
.....: # Naive stuff ahead =)
.....: time = '2013-01-01 00:00:0' + str(n)
.....: d = {'time' : time, 'stock' : 'BLAH', 'high' : np.random.rand()*10, 'low' : np.random.rand()*10, 'open' : np.random.rand()*10, 'close' : np.random.rand()*10}
.....: ls.append(d)

In [11]: df = pd.DataFrame(ls[1:3]).set_index('time')

In [12]: df
Out[12]:
close high low open stock
time
2013-01-01 00:00:01 3.270078 1.008289 7.486118 2.180683 BLAH
2013-01-01 00:00:02 3.883586 2.215645 0.051799 2.310823 BLAH


or something like that, maybe processing the input a little bit more.

html - CSS - design parent class if child has a specific class

Answer




Possible Duplicate:
Complex CSS selector for parent of active child
Is there a CSS parent selector?






Is there a way to design parent class based on if its child elements has a specific class?






text




.






text




I want to design the first .container differently based on if the child class is content1 or content2.
It must be pure css solution, without javascript.

javascript convert object to string

I have some form with several values depending which is selected









Now script



$(document).ready(function() {

$("#go").click(function() {

// Obtener la referencia a las listas
var lista1 = eval(document.getElementById("tropa1"));
// Obtener el valor de la opción seleccionada
var valort1 = eval(lista1.options[lista1.selectedIndex].value);
var cadena = String(valort1);
console.log("PHP: " + String(valort1));
if (cadena.indexOf('z') != -1) {
// value selected in options does not contain 'z'
console.log("DOES NOT CONTAIN Z");
console.log(cadena);

confront(nu1, valort1, nu2, valort2)

} else {
//// value selected in options contains 'z'
console.log("CONTAINS Z");
console.log(cadena);
}
})

});


I tried to make this, but console return : [object Object] and not show string.
even using String() function or eval() to convert object to a string

java.util.concurrent.RejectedExecutionException: org.eclipse.jetty.client.HttpClient

I am running the following program on jetty asynchronous http client.





Code is
public static void main(String[] args) throws InterruptedException, TimeoutException, ExecutionException {
String url2="http://www.google.co.in";


// JettyHttp.sendHttpSyncReq(url2);
JettyHttp.sendHttpAsyncReq(url2);

}
public static void sendHttpAsyncReq(String url) throws InterruptedException, TimeoutException, ExecutionException
{
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient =new HttpClient(sslContextFactory);
long total_t1=System.currentTimeMillis();



httpClient.newRequest(url).send(new Response.CompleteListener() {

@Override
public void onComplete(Result arg0) {
// TODO Auto-generated method stub

}
});


long total_t2=System.currentTimeMillis();
System.out.println(total_t2-total_t1 +" ==");


}


Error I am getting is





Exception in thread "main" java.util.concurrent.RejectedExecutionException: org.eclipse.jetty.client.HttpClient@412429c is stopped
at org.eclipse.jetty.client.HttpDestination.send(HttpDestination.java:198)
at org.eclipse.jetty.client.HttpClient.send(HttpClient.java:485)
at org.eclipse.jetty.client.HttpRequest.send(HttpRequest.java:486)
at org.eclipse.jetty.client.HttpRequest.send(HttpRequest.java:479)
at com.nielsen.http.JettyHttp.sendHttpAsyncReq(JettyHttp.java:38)
at com.nielsen.http.JettyHttp.main(JettyHttp.java:28)




Please Help me in this to get out of error::

java - how to check https using HttpURLConnection




I am trying to connect to a url with HttpUrlConnection. the host which user enter can be running on http:// or https://. when i am connecting it throws an exception as EOFException.
Is there any way that i identify that url is running on https through some error code or something ??



Following code i am using for this purpose.



HttpURLConnection.setFollowRedirects(true);
con = (HttpURLConnection) new URL(url[0]).openConnection();
con.setRequestMethod("POST");
con.setConnectTimeout(20000);



I m using the abode code what if the url is not valid like i type wwww.gooooooodldldle.com
which is not valid url. I am getting Java.net.SocketTimeout exception here


Answer



The URL cannot change after the connection has been created if you don't reacreate it again. I would do it like this to know the protocol.



URL url;
try {
url = new URL(url[0]);
if(url.getProtocol().equalsIgnoreCase(HTTPS){

Lod.i(TAG, "Is HTTPS connection");
} else {
Log.i(TAG, "Is HTTP connection");
}
} catch (EOFException eofEx) {
eofEx.printStackTrace();
}


After update:




You can check the url string with a Regular Expresion and then if it's correct try the connection. Or put all the logic inside a try catch and show a toast or dialog if the exception is rised.



Hope it helps.


c# - Prevent Caching in ASP.NET MVC for specific actions using an attribute




I have an ASP.NET MVC 3 application. This application requests records through JQuery. JQuery calls back to a controller action that returns results in JSON format. I have not been able to prove this, but I'm concerned that my data may be getting cached.



I only want the caching to be applied to specific actions, not for all actions.



Is there an attribute that I can put on an action to ensure that the data does not get cached? If not, how do I ensure that the browser gets a new set of records each time, instead of a cached set?


Answer



To ensure that JQuery isn't caching the results, on your ajax methods, put the following:



$.ajax({
cache: false

//rest of your ajax setup
});


Or to prevent caching in MVC, we created our own attribute, you could do the same. Here's our code:



[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)

{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();

base.OnResultExecuting(filterContext);
}
}



Then just decorate your controller with [NoCache]. OR to do it for all you could just put the attribute on the class of the base class that you inherit your controllers from (if you have one) like we have here:



[NoCache]
public class ControllerBase : Controller, IControllerBase


You can also decorate some of the actions with this attribute if you need them to be non-cacheable, instead of decorating the whole controller.




If your class or action didn't have NoCache when it was rendered in your browser and you want to check it's working, remember that after compiling the changes you need to do a "hard refresh" (Ctrl+F5) in your browser. Until you do so, your browser will keep the old cached version, and won't refresh it with a "normal refresh" (F5).


Friday, August 2, 2019

Batman Begins credit scene - Movies & TV



I was rewatching Batman begins and watched it until the credits roll. I noticed that Liam Neeson was listed as Ducard, Ken Watanabe was listed as Ra's Al ghul. It made me ponder over the entire movie as to whether Liam Neeson's character was really Ra's Al Ghul or did he take over the league after the death of Ken Watanabe because I remember towards the end, Bruce Wayne's character complimenting on Ra's deception tricks when they meet at Wayne Manor again. Is that a minor glitch or intended to be food for thought?


Answer



I think Neeson was indeed Ra's Al Ghul, and that the credits were only that way because that was how they would be listed on IMDb - if their true roles had been listed then the big surprise would be revealed before the film opened. This is similar to Marion Cotillard's character being listed on IMDb as Talia Al Ghul a year before TDKR opened (the listing was changed recently) thus ruining that big twist.



Inserting data from html form using php into data table in mysql database



I'm new here and have recently started studying various forms of code to create simple solutions to my various projects. I've used many of the helpful tips a lot of you have posted on this website but I think I have finally reached a point where I can't figure out for the life of me how to fix. So I decided to turn to you all for help. It seems like it should be a simple solution to me but I cannot find it so maybe fresh eyes will help. So here it is I hope someone may be able to assist me. I help run an event here in my city that uses the video game Rock Band for karaoke purposes. I have a table setup called rbn_setlist_small that has two columns of 'Artist' and 'Song Title'. I have to periodically insert more songs into the table to account for newly purchased songs. So I created a form to insert the data into the table. It's a Simple form that has two fields Artist and Song Title. Whenever I enter test information (say Artist: 123, Song Title: test) it says the data has been entered but when I go and check the table the new data that has been entered just has a blank spot under Artist and Title under Song Title. So I'm sure I'm missing a comma or something somewhere but I cannot find it.



This is the php for the form:



/* Attempt MySQL server connection.*/
$link = mysqli_connect("host", "user", "pass", "db");


/*Check connection*/
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

/*attempt insert query execution*/
$query = "INSERT INTO `rbn_setlist_small`(`Artist`, `Song Title`)


VALUES ('$Artist', '$Song Title')";
if ($result = mysqli_query($link, $query)) {
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}

/*close connection*/
mysqli_close($link);
?>



and this the HTML for the form:







Add Music to Database



















Also any assistance in my coding is appreciated I'm a super novice.
Thank you all for any assistance.


Answer



It seems like you've simply forgot to fetch the value from the form! That aside, your $Song Title isn't a variable, it's a variable, then a space, then the string "Title".




I recommend you don't use any names in a form or in the database that contains spaces, use underscore as a replacement (or choose simpler names). So for instance, your






should be







instead, which can be fetched in PHP with $_POST['Song_Title']. Using that, we can send it to the database. I've modified your code with the following improvements:




  • Fetching the values from the form, using $_POST

  • Added parameterized queries with placeholders (mysqli::prepare) to protect against SQL injection

  • Added checks (isset()) so we insert values only if the form has been sent



The above points would result in the following PHP snippet




/* Attempt MySQL server connection.*/
$link = mysqli_connect("host", "user", "pass", "db");

/*Check connection*/
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}


if (isset($_POST['Artist'], $_POST['Song_Title'])) {
if ($stmt = $link->prepare("INSERT INTO `rbn_setlist_small`(`Artist`, `Song Title`) VALUES (?, ?)")) {
$stmt->bind_param("ss", $_POST['Artist'], $_POST['Song_Title']);
if (!$stmt->execute()) {
error_log("Execute failed ".$stmt->error);
} else {
echo "Data successfully inserted! Artist ".$_POST['Artist']." and song ".$_POST['Song_Title'];
}
$stmt->close();
} else {

error_log("Prepare failed ".$link->error);
}
}


Also, when troubleshooting, PHP will give you the exact errors if you just enable error-reporting, by adding



error_reporting(E_ALL);
ini_set("display_errors", 1);



at the top of your file. MySQLi will also throw back whatever errors it might see with $link->error for normal MySQLi functions, and $stmt->error when using MySQLi-statements (for objects called on the object created by $link->prepare()).






python - How do I trim whitespace from a string?



How do I remove leading and trailing whitespace from a string in Python?



For example:



" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"


Answer



Just one space, or all consecutive spaces? If the second, then strings already have a .strip() method:



>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'

>>> ' Hello '.strip() # ALL consecutive spaces at both ends removed
'Hello'


If you need only to remove one space however, you could do it with:



def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s


>>> strip_one_space(" Hello ")
' Hello'


Also, note that str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip, i.e.:



>>> "  Hello\n".strip(" ")
'Hello\n'


php - Send Bootstrap Button-Group value in a form with Get or Post




I created this form with bootstrap 3:



                        





















Im using the button group, because it looks better then a dropdwon menue or just checkboxes.



I tried to send the btn-group value by the _get methode but it does not work.
So how can in submit the value with my _get methode to my PHP file?



Thank you for helping


Answer



I found a solution




                            














Practical use of possessive quantifiers regex

I understand .* (greedy quantifier) backtracks and tries to find a match. and .*+ (possessive quantifier) does not backtrack.



However I have been using .* and .\*? frequently but don't know when to use .*+.



Can somebody give a situation or an example where .*+ should be used?



explanation with an example is appreciated.



EDIT:




i have gone through the theory part and i repeat i understand how it works. i just need one example that matches possessive quantifiers (.*+)

javascript - Where to load scripts or css from CDN, head or body?

Where should I put the code for CDN scripts or styles? In the head element or before the closing body tag?

Transitions on the CSS display property



I'm currently designing a CSS 'mega dropdown' menu - basically a regular CSS-only dropdown menu, but one that contains different types of content.



At the moment, it appears that CSS 3 transitions don't apply to the 'display' property, i.e., you can't do any sort of transition from display: none to display: block (or any combination).



Is there a way for the second-tier menu from the above example to 'fade in' when someone hovers over one of the top level menu items?



I'm aware that you can use transitions on the visibility: property, but I can't think of a way to use that effectively.



I've also tried using height, but that just failed miserably.



I'm also aware that it's trivial to achieve this using JavaScript, but I wanted to challenge myself to use just CSS, and I think I'm coming up a little short.


Answer



You can concatenate two transitions or more, and visibility is what comes handy this time.





div {
border: 1px solid #eee;
}
div > ul {
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.5s linear;
}
div:hover > ul {
visibility: visible;
opacity: 1;
}



  • Item 1

  • Item 2

  • Item 3







(Don't forget the vendor prefixes to the transition property.)



More details are in this article.


How to copy a file in python

I am having a file named as new11 and new12 and the path is source=\Users\user.CLPSTPDFC46\Desktop\new11 and dest=\Users\user.CLPSTPDFC46\Desktop\new12



Now I need to copy the content from new11 to new12. how can I approach this ?

web services - HTTP POST and GET using cURL in Linux

I have a server application written in ASP.NET on Windows that provides a web service.



How can I call the web service in Linux with cURL?

php - Fatal error: Call to a member function fetch_assoc() on a non-object




I'm trying to execute a few queries to get a page of information about some images. I've written a function



function get_recent_highs($view_deleted_images=false)
{
$lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1));
$query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; //move to database class
$result = $this->database->query($query);
$page = array();

while($row = $result->fetch_assoc())
{
try
{
array_push($page, new Image($row['image_id'], $view_deleted_images));
}
catch(ImageNotFoundException $e)
{
throw $e;
}

}
return $page;
}


that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.



Fatal error: Call to a member function fetch_assoc() on a non-object



$result is a mysqli resultset, so I'm baffled as to why this isn't working.


Answer



That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::



$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}



That should throw an exception if there's an error...


email - PHP mail() doesn't work

I want to script a simple registration form with activation mail and so on. But for some reason mail() doesn't send the emails, or my 3 different email accounts (hotmail,gmail,yahoo) don't receive them and therefore don't even put them in the spam folder.



Code:



    $mailto = 'xxx@example.com';
$subject = 'the subject';
$message = 'the message';
$from = 'system@example.net';

$header = 'From:'.$from;

if(mail($mailto,$subject,$message,$header)) {
echo 'Email on the way';
}
?>


Everytime it outputs 'Email on the way' so mail() returns true, right? I really don't get it, I've even tried to turn off my little snitch (although I didn't block SMTP).

c++ - Get a single line representation for multiple close by lines clustered together in opencv

I detected lines in an image and drew them in a separate image file in OpenCv C++ using HoughLinesP method. Following is a part of that resulting image. There are actually hundreds of small and thin lines which form a big single line.



enter image description here



But I want single few lines that represent all those number of lines. Closer lines should be merged together to form a single line. For example above set of lines should be represented by just 3 separate lines as below.




enter image description here



The expected output is as above. How to accomplish this task.









Up to now progress result from akarsakov's answer.







(separate classes of lines resulted are drawn in different colors). Note that this result is the original complete image I am working on, but not the sample section I had used in the question



enter image description here

c++ - Deep copy vs Shallow Copy







What is the difference between deep and shallow copy. What type of a copy does a copy constructor do?

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...