I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.
var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;
var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);
I would like to know if there is a better way to do this using jQuery. I've been experimenting with:
var odv = $.create("div");
$.append(odv);
// And many more
But I'm not sure if this is any better.
here's your example in "one" line.
this.$OuterDiv = $('')
.hide()
.append($('')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;
Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about $("") vs
$("")
vs
$(document.createElement('div'))
as a way of creating new elements, and which is "best".
I put together a small benchmark, and here's roughly the results of repeating the above options 100,000 times:
jQuery 1.4, 1.5, 1.6
Chrome 11 Firefox 4 IE9
440ms 640ms 460ms
420ms 650ms 480ms
createElement 100ms 180ms 300ms
jQuery 1.3
Chrome 11
770ms
3800ms
createElement 100ms
jQuery 1.2
Chrome 11
3500ms
3500ms
createElement 100ms
I think it's no big surprise, but document.createElement
is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.
Update 2
Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!
http://jsben.ch/#/ARUtz
I've been told by others that writing using namespace std;
in code is wrong, and that I should use std::cout
and std::cin
directly instead.
Why is using namespace std;
considered a bad practice? Is it inefficient or does it risk declaring ambiguous variables (variables that share the same name as a function in std
namespace)? Does it impact performance?
This is not related to performance at all. But consider this: you are using two libraries called Foo and Bar:
using namespace foo;
using namespace bar;
Everything works fine, and you can call Blah()
from Foo and Quux()
from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called Quux()
. Now you've got a conflict: Both Foo 2.0 and Bar import Quux()
into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match.
If you had used foo::Blah()
and bar::Quux()
, then the introduction of foo::Quux()
would have been a non-event.
Possible Duplicate:
Should Usings be inside or outside the namespace
I'm supporting some code that, unusually, has all its using statements contained within the namespace declaration. It makes me a bit uncomfortable but I have no idea if this should be anything to be concerned about or not. I can't think of an immediate problem other than it being counter to usual convention.
Is there anything wrong with:
namespace myProject.controls
{
using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
Instead of the more widely-used:
using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace myProject.controls
{
I'm having a situation here, I need my class to be inherited from List
, but when I do this XmlSerializer does not serialize any property or field declared in my class, the following sample demonstrates:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DoSerialize();
}
private void DoSerialize()
{
MyClass obj = new MyClass();
obj.Add(1);
obj.Add(2);
obj.Add(3);
XmlSerializer s = new XmlSerializer(typeof(MyClass));
StringWriter sw = new StringWriter();
s.Serialize(sw, obj);
}
}
[Serializable]
[XmlRoot]
public class MyClass : List
{
public MyClass()
{
}
int myAttribute = 2011;
[XmlAttribute]
public int MyAttribute
{
get
{
return myAttribute;
}
set
{
myAttribute = value;
}
}
}
the resulting XML:
1
2
3
This is by design. I don't know why this decision was made, but it is stated in the documentation:
- Classes that implement ICollection or IEnumerable. Only collections are
serialized, not public properties.
(Look under "Items that can be serialized" section). Someone has filed a bug against this, but it won't be changed - here, Microsoft also confirms that not including the properties for classes implementing ICollection
is in fact the behaviour of XmlSerializer.
A workaround would be to either:
- Implement
IXmlSerializable
and control serialization yourself.
or
- Change MyClass so it has a public property of type List (and don't subclass it).
or
- Use DataContractSerializer, which handles this scenario.
In HTML is there a way to redirect to a different web page without there being a notification? I really need this for a website so that people cannot access work in progress pages and are redirected to the home page. But everything I have tried is an optional redirection.
During coding in Visual Studio I got an unresolved external symbol error
and I've got no idea what to do. I don't know what's wrong.
Could you please decipher me? Where should I be looking for what kind of errors?
1>Form.obj : error LNK2019: unresolved external symbol "public: class Field * __thiscall Field::addField(class Field *)" (?addField@Field@@QAEPAV1@PAV1@@Z) referenced in function "public: void __thiscall Form::parse(class std::basic_stringstream,class std::allocator > &)" (?parse@Form@@QAEXAAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)
1>Form.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall Field::parse(class std::basic_stringstream,class std::allocator > &)" (?parse@Field@@UAEXAAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "public: __thiscall InputField::InputField(class std::basic_stringstream,class std::allocator > &)" (??0InputField@@QAE@AAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Field::prompt(void)" (?prompt@Field@@UAEXXZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual class std::basic_string,class std::allocator > __thiscall Field::getName(void)" (?getName@Field@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual class std::basic_string,class std::allocator > __thiscall Field::getType(void)" (?getType@Field@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Field::describe(void)" (?describe@Field@@UAEXXZ)
1>C:\Users\tomy\Documents\Visual Studio 2010\Projects\zapoctovkac++\Debug\zapoctovkac++.exe : fatal error LNK1120: 6 unresolved externals
This error often means that some function has a declaration, but not a definition.
Example:
// A.hpp
class A
{
public:
void myFunc(); // Function declaration
};
// A.cpp
// Function definition
void A::myFunc()
{
// do stuff
}
In your case, the definition cannot be found. The issue could be that you are including a header file, which brings in some function declarations, but you either:
- do not define the functions in your cpp file (if you wrote this code yourself)
- do not include the lib/dll file that contains the definitions
A common mistake is that you define a function as a standalone and forget the class selector, e.g. A::
, in your .cpp file:
Wrong: void myFunc() { /* do stuff */ }
Right: void A::myFunc() { /* do stuff */ }
I want to match strings like
(()) - 2 open brackets, 2 closed brackets
but not strings like
()() - open and closed and then another opens and closses
(() - two opens, one closed
So more specific i want a regex like this
\({n}\){n}
n opened brackets followed by (same value for n, but n must be greedy) n closed brackets.
Wordpress website went down without any changes.
Here are the error messages:
Warning: include(/home/theme/public_html/wp-content/themes/sachba/functions.php): failed to open stream: Permission denied in /home/user/public_html/wp-settings.php on line 425
Warning: include(): Failed opening '/home/sachbaco/public_html/wp-content/themes/theme/functions.php' for inclusion (include_path='.:/opt/cpanel/ea-php56/root/usr/share/pear') in /home/user/public_html/wp-settings.php on line 425
Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/wp-settings.php:425) in /home/user/public_html/wp-includes/pluggable.php on line 1195
Any help please?
I've looked through all the other StackOverflow (and google) posts with the same problem, but none seemed to address my problem.
I am using PDO and PHP.
My code:
$vals = array(
':from' => $email,
':to' => $recipient,
':name' => $name,
':subject' => $subject,
':message' = >$message
);
print_r($vals);
try {
$pdo = new PDOConfig();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM messages WHERE `message` LIKE :message";
$q = $pdo->prepare($sql);
$q->execute(array(':message' => $vals[':message']));
$resp = $q->fetchAll();
foreach ($resp as $row) {
throw new Exception('Please do not post the same message twice!');
}
$sql = "INSERT INTO messages (from, to, name, subject, message) VALUES (:from, :to, :name, :subject, :message)";
$q = $pdo->prepare($sql);
$q->execute($vals);
}
catch(PDOException $e) {
echo $e->getMessage();
}
and the first print_r gives
Array ( [:from] => abc@gmail.com
[:to] => lala@me.com
[:name] => abc
[:subject] => abc
[:message] => abc )
which is expected (none are null)
but it outputs the error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from, to, name, subject, message) VALUES ('abc@gmail.com', 'lala@me.com' at line 1
No idea how to fix this. any ideas?
from
is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`
.
Personally, I wouldn't bother; I'd just rename the column.
PS. as pointed out in the comments, to
is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.
I have developed a simple (no COM) C++ DLL for VBA (Excel) in VS 2008, which works perfectly on Win 10 and Excel 2016, as well as on Win XP and Excel 2003, both during debug and release. I have developed it following this example.
Now, jumping to the issue, using the same recipe and piece of code I have developed the same DLL, but in VS 2015. The debug and release versions for x64 work perfectly, but when I want to release the DLL for X86, it throws me the following error:
1>defFile.def : error LNK2001: unresolved external symbol "func_name"
Additional info, the project has only 2 files, as in the example:
Anyone has an idea how to get over this link issue?
My feeling is that, there might be a setting that I overlooked or skipped!
If you need the code or the settings, I will happily provide them, but they should be as in the example!
Thanks!
Is there a way to deal with callback functions inside an async function() other than mixing in bluebird or return new Promise()?
Examples are fun...
Problem
async function bindClient () {
client.bind(LDAP_USER, LDAP_PASS, (err) => {
if (err) return log.fatal('LDAP Master Could Not Bind', err);
});
}
Solution
function bindClient () {
return new Promise((resolve, reject) => {
client.bind(LDAP_USER, LDAP_PASS, (err, bindInstance) => {
if (err) {
log.fatal('LDAP Master Could Not Bind', err);
return reject(err);
}
return resolve(bindInstance);
});
});
}
Is there a more elegant solution?
NodeJS v.8.x.x natively supports promisifying and async-await, so it's time to enjoy the stuff (:
const
promisify = require('util').promisify,
bindClient = promisify(client.bind);
let clientInstance; // defining variable in global scope
(async () => { // wrapping routine below to tell interpreter that it must pause (wait) for result
try {
clientInstance = await bindClient(LDAP_USER, LDAP_PASS);
}
catch(error) {
console.log('LDAP Master Could Not Bind. Error:', error);
}
})();
or just simply use co
package and wait for native support of async-await:
const co = require('co');
co(function*() { // wrapping routine below to tell interpreter that it must pause (wait) for result
clientInstance = yield bindClient(LDAP_USER, LDAP_PASS);
if (!clientInstance) {
console.log('LDAP Master Could Not Bind');
}
});
P.S. async-await is syntactic sugar for generator-yield language construction.
Why does Google prepend while(1);
to their (private) JSON responses?
For example, here's a response while turning a calendar on and off in Google Calendar:
while (1);
[
['u', [
['smsSentFlag', 'false'],
['hideInvitations', 'false'],
['remindOnRespondedEventsOnly', 'true'],
['hideInvitations_remindOnRespondedEventsOnly', 'false_true'],
['Calendar ID stripped for privacy', 'false'],
['smsVerifiedFlag', 'true']
]]
]
I would assume this is to prevent people from doing an eval()
on it, but all you'd really have to do is replace the while
and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.
I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, Google Docs starts with &&&START&&&
instead, and Google Contacts seems to start with while(1); &&&START&&&
.
What's going on here?
It prevents JSON hijacking, a major JSON security issue that is formally fixed in all major browsers since 2011 with ECMAScript 5.
Contrived example: say Google has a URL like mail.google.com/json?action=inbox
which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a
tag. The URL is visited with your cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.
The while(1);
or &&&BLAH&&&
prevents this: an AJAX request at mail.google.com
will have full access to the text content, and can strip it away. But a
tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.
This does not address the issue of cross-site request forgery.
I am trying to run one of the sample projects that come with android (and I have tried many). I keep getting this error in eclipse's Problems
window.
Error generating final archive: Debug Certificate expired on 10/24/12 7:27 AM com.example.android.mediafx.HelloEffects Unknown Android Packaging Problem
Basically I import the project from the samples
directory. Then I right click on the project and choose
Run As --> android project
Another symptom of the problem is that the project has a red x
next to it, but no red x
in any sub-directory or file.
Delete ~/.android/debug.keystore
and try again. The ADT should generate new debug keystore with new certificate in it.
As a C# developer I'm used to run through constructors:
class Test {
public Test() {
DoSomething();
}
public Test(int count) : this() {
DoSomethingWithCount(count);
}
public Test(int count, string name) : this(count) {
DoSomethingWithName(name);
}
}
Is there a way to do this in C++?
I tried calling the Class name and using the 'this' keyword, but both fails.
C++11: Yes!
C++11 and onwards has this same feature (called delegating constructors).
The syntax is slightly different from C#:
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {}
};
C++03: No
Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:
You can combine two (or more) constructors via default parameters:
class Foo {
public:
Foo(char x, int y=0); // combines two constructors (char) and (char, int)
// ...
};
Use an init method to share common code:
class Foo {
public:
Foo(char x);
Foo(char x, int y);
// ...
private:
void init(char x, int y);
};
Foo::Foo(char x)
{
init(x, int(x) + 7);
// ...
}
Foo::Foo(char x, int y)
{
init(x, y);
// ...
}
void Foo::init(char x, int y)
{
// ...
}
See the C++FAQ entry for reference.