Programs & Examples On #Article

justify-content property isn't working

This answer might be stupid, but I spent quite some time to figure it out.

What happened to me was I didn't set display: flex to the container. And of course, justify-content won't work without a container with that property.

The definitive guide to form-based website authentication

PART I: How To Log In

We'll assume you already know how to build a login+password HTML form which POSTs the values to a script on the server side for authentication. The sections below will deal with patterns for sound practical auth, and how to avoid the most common security pitfalls.

To HTTPS or not to HTTPS?

Unless the connection is already secure (that is, tunneled through HTTPS using SSL/TLS), your login form values will be sent in cleartext, which allows anyone eavesdropping on the line between browser and web server will be able to read logins as they pass through. This type of wiretapping is done routinely by governments, but in general, we won't address 'owned' wires other than to say this: Just use HTTPS.

In essence, the only practical way to protect against wiretapping/packet sniffing during login is by using HTTPS or another certificate-based encryption scheme (for example, TLS) or a proven & tested challenge-response scheme (for example, the Diffie-Hellman-based SRP). Any other method can be easily circumvented by an eavesdropping attacker.

Of course, if you are willing to get a little bit impractical, you could also employ some form of two-factor authentication scheme (e.g. the Google Authenticator app, a physical 'cold war style' codebook, or an RSA key generator dongle). If applied correctly, this could work even with an unsecured connection, but it's hard to imagine that a dev would be willing to implement two-factor auth but not SSL.

(Do not) Roll-your-own JavaScript encryption/hashing

Given the perceived (though now avoidable) cost and technical difficulty of setting up an SSL certificate on your website, some developers are tempted to roll their own in-browser hashing or encryption schemes in order to avoid passing cleartext logins over an unsecured wire.

While this is a noble thought, it is essentially useless (and can be a security flaw) unless it is combined with one of the above - that is, either securing the line with strong encryption or using a tried-and-tested challenge-response mechanism (if you don't know what that is, just know that it is one of the most difficult to prove, most difficult to design, and most difficult to implement concepts in digital security).

While it is true that hashing the password can be effective against password disclosure, it is vulnerable to replay attacks, Man-In-The-Middle attacks / hijackings (if an attacker can inject a few bytes into your unsecured HTML page before it reaches your browser, they can simply comment out the hashing in the JavaScript), or brute-force attacks (since you are handing the attacker both username, salt and hashed password).

CAPTCHAS against humanity

CAPTCHA is meant to thwart one specific category of attack: automated dictionary/brute force trial-and-error with no human operator. There is no doubt that this is a real threat, however, there are ways of dealing with it seamlessly that don't require a CAPTCHA, specifically properly designed server-side login throttling schemes - we'll discuss those later.

Know that CAPTCHA implementations are not created alike; they often aren't human-solvable, most of them are actually ineffective against bots, all of them are ineffective against cheap third-world labor (according to OWASP, the current sweatshop rate is $12 per 500 tests), and some implementations may be technically illegal in some countries (see OWASP Authentication Cheat Sheet). If you must use a CAPTCHA, use Google's reCAPTCHA, since it is OCR-hard by definition (since it uses already OCR-misclassified book scans) and tries very hard to be user-friendly.

Personally, I tend to find CAPTCHAS annoying, and use them only as a last resort when a user has failed to log in a number of times and throttling delays are maxed out. This will happen rarely enough to be acceptable, and it strengthens the system as a whole.

Storing Passwords / Verifying logins

This may finally be common knowledge after all the highly-publicized hacks and user data leaks we've seen in recent years, but it has to be said: Do not store passwords in cleartext in your database. User databases are routinely hacked, leaked or gleaned through SQL injection, and if you are storing raw, plaintext passwords, that is instant game over for your login security.

So if you can't store the password, how do you check that the login+password combination POSTed from the login form is correct? The answer is hashing using a key derivation function. Whenever a new user is created or a password is changed, you take the password and run it through a KDF, such as Argon2, bcrypt, scrypt or PBKDF2, turning the cleartext password ("correcthorsebatterystaple") into a long, random-looking string, which is a lot safer to store in your database. To verify a login, you run the same hash function on the entered password, this time passing in the salt and compare the resulting hash string to the value stored in your database. Argon2, bcrypt and scrypt store the salt with the hash already. Check out this article on sec.stackexchange for more detailed information.

The reason a salt is used is that hashing in itself is not sufficient -- you'll want to add a so-called 'salt' to protect the hash against rainbow tables. A salt effectively prevents two passwords that exactly match from being stored as the same hash value, preventing the whole database being scanned in one run if an attacker is executing a password guessing attack.

A cryptographic hash should not be used for password storage because user-selected passwords are not strong enough (i.e. do not usually contain enough entropy) and a password guessing attack could be completed in a relatively short time by an attacker with access to the hashes. This is why KDFs are used - these effectively "stretch the key", which means that every password guess an attacker makes causes multiple repetitions of the hash algorithm, for example 10,000 times, which causes the attacker to guess the password 10,000 times slower.

Session data - "You are logged in as Spiderman69"

Once the server has verified the login and password against your user database and found a match, the system needs a way to remember that the browser has been authenticated. This fact should only ever be stored server side in the session data.

If you are unfamiliar with session data, here's how it works: A single randomly-generated string is stored in an expiring cookie and used to reference a collection of data - the session data - which is stored on the server. If you are using an MVC framework, this is undoubtedly handled already.

If at all possible, make sure the session cookie has the secure and HTTP Only flags set when sent to the browser. The HttpOnly flag provides some protection against the cookie being read through XSS attack. The secure flag ensures that the cookie is only sent back via HTTPS, and therefore protects against network sniffing attacks. The value of the cookie should not be predictable. Where a cookie referencing a non-existent session is presented, its value should be replaced immediately to prevent session fixation.

Session state can also be maintained on the client side. This is achieved by using techniques like JWT (JSON Web Token).

PART II: How To Remain Logged In - The Infamous "Remember Me" Checkbox

Persistent Login Cookies ("remember me" functionality) are a danger zone; on the one hand, they are entirely as safe as conventional logins when users understand how to handle them; and on the other hand, they are an enormous security risk in the hands of careless users, who may use them on public computers and forget to log out, and who may not know what browser cookies are or how to delete them.

Personally, I like persistent logins for the websites I visit on a regular basis, but I know how to handle them safely. If you are positive that your users know the same, you can use persistent logins with a clean conscience. If not - well, then you may subscribe to the philosophy that users who are careless with their login credentials brought it upon themselves if they get hacked. It's not like we go to our user's houses and tear off all those facepalm-inducing Post-It notes with passwords they have lined up on the edge of their monitors, either.

Of course, some systems can't afford to have any accounts hacked; for such systems, there is no way you can justify having persistent logins.

If you DO decide to implement persistent login cookies, this is how you do it:

  1. First, take some time to read Paragon Initiative's article on the subject. You'll need to get a bunch of elements right, and the article does a great job of explaining each.

  2. And just to reiterate one of the most common pitfalls, DO NOT STORE THE PERSISTENT LOGIN COOKIE (TOKEN) IN YOUR DATABASE, ONLY A HASH OF IT! The login token is Password Equivalent, so if an attacker got their hands on your database, they could use the tokens to log in to any account, just as if they were cleartext login-password combinations. Therefore, use hashing (according to https://security.stackexchange.com/a/63438/5002 a weak hash will do just fine for this purpose) when storing persistent login tokens.

PART III: Using Secret Questions

Don't implement 'secret questions'. The 'secret questions' feature is a security anti-pattern. Read the paper from link number 4 from the MUST-READ list. You can ask Sarah Palin about that one, after her Yahoo! email account got hacked during a previous presidential campaign because the answer to her security question was... "Wasilla High School"!

Even with user-specified questions, it is highly likely that most users will choose either:

  • A 'standard' secret question like mother's maiden name or favorite pet

  • A simple piece of trivia that anyone could lift from their blog, LinkedIn profile, or similar

  • Any question that is easier to answer than guessing their password. Which, for any decent password, is every question you can imagine

In conclusion, security questions are inherently insecure in virtually all their forms and variations, and should not be employed in an authentication scheme for any reason.

The true reason why security questions even exist in the wild is that they conveniently save the cost of a few support calls from users who can't access their email to get to a reactivation code. This at the expense of security and Sarah Palin's reputation. Worth it? Probably not.

PART IV: Forgotten Password Functionality

I already mentioned why you should never use security questions for handling forgotten/lost user passwords; it also goes without saying that you should never e-mail users their actual passwords. There are at least two more all-too-common pitfalls to avoid in this field:

  1. Don't reset a forgotten password to an autogenerated strong password - such passwords are notoriously hard to remember, which means the user must either change it or write it down - say, on a bright yellow Post-It on the edge of their monitor. Instead of setting a new password, just let users pick a new one right away - which is what they want to do anyway. (An exception to this might be if the users are universally using a password manager to store/manage passwords that would normally be impossible to remember without writing it down).

  2. Always hash the lost password code/token in the database. AGAIN, this code is another example of a Password Equivalent, so it MUST be hashed in case an attacker got their hands on your database. When a lost password code is requested, send the plaintext code to the user's email address, then hash it, save the hash in your database -- and throw away the original. Just like a password or a persistent login token.

A final note: always make sure your interface for entering the 'lost password code' is at least as secure as your login form itself, or an attacker will simply use this to gain access instead. Making sure you generate very long 'lost password codes' (for example, 16 case-sensitive alphanumeric characters) is a good start, but consider adding the same throttling scheme that you do for the login form itself.

PART V: Checking Password Strength

First, you'll want to read this small article for a reality check: The 500 most common passwords

Okay, so maybe the list isn't the canonical list of most common passwords on any system anywhere ever, but it's a good indication of how poorly people will choose their passwords when there is no enforced policy in place. Plus, the list looks frighteningly close to home when you compare it to publicly available analyses of recently stolen passwords.

So: With no minimum password strength requirements, 2% of users use one of the top 20 most common passwords. Meaning: if an attacker gets just 20 attempts, 1 in 50 accounts on your website will be crackable.

Thwarting this requires calculating the entropy of a password and then applying a threshold. The National Institute of Standards and Technology (NIST) Special Publication 800-63 has a set of very good suggestions. That, when combined with a dictionary and keyboard layout analysis (for example, 'qwertyuiop' is a bad password), can reject 99% of all poorly selected passwords at a level of 18 bits of entropy. Simply calculating password strength and showing a visual strength meter to a user is good, but insufficient. Unless it is enforced, a lot of users will most likely ignore it.

And for a refreshing take on user-friendliness of high-entropy passwords, Randall Munroe's Password Strength xkcd is highly recommended.

Utilize Troy Hunt's Have I Been Pwned API to check users passwords against passwords compromised in public data breaches.

PART VI: Much More - Or: Preventing Rapid-Fire Login Attempts

First, have a look at the numbers: Password Recovery Speeds - How long will your password stand up

If you don't have the time to look through the tables in that link, here's the list of them:

  1. It takes virtually no time to crack a weak password, even if you're cracking it with an abacus

  2. It takes virtually no time to crack an alphanumeric 9-character password if it is case insensitive

  3. It takes virtually no time to crack an intricate, symbols-and-letters-and-numbers, upper-and-lowercase password if it is less than 8 characters long (a desktop PC can search the entire keyspace up to 7 characters in a matter of days or even hours)

  4. It would, however, take an inordinate amount of time to crack even a 6-character password, if you were limited to one attempt per second!

So what can we learn from these numbers? Well, lots, but we can focus on the most important part: the fact that preventing large numbers of rapid-fire successive login attempts (ie. the brute force attack) really isn't that difficult. But preventing it right isn't as easy as it seems.

Generally speaking, you have three choices that are all effective against brute-force attacks (and dictionary attacks, but since you are already employing a strong passwords policy, they shouldn't be an issue):

  • Present a CAPTCHA after N failed attempts (annoying as hell and often ineffective -- but I'm repeating myself here)

  • Locking accounts and requiring email verification after N failed attempts (this is a DoS attack waiting to happen)

  • And finally, login throttling: that is, setting a time delay between attempts after N failed attempts (yes, DoS attacks are still possible, but at least they are far less likely and a lot more complicated to pull off).

Best practice #1: A short time delay that increases with the number of failed attempts, like:

  • 1 failed attempt = no delay
  • 2 failed attempts = 2 sec delay
  • 3 failed attempts = 4 sec delay
  • 4 failed attempts = 8 sec delay
  • 5 failed attempts = 16 sec delay
  • etc.

DoS attacking this scheme would be very impractical, since the resulting lockout time is slightly larger than the sum of the previous lockout times.

To clarify: The delay is not a delay before returning the response to the browser. It is more like a timeout or refractory period during which login attempts to a specific account or from a specific IP address will not be accepted or evaluated at all. That is, correct credentials will not return in a successful login, and incorrect credentials will not trigger a delay increase.

Best practice #2: A medium length time delay that goes into effect after N failed attempts, like:

  • 1-4 failed attempts = no delay
  • 5 failed attempts = 15-30 min delay

DoS attacking this scheme would be quite impractical, but certainly doable. Also, it might be relevant to note that such a long delay can be very annoying for a legitimate user. Forgetful users will dislike you.

Best practice #3: Combining the two approaches - either a fixed, short time delay that goes into effect after N failed attempts, like:

  • 1-4 failed attempts = no delay
  • 5+ failed attempts = 20 sec delay

Or, an increasing delay with a fixed upper bound, like:

  • 1 failed attempt = 5 sec delay
  • 2 failed attempts = 15 sec delay
  • 3+ failed attempts = 45 sec delay

This final scheme was taken from the OWASP best-practices suggestions (link 1 from the MUST-READ list) and should be considered best practice, even if it is admittedly on the restrictive side.

As a rule of thumb, however, I would say: the stronger your password policy is, the less you have to bug users with delays. If you require strong (case-sensitive alphanumerics + required numbers and symbols) 9+ character passwords, you could give the users 2-4 non-delayed password attempts before activating the throttling.

DoS attacking this final login throttling scheme would be very impractical. And as a final touch, always allow persistent (cookie) logins (and/or a CAPTCHA-verified login form) to pass through, so legitimate users won't even be delayed while the attack is in progress. That way, the very impractical DoS attack becomes an extremely impractical attack.

Additionally, it makes sense to do more aggressive throttling on admin accounts, since those are the most attractive entry points

PART VII: Distributed Brute Force Attacks

Just as an aside, more advanced attackers will try to circumvent login throttling by 'spreading their activities':

  • Distributing the attempts on a botnet to prevent IP address flagging

  • Rather than picking one user and trying the 50.000 most common passwords (which they can't, because of our throttling), they will pick THE most common password and try it against 50.000 users instead. That way, not only do they get around maximum-attempts measures like CAPTCHAs and login throttling, their chance of success increases as well, since the number 1 most common password is far more likely than number 49.995

  • Spacing the login requests for each user account, say, 30 seconds apart, to sneak under the radar

Here, the best practice would be logging the number of failed logins, system-wide, and using a running average of your site's bad-login frequency as the basis for an upper limit that you then impose on all users.

Too abstract? Let me rephrase:

Say your site has had an average of 120 bad logins per day over the past 3 months. Using that (running average), your system might set the global limit to 3 times that -- ie. 360 failed attempts over a 24 hour period. Then, if the total number of failed attempts across all accounts exceeds that number within one day (or even better, monitor the rate of acceleration and trigger on a calculated threshold), it activates system-wide login throttling - meaning short delays for ALL users (still, with the exception of cookie logins and/or backup CAPTCHA logins).

I also posted a question with more details and a really good discussion of how to avoid tricky pitfals in fending off distributed brute force attacks

PART VIII: Two-Factor Authentication and Authentication Providers

Credentials can be compromised, whether by exploits, passwords being written down and lost, laptops with keys being stolen, or users entering logins into phishing sites. Logins can be further protected with two-factor authentication, which uses out-of-band factors such as single-use codes received from a phone call, SMS message, app, or dongle. Several providers offer two-factor authentication services.

Authentication can be completely delegated to a single-sign-on service, where another provider handles collecting credentials. This pushes the problem to a trusted third party. Google and Twitter both provide standards-based SSO services, while Facebook provides a similar proprietary solution.

MUST-READ LINKS About Web Authentication

  1. OWASP Guide To Authentication / OWASP Authentication Cheat Sheet
  2. Dos and Don’ts of Client Authentication on the Web (very readable MIT research paper)
  3. Wikipedia: HTTP cookie
  4. Personal knowledge questions for fallback authentication: Security questions in the era of Facebook (very readable Berkeley research paper)

HTML5 best practices; section/header/aside/article elements

<body itemscope itemtype="http://schema.org/Blog">
 <header>
  <h1>Wake up sheeple!</h1>
  <p><a href="news.html">News</a> -
     <a href="blog.html">Blog</a> -
     <a href="forums.html">Forums</a></p>
  <p>Last Modified: <span itemprop="dateModified">2009-04-01</span></p>
  <nav>
   <h1>Navigation</h1>
   <ul>
    <li><a href="articles.html">Index of all articles</a></li>
    <li><a href="today.html">Things sheeple need to wake up for today</a></li>
    <li><a href="successes.html">Sheeple we have managed to wake</a></li>
   </ul>
  </nav>
 </header>
 <main>
  <article itemprop="blogPosts" itemscope itemtype="http://schema.org/BlogPosting">
   <header>
    <h1 itemprop="headline">My Day at the Beach</h1>
   </header>
   <div itemprop="articleBody">
    <p>Today I went to the beach and had a lot of fun.</p>
    ...more content...
   </div>
   <footer>
    <p>Posted <time itemprop="datePublished" datetime="2009-10-10">Thursday</time>.</p>
   </footer>
  </article>
  ...more blog posts...
 </main>
 <footer>
  <p>Copyright ©
   <span itemprop="copyrightYear">2010</span>
   <span itemprop="copyrightHolder">The Example Company</span>
  </p>
  <p><a href="about.html">About</a> -
     <a href="policy.html">Privacy Policy</a> -
     <a href="contact.html">Contact Us</a></p>
 </footer>
</body>

https://www.w3.org/TR/2014/REC-html5-20141028/sections.html#the-nav-element

PreparedStatement setNull(..)

You could also consider using preparedStatement.setObject(index,value,type);

How do I automatically update a timestamp in PostgreSQL

Updating timestamp, only if the values changed

Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)

CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
   IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
      NEW.modified = now(); 
      RETURN NEW;
   ELSE
      RETURN OLD;
   END IF;
END;
$$ language 'plpgsql';

Easier way to create circle div than using an image?

basically this uses div's position absolute to place a character at the given coordinates. so using the parametric equation for a circle, you can draw a circle. if you were to change div's position to relative, it'll result in a sine wave...

in essence we are graphing equations by abusing the position property. i'm not versed well in css, so someone can surely make this more elegant. enjoy.

this works on all browsers and mobile devices (that i'm aware of). i use it on my own website to draw sine waves of text (www.cpixel.com). the original source of this code is found here: www.mathopenref.com/coordcirclealgorithm.html

    <html>
    <head></head>
    <body>
    <script language="Javascript">

    var x_center = 50; //0 in both x_center and y_center will place the center
    var y_center = 50; // at the top left of the browser
    var resolution_step = 360; //how many times to stop along the circle to plot your character.
    var radius = 50; //how big ya want your circle?
    var plot_character = "·"; //could use any character here, try letters/words for cool effects
    var div_top_offset=10;
    var div_left_offset=10;
    var x,y;

    for ( var angle_theta = 0;  angle_theta < 2 * Math.PI;  angle_theta += 2 * Math.PI/resolution_step ){
        x = x_center + radius * Math.cos(angle_theta);
        y = y_center - radius * Math.sin(angle_theta);
        document.write("<div style='position:absolute;top:" + (y+div_top_offset) + ";left:"+ (x+div_left_offset) + "'>" + plot_character + "</div>");
    }

    </script>
    </body>
    </html>

What's the best practice to "git clone" into an existing folder?

git clone your_repo tmp && mv tmp/.git . && rm -rf tmp && git reset --mixed

Using Bootstrap Tooltip with AngularJS

I wrote a simple Angular Directive that's been working well for us.

Here's a demo: http://jsbin.com/tesido/edit?html,js,output

Directive (for Bootstrap 3):

// registers native Twitter Bootstrap 3 tooltips
app.directive('bootstrapTooltip', function() {
  return function(scope, element, attrs) {
    attrs.$observe('title',function(title){
      // Destroy any existing tooltips (otherwise new ones won't get initialized)
      element.tooltip('destroy');
      // Only initialize the tooltip if there's text (prevents empty tooltips)
      if (jQuery.trim(title)) element.tooltip();
    })
    element.on('$destroy', function() {
      element.tooltip('destroy');
      delete attrs.$$observers['title'];
    });
  }
});

Note: If you're using Bootstrap 4, on lines 6 & 11 above you'll need to replace tooltip('destroy') with tooltip('dispose') (Thanks to user1191559 for this upadate)

Simply add bootstrap-tooltip as an attribute to any element with a title. Angular will monitor for changes to the title but otherwise pass the tooltip handling over to Bootstrap.

This also allows you to use any of the native Bootstrap Tooltip Options as data- attributes in the normal Bootstrap way.

Markup:

<div bootstrap-tooltip data-placement="left" title="Tooltip on left">
        Tooltip on left
</div>

Clearly this doesn't have all the elaborate bindings & advanced integration that AngularStrap and UI Bootstrap offer, but it's a good solution if you're already using Bootstrap's JS in your Angular app and you just need a basic tooltip bridge across your entire app without modifying controllers or managing mouse events.

Parsing arguments to a Java command line program

Ok, thanks to Charles Goodwin for the concept. Here is the answer:

import java.util.*;
public class Test {

  public static void main(String[] args) {
     List<String> argsList  = new ArrayList<String>();  
     List<String> optsList  = new ArrayList<String>();
     List<String> doubleOptsList  = new ArrayList<String>();
     for (int i=0; i < args.length; i++) {
         switch (args[i].charAt(0)) {
         case '-':
             if (args[i].charAt(1) == '-') {
                 int len = 0;
                 String argstring = args[i].toString();
                 len = argstring.length();
                 System.out.println("Found double dash with command " +
                     argstring.substring(2, len) );
                 doubleOptsList.add(argstring.substring(2, len));           
             } else {
                 System.out.println("Found dash with command " + 
                   args[i].charAt(1) + " and value " + args[i+1] );   
                 i= i+1;
                 optsList.add(args[i]);      
             }           
         break;         
         default:            
         System.out.println("Add a default arg." );
         argsList.add(args[i]);
         break;         
         }     
     } 
  } 

}

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

I had a similar problem, you may find that going to the top right corner of your page in Eclipse and click "Java EE" instead of "Java" will solve your problem. I had EE installed correctly like you, and this solved the issue for me. Hope I helped :)

Replace comma with newline in sed on MacOS?

Just to clearify: man-page of sed on OSX (10.8; Darwin Kernel Version 12.4.0) says:

[...]

Sed Regular Expressions

 The regular expressions used in sed, by default, are basic regular expressions (BREs, see re_format(7) for more information), but extended
 (modern) regular expressions can be used instead if the -E flag is given.  In addition, sed has the following two additions to regular
 expressions:

 1.   In a context address, any character other than a backslash (``\'') or newline character may be used to delimit the regular expression.
      Also, putting a backslash character before the delimiting character causes the character to be treated literally.  For example, in the
      context address \xabc\xdefx, the RE delimiter is an ``x'' and the second ``x'' stands for itself, so that the regular expression is
      ``abcxdef''.

 2.   The escape sequence \n matches a newline character embedded in the pattern space.  You cannot, however, use a literal newline charac-
      ter in an address or in the substitute command.

[...]

so I guess one have to use tr - as mentioned above - or the nifty

sed "s/,/^M
/g"

note: you have to type <ctrl>-v,<return> to get '^M' in vi editor

How do I get rid of the b-prefix in a string in python?

Assuming you don't want to immediately decode it again like others are suggesting here, you can parse it to a string and then just strip the leading 'b and trailing '.

>>> x = "Hi there " 
>>> x = "Hi there ".encode("utf-8") 
>>> x
b"Hi there \xef\xbf\xbd"
>>> str(x)[2:-1]
"Hi there \\xef\\xbf\\xbd"   

How do I query between two dates using MySQL?

Your second date is before your first date (ie. you are querying between September 29 2010 and January 30 2010). Try reversing the order of the dates:

SELECT *
FROM `objects`
WHERE (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')

How to get a substring between two strings in PHP?

Got best solution for this from tonyspiro

function getBetween($content,$start,$end){
   $r = explode($start, $content);
   if (isset($r[1])){
       $r = explode($end, $r[1]);
       return $r[0];
   }
   return '';
}

array filter in python?

>>> a = set([6, 7, 8, 9, 10, 11, 12])
>>> sub_a = set([6, 9, 12])
>>> a - sub_a
set([8, 10, 11, 7])

Iterate keys in a C++ map

Here's an example of how to do it using Boost's transform_iterator

#include <iostream>
#include <map>
#include <iterator>
#include "boost/iterator/transform_iterator.hpp"

using std::map;
typedef std::string Key;
typedef std::string Val;

map<Key,Val>::key_type get_key(map<Key,Val>::value_type aPair) {
  return aPair.first;
}

typedef map<Key,Val>::key_type (*get_key_t)(map<Key,Val>::value_type);
typedef map<Key,Val>::iterator map_iterator;
typedef boost::transform_iterator<get_key_t, map_iterator> mapkey_iterator;

int main() {
  map<Key,Val> m;
  m["a"]="A";
  m["b"]="B";
  m["c"]="C";

  // iterate over the map's (key,val) pairs as usual
  for(map_iterator i = m.begin(); i != m.end(); i++) {
    std::cout << i->first << " " << i->second << std::endl;
  }

  // iterate over the keys using the transformed iterators
  mapkey_iterator keybegin(m.begin(), get_key);
  mapkey_iterator keyend(m.end(), get_key);
  for(mapkey_iterator i = keybegin; i != keyend; i++) {
    std::cout << *i << std::endl;
  }
}

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

There are two reasons for this error

1) In the array of import if you imported HttpModule twice

enter image description here

2) If you haven't import:

import { HttpModule, JsonpModule } from '@angular/http'; 

If you want then run:

npm install @angular/http

How to show x and y axes in a MATLAB graph?

I know this is coming a bit late, but a colleague of mine figured something out:

figure, plot ((1:10),cos(rand(1,10))-0.75,'*-')
hold on
plot ((1:10),zeros(1,10),'k+-')
text([1:10]-0.09,ones(1,10).*-0.015,[{'0' '1'  '2' '3' '4' '5' '6' '7' '8' '9'}])
set(gca,'XTick',[], 'XColor',[1 1 1])
box off

Getting last day of the month in a given string date

By using java 8 java.time.LocalDate

String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/dd/yyyy"))
       .with(TemporalAdjusters.lastDayOfMonth());

MySQL's now() +1 day

better use quoted `data` and `date`. AFAIR these may be reserved words my version is:

INSERT INTO `table` ( `data` , `date` ) VALUES('".$date."',NOW()+INTERVAL 1 DAY);

How can I convert a string to a number in Perl?

As I understand it int() is not intended as a 'cast' function for designating data type it's simply being (ab)used here to define the context as an arithmetic one. I've (ab)used (0+$val) in the past to ensure that $val is treated as a number.

Converting a date string to a DateTime object using Joda Time library

From comments I picked an answer like and also adding TimeZone:

String dateTime = "2015-07-18T13:32:56.971-0400";

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
        .withLocale(Locale.ROOT)
        .withChronology(ISOChronology.getInstanceUTC());

DateTime dt = formatter.parseDateTime(dateTime);

How do I override nested NPM dependency versions?

For those from 2018 and beyond, using npm version 5 or later: edit your package-lock.json: remove the library from "requires" section and add it under "dependencies".

For example, you want deglob package to use glob package version 3.2.11 instead of its current one. You open package-lock.json and see:

"deglob": {
  "version": "2.1.0",
  "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
  "integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
  "requires": {
    "find-root": "1.1.0",
    "glob": "7.1.2",
    "ignore": "3.3.5",
    "pkg-config": "1.1.1",
    "run-parallel": "1.1.6",
    "uniq": "1.0.1"
  }
},

Remove "glob": "7.1.2", from "requires", add "dependencies" with proper version:

"deglob": {
  "version": "2.1.0",
  "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
  "integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
  "requires": {
    "find-root": "1.1.0",
    "ignore": "3.3.5",
    "pkg-config": "1.1.1",
    "run-parallel": "1.1.6",
    "uniq": "1.0.1"
  },
  "dependencies": {
    "glob": {
      "version": "3.2.11"
    }
  }
},

Now remove your node_modules folder, run npm install and it will add missing parts to the "dependencies" section.

Using GCC to produce readable assembly?

Use the -S (note: capital S) switch to GCC, and it will emit the assembly code to a file with a .s extension. For example, the following command:

gcc -O2 -S foo.c

will leave the generated assembly code on the file foo.s.

Ripped straight from http://www.delorie.com/djgpp/v2faq/faq8_20.html (but removing erroneous -c)

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

I came across this error while making a segue from a table view controller to a view controller because I had forgotten to specify the custom class name for the view controller in the main storyboard.

Something simple that is worth checking if all else looks ok

.NET console application as Windows service

I've had great success with TopShelf.

TopShelf is a Nuget package designed to make it easy to create .NET Windows apps that can run as console apps or as Windows Services. You can quickly hook up events such as your service Start and Stop events, configure using code e.g. to set the account it runs as, configure dependencies on other services, and configure how it recovers from errors.

From the Package Manager Console (Nuget):

Install-Package Topshelf

Refer to the code samples to get started.

Example:

HostFactory.Run(x =>                                 
{
    x.Service<TownCrier>(s =>                        
    {
       s.ConstructUsing(name=> new TownCrier());     
       s.WhenStarted(tc => tc.Start());              
       s.WhenStopped(tc => tc.Stop());               
    });
    x.RunAsLocalSystem();                            

    x.SetDescription("Sample Topshelf Host");        
    x.SetDisplayName("Stuff");                       
    x.SetServiceName("stuff");                       
}); 

TopShelf also takes care of service installation, which can save a lot of time and removes boilerplate code from your solution. To install your .exe as a service you just execute the following from the command prompt:

myservice.exe install -servicename "MyService" -displayname "My Service" -description "This is my service."

You don't need to hook up a ServiceInstaller and all that - TopShelf does it all for you.

Split a List into smaller lists of N size

Addition after very useful comment of mhand at the end

Original answer

Although most solutions might work, I think they are not very efficiently. Suppose if you only want the first few items of the first few chunks. Then you wouldn't want to iterate over all (zillion) items in your sequence.

The following will at utmost enumerate twice: once for the Take and once for the Skip. It won't enumerate over any more elements than you will use:

public static IEnumerable<IEnumerable<TSource>> ChunkBy<TSource>
    (this IEnumerable<TSource> source, int chunkSize)
{
    while (source.Any())                     // while there are elements left
    {   // still something to chunk:
        yield return source.Take(chunkSize); // return a chunk of chunkSize
        source = source.Skip(chunkSize);     // skip the returned chunk
    }
}

How many times will this Enumerate the sequence?

Suppose you divide your source into chunks of chunkSize. You enumerate only the first N chunks. From every enumerated chunk you'll only enumerate the first M elements.

While(source.Any())
{
     ...
}

the Any will get the Enumerator, do 1 MoveNext() and returns the returned value after Disposing the Enumerator. This will be done N times

yield return source.Take(chunkSize);

According to the reference source this will do something like:

public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count)
{
    return TakeIterator<TSource>(source, count);
}

static IEnumerable<TSource> TakeIterator<TSource>(IEnumerable<TSource> source, int count)
{
    foreach (TSource element in source)
    {
        yield return element;
        if (--count == 0) break;
    }
}

This doesn't do a lot until you start enumerating over the fetched Chunk. If you fetch several Chunks, but decide not to enumerate over the first Chunk, the foreach is not executed, as your debugger will show you.

If you decide to take the first M elements of the first chunk then the yield return is executed exactly M times. This means:

  • get the enumerator
  • call MoveNext() and Current M times.
  • Dispose the enumerator

After the first chunk has been yield returned, we skip this first Chunk:

source = source.Skip(chunkSize);

Once again: we'll take a look at reference source to find the skipiterator

static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count)
{
    using (IEnumerator<TSource> e = source.GetEnumerator()) 
    {
        while (count > 0 && e.MoveNext()) count--;
        if (count <= 0) 
        {
            while (e.MoveNext()) yield return e.Current;
        }
    }
}

As you see, the SkipIterator calls MoveNext() once for every element in the Chunk. It doesn't call Current.

So per Chunk we see that the following is done:

  • Any(): GetEnumerator; 1 MoveNext(); Dispose Enumerator;
  • Take():

    • nothing if the content of the chunk is not enumerated.
    • If the content is enumerated: GetEnumerator(), one MoveNext and one Current per enumerated item, Dispose enumerator;

    • Skip(): for every chunk that is enumerated (NOT the contents of the chunk): GetEnumerator(), MoveNext() chunkSize times, no Current! Dispose enumerator

If you look at what happens with the enumerator, you'll see that there are a lot of calls to MoveNext(), and only calls to Current for the TSource items you actually decide to access.

If you take N Chunks of size chunkSize, then calls to MoveNext()

  • N times for Any()
  • not yet any time for Take, as long as you don't enumerate the Chunks
  • N times chunkSize for Skip()

If you decide to enumerate only the first M elements of every fetched chunk, then you need to call MoveNext M times per enumerated Chunk.

The total

MoveNext calls: N + N*M + N*chunkSize
Current calls: N*M; (only the items you really access)

So if you decide to enumerate all elements of all chunks:

MoveNext: numberOfChunks + all elements + all elements = about twice the sequence
Current: every item is accessed exactly once

Whether MoveNext is a lot of work or not, depends on the type of source sequence. For lists and arrays it is a simple index increment, with maybe an out of range check.

But if your IEnumerable is the result of a database query, make sure that the data is really materialized on your computer, otherwise the data will be fetched several times. DbContext and Dapper will properly transfer the data to local process before it can be accessed. If you enumerate the same sequence several times it is not fetched several times. Dapper returns an object that is a List, DbContext remembers that the data is already fetched.

It depends on your Repository whether it is wise to call AsEnumerable() or ToLists() before you start to divide the items in Chunks

How to check whether a Button is clicked by using JavaScript

Try adding an event listener for clicks:

document.getElementById('button').addEventListener("click", function() {
   alert("You clicked me");
}?);?

Using addEventListener is probably a better idea then setting onclick - onclick can easily be overwritten by another piece of code.

You can use a variable to store whether or not the button has been clicked before:

var clicked = false
document.getElementById('button').addEventListener("click", function() {
   clicked = true
}?);?

addEventListener on MDN

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

I had installed Python 32 bit version and psycopg2 64 bit version to get this problem. I installed psycopg2 32 bit version and then it worked.

Reordering arrays

You could always use the sort method, if you don't know where the record is at present:

playlist.sort(function (a, b) {
    return a.artist == "Lalo Schifrin" 
               ? 1    // Move it down the list
               : 0;   // Keep it the same
});

ng is not recognized as an internal or external command

Set path=%path%;C:\Users\\AppData\Roaming\npm

Where are the Properties.Settings.Default stored?

In order to work with newer versions of Windows' policy of only allowing read access by default to the Program Files folder (unless you prompt for elevation with UAC, but that's another topic...), your application will have a settings folder under %userprofile%\appdata\local or %userprofile%\Local Settings\Application Data depending on which version of Windows you're running, for settings that are user specific. If you store settings for all users, then they'll be in the corresponding folder under C:\users or C:\Documents and Settings for all user profiles (ex: C:\users\public\appdata\local).

Fast Linux file count for a large number of files

find, ls, and perl tested against 40,000 files has the same speed (though I didn't try to clear the cache):

[user@server logs]$ time find . | wc -l
42917

real    0m0.054s
user    0m0.018s
sys     0m0.040s

[user@server logs]$ time /bin/ls -f | wc -l
42918

real    0m0.059s
user    0m0.027s
sys     0m0.037s

And with Perl's opendir and readdir, the same time:

[user@server logs]$ time perl -e 'opendir D, "."; @files = readdir D; closedir D; print scalar(@files)."\n"'
42918

real    0m0.057s
user    0m0.024s
sys     0m0.033s

Note: I used /bin/ls -f to make sure to bypass the alias option which might slow a little bit and -f to avoid file ordering. ls without -f is twice slower than find/perl except if ls is used with -f, it seems to be the same time:

[user@server logs]$ time /bin/ls . | wc -l
42916

real    0m0.109s
user    0m0.070s
sys     0m0.044s

I also would like to have some script to ask the file system directly without all the unnecessary information.

The tests were based on the answers of Peter van der Heijden, glenn jackman, and mark4o.

How to compile .c file with OpenSSL includes?

For this gcc error, you should reference to to the gcc document about Search Path.

In short:

1) If you use angle brackets(<>) with #include, gcc will search header file firstly from system path such as /usr/local/include and /usr/include, etc.

2) The path specified by -Ldir command-line option, will be searched before the default directories.

3)If you use quotation("") with #include as #include "file", the directory containing the current file will be searched firstly.

so, the answer to your question is as following:

1) If you want to use header files in your source code folder, replace <> with "" in #include directive.

2) if you want to use -I command line option, add it to your compile command line.(if set CFLAGS in environment variables, It will not referenced automatically)

3) About package configuration(openssl.pc), I do not think it will be referenced without explicitly declared in build configuration.

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

Use a LIKE statement on SQL Server XML Datatype

You should be able to do this quite easily:

SELECT * 
FROM WebPageContent 
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'

The .value method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.

Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:

  • create a stored function which gets the XML and returns the value you're looking for as a VARCHAR()
  • define a new computed field on your table which calls this function, and make it a PERSISTED column

With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).

Marc

How to remove non UTF-8 characters from text file

Your method must read byte by byte and fully understand and appreciate the byte wise construction of characters. The simplest method is to use an editor which will read anything but only output UTF-8 characters. Textpad is one choice.

Can't bind to 'ngIf' since it isn't a known property of 'div'

If you are using RC5 then import this:

import { CommonModule } from '@angular/common';  
import { BrowserModule } from '@angular/platform-browser';

and be sure to import CommonModule from the module that is providing your component.

 @NgModule({
    imports: [CommonModule],
    declarations: [MyComponent]
  ...
})
class MyComponentModule {}

How to change resolution (DPI) of an image?

DPI should not be stored in an bitmap image file, as most sources of data for bitmaps render it meaningless.

A bitmap image is stored as pixels. Pixels have no inherent size in any respect. It's only at render time - be it monitor, printer, or automated crossstitching machine - that DPI matters.

A 800x1000 pixel bitmap image, printed at 100 dpi, turns into a nice 8x10" photo. Printed at 200 dpi, the EXACT SAME bitmap image turns into a 4x5" photo.

Capture an image with a digital camera, and what does DPI mean? It's certainly not the size of the area focused onto the CCD imager - that depends on the distance, and with NASA returning images of galaxies that are 100,000 light years across, and 2 million light years apart, in the same field of view, what kind of DPI do you get from THAT information?

Don't fall victim to the idea of the DPI of a bitmap image - it's a mistake. A bitmap image has no physical dimensions (save for a few micrometers of storage space in RAM or hard drive). It's only a displayed image, or a printed image, that has a physical size in inches, or millimeters, or furlongs.

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

cursor.execute(sql,array)

Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)

How to compute the similarity between two text documents?

I am combining the solutions from answers of @FredFoo and @Renaud. My solution is able to apply @Renaud's preprocessing on the text corpus of @FredFoo and then display pairwise similarities where the similarity is greater than 0. I ran this code on Windows by installing python and pip first. pip is installed as part of python but you may have to explicitly do it by re-running the installation package, choosing modify and then choosing pip. I use the command line to execute my python code saved in a file "similarity.py". I had to execute the following commands:

>set PYTHONPATH=%PYTHONPATH%;C:\_location_of_python_lib_
>python -m pip install sklearn
>python -m pip install nltk
>py similarity.py

The code for similarity.py is as follows:

from sklearn.feature_extraction.text import TfidfVectorizer
import nltk, string
import numpy as np
nltk.download('punkt') # if necessary...

stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)

def stem_tokens(tokens):
    return [stemmer.stem(item) for item in tokens]

def normalize(text):
    return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))

corpus = ["I'd like an apple", 
           "An apple a day keeps the doctor away", 
           "Never compare an apple to an orange", 
           "I prefer scikit-learn to Orange", 
           "The scikit-learn docs are Orange and Blue"]  

vect = TfidfVectorizer(tokenizer=normalize, stop_words='english')
tfidf = vect.fit_transform(corpus)   
                                                                                                                                                                                                                    
pairwise_similarity = tfidf * tfidf.T

#view the pairwise similarities 
print(pairwise_similarity)

#check how a string is normalized
print(normalize("The scikit-learn docs are Orange and Blue"))

How to search for an element in a golang slice

There is no library function for that. You have to code by your own.

for _, value := range myconfig {
    if value.Key == "key1" {
        // logic
    }
}

Working code: https://play.golang.org/p/IJIhYWROP_

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    type Config struct {
        Key   string
        Value string
    }

    var respbody = []byte(`[
        {"Key":"Key1", "Value":"Value1"},
        {"Key":"Key2", "Value":"Value2"}
    ]`)

    var myconfig []Config

    err := json.Unmarshal(respbody, &myconfig)
    if err != nil {
        fmt.Println("error:", err)
    }

    fmt.Printf("%+v\n", myconfig)

    for _, v := range myconfig {
        if v.Key == "Key1" {
            fmt.Println("Value: ", v.Value)
        }
    }

}

Open fancybox from function

The answers seems a bit over complicated. I hope I didn't misunderstand the question.

If you simply want to open a fancy box from a click to an "A" tag. Just set your html to

<a id="my_fancybox" href="#contentdiv">click me</a>

The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:

$('#my_fancybox').fancybox({
    'autoScale': true,
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'speedIn': 500,
    'speedOut': 300,
    'autoDimensions': true,
    'centerOnScroll': true,
});

This will show a fancybox containing "contentdiv" when your anchor tag is clicked.

Finding the average of a list

In order to use reduce for taking a running average, you'll need to track the total but also the total number of elements seen so far. since that's not a trivial element in the list, you'll also have to pass reduce an extra argument to fold into.

>>> l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
>>> running_average = reduce(lambda aggr, elem: (aggr[0] + elem, aggr[1]+1), l, (0.0,0))
>>> running_average[0]
(181.0, 9)
>>> running_average[0]/running_average[1]
20.111111111111111

Getting a list of all subdirectories in the current directory

This below class would be able to get list of files, folder and all sub folder inside a given directory

import os
import json

class GetDirectoryList():
    def __init__(self, path):
        self.main_path = path
        self.absolute_path = []
        self.relative_path = []


    def get_files_and_folders(self, resp, path):
        all = os.listdir(path)
        resp["files"] = []
        for file_folder in all:
            if file_folder != "." and file_folder != "..":
                if os.path.isdir(path + "/" + file_folder):
                    resp[file_folder] = {}
                    self.get_files_and_folders(resp=resp[file_folder], path= path + "/" + file_folder)
                else:
                    resp["files"].append(file_folder)
                    self.absolute_path.append(path.replace(self.main_path + "/", "") + "/" + file_folder)
                    self.relative_path.append(path + "/" + file_folder)
        return resp, self.relative_path, self.absolute_path

    @property
    def get_all_files_folder(self):
        self.resp = {self.main_path: {}}
        all = self.get_files_and_folders(self.resp[self.main_path], self.main_path)
        return all

if __name__ == '__main__':
    mylib = GetDirectoryList(path="sample_folder")
    file_list = mylib.get_all_files_folder
    print (json.dumps(file_list))

Whereas Sample Directory looks like

sample_folder/
    lib_a/
        lib_c/
            lib_e/
                __init__.py
                a.txt
            __init__.py
            b.txt
            c.txt
        lib_d/
            __init__.py
        __init__.py
        d.txt
    lib_b/
        __init__.py
        e.txt
    __init__.py

Result Obtained

[
  {
    "files": [
      "__init__.py"
    ],
    "lib_b": {
      "files": [
        "__init__.py",
        "e.txt"
      ]
    },
    "lib_a": {
      "files": [
        "__init__.py",
        "d.txt"
      ],
      "lib_c": {
        "files": [
          "__init__.py",
          "c.txt",
          "b.txt"
        ],
        "lib_e": {
          "files": [
            "__init__.py",
            "a.txt"
          ]
        }
      },
      "lib_d": {
        "files": [
          "__init__.py"
        ]
      }
    }
  },
  [
    "sample_folder/lib_b/__init__.py",
    "sample_folder/lib_b/e.txt",
    "sample_folder/__init__.py",
    "sample_folder/lib_a/lib_c/lib_e/__init__.py",
    "sample_folder/lib_a/lib_c/lib_e/a.txt",
    "sample_folder/lib_a/lib_c/__init__.py",
    "sample_folder/lib_a/lib_c/c.txt",
    "sample_folder/lib_a/lib_c/b.txt",
    "sample_folder/lib_a/lib_d/__init__.py",
    "sample_folder/lib_a/__init__.py",
    "sample_folder/lib_a/d.txt"
  ],
  [
    "lib_b/__init__.py",
    "lib_b/e.txt",
    "sample_folder/__init__.py",
    "lib_a/lib_c/lib_e/__init__.py",
    "lib_a/lib_c/lib_e/a.txt",
    "lib_a/lib_c/__init__.py",
    "lib_a/lib_c/c.txt",
    "lib_a/lib_c/b.txt",
    "lib_a/lib_d/__init__.py",
    "lib_a/__init__.py",
    "lib_a/d.txt"
  ]
]

How to fix broken paste clipboard in VNC on Windows

You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.

What's the source of Error: getaddrinfo EAI_AGAIN?

Enabled Blaze and it still doesn't work?

Most probably you need to set .env from the right path, require('dotenv').config({ path: __dirname + './../.env' }); won't work (or any other path). Simply put the .env file in the functions directory, from which you deploy to Firebase.

How to pass an object into a state using UI-router?

No, the URL will always be updated when params are passed to transitionTo.

This happens on state.js:698 in ui-router.

Concatenating variables and strings in React

you can simply do this..

 <img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>

How to _really_ programmatically change primary and accent color in Android Lollipop?

You can use Theme.applyStyle to modify your theme at runtime by applying another style to it.

Let's say you have these style definitions:

<style name="DefaultTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/md_lime_500</item>
    <item name="colorPrimaryDark">@color/md_lime_700</item>
    <item name="colorAccent">@color/md_amber_A400</item>
</style>

<style name="OverlayPrimaryColorRed">
    <item name="colorPrimary">@color/md_red_500</item>
    <item name="colorPrimaryDark">@color/md_red_700</item>
</style>

<style name="OverlayPrimaryColorGreen">
    <item name="colorPrimary">@color/md_green_500</item>
    <item name="colorPrimaryDark">@color/md_green_700</item>
</style>

<style name="OverlayPrimaryColorBlue">
    <item name="colorPrimary">@color/md_blue_500</item>
    <item name="colorPrimaryDark">@color/md_blue_700</item>
</style>

Now you can patch your theme at runtime like so:

getTheme().applyStyle(R.style.OverlayPrimaryColorGreen, true);

The method applyStylehas to be called before the layout gets inflated! So unless you load the view manually you should apply styles to the theme before calling setContentView in your activity.

Of course this cannot be used to specify an arbitrary color, i.e. one out of 16 million (2563) colors. But if you write a small program that generates the style definitions and the Java code for you then something like one out of 512 (83) should be possible.

What makes this interesting is that you can use different style overlays for different aspects of your theme. Just add a few overlay definitions for colorAccent for example. Now you can combine different values for primary color and accent color almost arbitrarily.

You should make sure that your overlay theme definitions don't accidentally inherit a bunch of style definitions from a parent style definition. For example a style called AppTheme.OverlayRed implicitly inherits all styles defined in AppTheme and all these definitions will also be applied when you patch the master theme. So either avoid dots in the overlay theme names or use something like Overlay.Red and define Overlay as an empty style.

MySQL SELECT only not null values

SELECT * FROM TABLE_NAME
where COLUMN_NAME <> '';

IIS7 folder permissions for web application

  1. Working on IIS 7.5 and Windows 7 i couldnt give permission APPPOOL/Mypool
  2. IUSR and IIS_IUSRS permissions not working for me
  3. I got to problem this way:

    -Created console application with C#
    -This appliaction using createeventsource like this

    if(!System.Diagnostics.EventLog.SourceExists(sourceName)) System.Diagnostics.EventLog.CreateEventSource(sourceName,logName);

    -Build solution and get .exe file

    -Run exe as administator.This create log file.

NOTE: Dont remember Event viewer must be refresh for see the log.

I hope this solution helps someone :)

jQuery DataTables Getting selected row values

You can iterate over the row data

$('#button').click(function () {
    var ids = $.map(table.rows('.selected').data(), function (item) {
        return item[0]
    });
    console.log(ids)
    alert(table.rows('.selected').data().length + ' row(s) selected');
});

Demo: Fiddle

How do I check in python if an element of a list is empty?

Unlike in some laguages, empty is not a keyword in Python. Python lists are constructed form the ground up, so if element i has a value, then element i-1 has a value, for all i > 0.

To do an equality check, you usually use either the == comparison operator.

>>> my_list = ["asdf", 0, 42, '', None, True, "LOLOL"]
>>> my_list[0] == "asdf"
True
>>> my_list[4] is None
True
>>> my_list[2] == "the universe"
False
>>> my_list[3]
""
>>> my_list[3] == ""
True

Here's a link to the strip method: your comment indicates to me that you may have some strange file parsing error going on, so make sure you're stripping off newlines and extraneous whitespace before you expect an empty line.

How to prevent IFRAME from redirecting top-level window

I know it has been a long time since question was done but here is my improved version it will wait 500ms for any subsequent call only when the iframe is loaded.

<script type="text/javasript">
var prevent_bust = false ;
    var from_loading_204 = false;
    var frame_loading = false;
    var prevent_bust_timer = 0;
    var  primer = true;
    window.onbeforeunload = function(event) {
        prevent_bust = !from_loading_204 && frame_loading;
        if(from_loading_204)from_loading_204 = false;
        if(prevent_bust){
            prevent_bust_timer=500;
        }
    }
    function frameLoad(){
        if(!primer){
            from_loading_204 = true;
            window.top.location = '/?204';
            prevent_bust = false;
            frame_loading = true;
            prevent_bust_timer=1000;
        }else{
            primer = false;
        }
    }
    setInterval(function() {  
        if (prevent_bust_timer>0) {  
            if(prevent_bust){
                from_loading_204 = true;
                window.top.location = '/?204';
                prevent_bust = false;
            }else if(prevent_bust_timer == 1){
                frame_loading = false;
                prevent_bust = false;
                from_loading_204 = false;
                prevent_bust_timer == 0;
            }



        }
        prevent_bust_timer--;
        if(prevent_bust_timer==-100) {
            prevent_bust_timer = 0;
        }
    }, 1);
</script>

and onload="frameLoad()" and onreadystatechange="frameLoad();" must be added to the frame or iframe.

Are there inline functions in java?

so, it seems there arent, but you can use this workaround using guava or an equivalent Function class implementation, because that class is extremely simple, ex.:

    assert false : new com.google.common.base.Function<Void,String>(){
        @Override public String apply(Void input) {
            //your complex code go here
            return "weird message";
        }}.apply(null);

yes, this is dead code just to exemplify how to create a complex code block (within {}) to do something so specific that shouldnt bother us on creating any method for it, AKA inline!

Bootstrap Dropdown with Hover

html

        <div class="dropdown">

            <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
                Dropdown Example <span class="caret"></span>
            </button>

            <ul class="dropdown-menu">
                <li><a href="#">HTML</a></li>
                <li><a href="#">CSS</a></li>
                <li><a href="#">JavaScript</a></li>
            </ul>

        </div> 

jquery

        $(document).ready( function() {                

            /* $(selector).hover( inFunction, outFunction ) */
            $('.dropdown').hover( 
                function() {                        
                    $(this).find('ul').css({
                        "display": "block",
                        "margin-top": 0
                    });                        
                }, 
                function() {                        
                    $(this).find('ul').css({
                        "display": "none",
                        "margin-top": 0
                    });                        
                } 
            );

        });

codepen

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

I had the similar issue. It happened every time when I run a pack of database (Spring JDBC) tests with SpringJUnit4ClassRunner, so I resolved the issue putting @DirtiesContext annotation for each test in order to cleanup the application context and release all resources thus each test could run with a new initalization of the application context.

C# switch on type

Update: This got fixed in C# 7.0 with pattern matching

switch (MyObj)
    case Type1 t1: 
    case Type2 t2:
    case Type3 t3:

Old answer:

It is a hole in C#'s game, no silver bullet yet.

You should google on the 'visitor pattern' but it might be a little heavy for you but still something you should know about.

Here's another take on the matter using Linq: http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx

Otherwise something along these lines could help

// nasty..
switch(MyObj.GetType.ToString()){
  case "Type1": etc
}

// clumsy...
if myObj  is Type1 then
if myObj is Type2 then

etc.

HTML forms - input type submit problem with action=URL when URL contains index.aspx

Put the query arguments in hidden input fields:

<form action="http://spufalcons.com/index.aspx">
    <input type="hidden" name="tab" value="gymnastics" />
    <input type="hidden" name="path" value="gym" />
    <input type="submit" value="SPU Gymnastics"/>
</form>

Using find command in bash script

You can use this:

list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')

Besides, you might want to use -iname instead of -name to catch files with ".PDF" (upper-case) extension as well.

Django -- Template tag in {% if %} block

You shouldn't use the double-bracket {{ }} syntax within if or ifequal statements, you can simply access the variable there like you would in normal python:

{% if title == source %}
   ...
{% endif %}

How to validate Google reCAPTCHA v3 on server side?

To verify at server side using PHP. Two most important thing you need to consider.

1. $_POST['g-recaptcha-response']

2.$secretKey = '6LeycSQTAAAAAMM3AeG62pBslQZwBTwCbzeKt06V';

$verifydata = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
        $response= json_decode($verifydata);

If you get $verifydata true, You done.
For more check out this
Google reCaptcha Using PHP | Only 2 Step Integration

No == operator found while comparing structs in C++

C++20 introduced default comparisons, aka the "spaceship" operator<=>, which allows you to request compiler-generated </<=/==/!=/>=/ and/or > operators with the obvious/naive(?) implementation...

auto operator<=>(const MyClass&) const = default;

...but you can customise that for more complicated situations (discussed below). See here for the language proposal, which contains justifications and discussion. This answer remains relevant for C++17 and earlier, and for insight in to when you should customise the implementation of operator<=>....

It may seem a bit unhelpful of C++ not to have already Standardised this earlier, but often structs/classes have some data members to exclude from comparison (e.g. counters, cached results, container capacity, last operation success/error code, cursors), as well as decisions to make about myriad things including but not limited to:

  • which fields to compare first, e.g. comparing a particular int member might eliminate 99% of unequal objects very quickly, while a map<string,string> member might often have identical entries and be relatively expensive to compare - if the values are loaded at runtime, the programmer may have insights the compiler can't possibly
  • in comparing strings: case sensitivity, equivalence of whitespace and separators, escaping conventions...
  • precision when comparing floats/doubles
  • whether NaN floating point values should be considered equal
  • comparing pointers or pointed-to-data (and if the latter, how to know how whether the pointers are to arrays and of how many objects/bytes needing comparison)
  • whether order matters when comparing unsorted containers (e.g. vector, list), and if so whether it's ok to sort them in-place before comparing vs. using extra memory to sort temporaries each time a comparison is done
  • how many array elements currently hold valid values that should be compared (is there a size somewhere or a sentinel?)
  • which member of a union to compare
  • normalisation: for example, date types may allow out-of-range day-of-month or month-of-year, or a rational/fraction object may have 6/8ths while another has 3/4ers, which for performance reasons they correct lazily with a separate normalisation step; you may have to decide whether to trigger a normalisation before comparison
  • what to do when weak pointers aren't valid
  • how to handle members and bases that don't implement operator== themselves (but might have compare() or operator< or str() or getters...)
  • what locks must be taken while reading/comparing data that other threads may want to update

So, it's kind of nice to have an error until you've explicitly thought about what comparison should mean for your specific structure, rather than letting it compile but not give you a meaningful result at run-time.

All that said, it'd be good if C++ let you say bool operator==() const = default; when you'd decided a "naive" member-by-member == test was ok. Same for !=. Given multiple members/bases, "default" <, <=, >, and >= implementations seem hopeless though - cascading on the basis of order of declaration's possible but very unlikely to be what's wanted, given conflicting imperatives for member ordering (bases being necessarily before members, grouping by accessibility, construction/destruction before dependent use). To be more widely useful, C++ would need a new data member/base annotation system to guide choices - that would be a great thing to have in the Standard though, ideally coupled with AST-based user-defined code generation... I expect it'll happen one day.

Typical implementation of equality operators

A plausible implementation

It's likely that a reasonable and efficient implementation would be:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return lhs.my_struct2 == rhs.my_struct2 &&
           lhs.an_int     == rhs.an_int;
}

Note that this needs an operator== for MyStruct2 too.

Implications of this implementation, and alternatives, are discussed under the heading Discussion of specifics of your MyStruct1 below.

A consistent approach to ==, <, > <= etc

It's easy to leverage std::tuple's comparison operators to compare your own class instances - just use std::tie to create tuples of references to fields in the desired order of comparison. Generalising my example from here:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return std::tie(lhs.my_struct2, lhs.an_int) ==
           std::tie(rhs.my_struct2, rhs.an_int);
}

inline bool operator<(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return std::tie(lhs.my_struct2, lhs.an_int) <
           std::tie(rhs.my_struct2, rhs.an_int);
}

// ...etc...

When you "own" (i.e. can edit, a factor with corporate and 3rd party libs) the class you want to compare, and especially with C++14's preparedness to deduce function return type from the return statement, it's often nicer to add a "tie" member function to the class you want to be able to compare:

auto tie() const { return std::tie(my_struct1, an_int); }

Then the comparisons above simplify to:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return lhs.tie() == rhs.tie();
}

If you want a fuller set of comparison operators, I suggest boost operators (search for less_than_comparable). If it's unsuitable for some reason, you may or may not like the idea of support macros (online):

#define TIED_OP(STRUCT, OP, GET_FIELDS) \
    inline bool operator OP(const STRUCT& lhs, const STRUCT& rhs) \
    { \
        return std::tie(GET_FIELDS(lhs)) OP std::tie(GET_FIELDS(rhs)); \
    }

#define TIED_COMPARISONS(STRUCT, GET_FIELDS) \
    TIED_OP(STRUCT, ==, GET_FIELDS) \
    TIED_OP(STRUCT, !=, GET_FIELDS) \
    TIED_OP(STRUCT, <, GET_FIELDS) \
    TIED_OP(STRUCT, <=, GET_FIELDS) \
    TIED_OP(STRUCT, >=, GET_FIELDS) \
    TIED_OP(STRUCT, >, GET_FIELDS)

...that can then be used a la...

#define MY_STRUCT_FIELDS(X) X.my_struct2, X.an_int
TIED_COMPARISONS(MyStruct1, MY_STRUCT_FIELDS)

(C++14 member-tie version here)

Discussion of specifics of your MyStruct1

There are implications to the choice to provide a free-standing versus member operator==()...

Freestanding implementation

You have an interesting decision to make. As your class can be implicitly constructed from a MyStruct2, a free-standing / non-member bool operator==(const MyStruct2& lhs, const MyStruct2& rhs) function would support...

my_MyStruct2 == my_MyStruct1

...by first creating a temporary MyStruct1 from my_myStruct2, then doing the comparison. This would definitely leave MyStruct1::an_int set to the constructor's default parameter value of -1. Depending on whether you include an_int comparison in the implementation of your operator==, a MyStruct1 might or might not compare equal to a MyStruct2 that itself compares equal to the MyStruct1's my_struct_2 member! Further, creating a temporary MyStruct1 can be a very inefficient operation, as it involves copying the existing my_struct2 member to a temporary, only to throw it away after the comparison. (Of course, you could prevent this implicit construction of MyStruct1s for comparison by making that constructor explicit or removing the default value for an_int.)

Member implementation

If you want to avoid implicit construction of a MyStruct1 from a MyStruct2, make the comparison operator a member function:

struct MyStruct1
{
    ...
    bool operator==(const MyStruct1& rhs) const
    {
        return tie() == rhs.tie(); // or another approach as above
    }
};

Note the const keyword - only needed for the member implementation - advises the compiler that comparing objects doesn't modify them, so can be allowed on const objects.

Comparing the visible representations

Sometimes the easiest way to get the kind of comparison you want can be...

    return lhs.to_string() == rhs.to_string();

...which is often very expensive too - those strings painfully created just to be thrown away! For types with floating point values, comparing visible representations means the number of displayed digits determines the tolerance within which nearly-equal values are treated as equal during comparison.

Skip download if files exist in wget?

When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

So adding -nc will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.

See more info at GNU.

Best practices to test protected methods with PHPUnit

You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a private one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:

class Foo {
  protected function stuff() {
    // secret stuff, you want to test
  }
}

class SubFoo extends Foo {
  public function exposedStuff() {
    return $this->stuff();
  }
}

Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.

How to run JUnit tests with Gradle?

If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:

sourceSets {
    test {
        java.srcDirs += [
                'src/customDir/test/kotlin'
        ]
        print(java.srcDirs)   // Clean
    }
}

Pay attention to the operator += and if you want to run integration tests change test to androidTest.

GL

C++ Array of pointers: delete or delete []?

Your second example is correct; you don't need to delete the monsters array itself, just the individual objects you created.

Getters \ setters for dummies

If you're referring to the concept of accessors, then the simple goal is to hide the underlying storage from arbitrary manipulation. The most extreme mechanism for this is

function Foo(someValue) {
    this.getValue = function() { return someValue; }
    return this;
}

var myFoo = new Foo(5);
/* We can read someValue through getValue(), but there is no mechanism
 * to modify it -- hurrah, we have achieved encapsulation!
 */
myFoo.getValue();

If you're referring to the actual JS getter/setter feature, eg. defineGetter/defineSetter, or { get Foo() { /* code */ } }, then it's worth noting that in most modern engines subsequent usage of those properties will be much much slower than it would otherwise be. eg. compare performance of

var a = { getValue: function(){ return 5; }; }
for (var i = 0; i < 100000; i++)
    a.getValue();

vs.

var a = { get value(){ return 5; }; }
for (var i = 0; i < 100000; i++)
    a.value;

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

app.all('*', function(req, res,next) {
    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

Class extending more than one class Java?

Hello please note like real work.

Children can not have two mother

So in java, subclass can not have two parent class.

Get DOM content of cross-domain iframe

If you have an access to that domain/iframe that is loaded, then you can use window.postMessage to communicate between iframe and the main window.

Read the DOM with JavaScript in iframe and send it via postMessage to the top window.

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Update Rows in SSIS OLEDB Destination

Use Lookupstage to decide whether to insert or update. Check this link for more info - http://beingoyen.blogspot.com/2010/03/ssis-how-to-update-instead-of-insert.html

Steps to do update:

  1. Drag OLEDB Command [instead of oledb destination]
  2. Go to properties window
  3. Under Custom properties select SQLCOMMAND and insert update command ex:

    UPDATE table1 SET col1 = ?, col2 = ? where id = ?

  4. map columns in exact order from source to output as in update command

Is there an equivalent for var_dump (PHP) in Javascript?

If you are looking for PHP function converted in JS, there is this little site: http://phpjs.org. On there you can get most of the PHP function reliably written in JS. for var_dump try: http://phpjs.org/functions/var_dump/ (make sure to check the top comment, this depends on "echo", which can also be downloaded from the same site)

Accessing dict_keys element by index in Python3

test = {'foo': 'bar', 'hello': 'world'}
ls = []
for key in test.keys():
    ls.append(key)
print(ls[0])

Conventional way of appending the keys to a statically defined list and then indexing it for same

how do I query sql for a latest record date for each user

I did somewhat for my application as it:

Below is the query:

select distinct i.userId,i.statusCheck, l.userName from internetstatus 
as i inner join login as l on i.userID=l.userID 
where nowtime in((select max(nowtime) from InternetStatus group by userID));    

SSRS Query execution failed for dataset

I just dealt with this same issue. Make sure your query lists the full source name, using no shortcuts. Visual Studio can recognize the shortcuts, but your reporting services application may not be able to recognize which tables your data should be coming from. Hope that helps.

Raising a number to a power in Java

int weight=10;
int height=10;
double bmi;
bmi = weight / Math.pow(height / 100.0, 2.0);
System.out.println("bmi"+(bmi));
double result = bmi * 100;
result = Math.round(result);
result = result / 100;
System.out.println("result"+result);

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

It's in the app.config file.

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceDebug includeExceptionDetailInFaults="true"/>

Java - Convert image to Base64

To begin with, this line of code:

while ((bytesRead = fis.read(byteArray)) != -1)

is equivalent to

while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1)

So it's writing into the byteArray from offset 0, rather than from where you wrote to before.

You need something like this:

int offset = 0;
int bytesRead = 0;

while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) {
    offset += bytesRead;
}

After you have read the data (bytes) in then, you can convert it to Base64.

There are bigger problems though - you're using a fixed size array, so files that are too big won't be converted correctly, and the code is tricker because of it too.

I would ditch the byte array and go with something like this:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// commons-io IOUtils
IOUtils.copy(fis, buffer);
byte [] data = buffer.toByteArray();
Base64.encode(data);

Or condense it further as Thilo has with FileUtils.

How to run a program automatically as admin on Windows 7 at startup?

A program I wrote, farmComm, may solve this. I released it as open-source and Public Domain.

If it doesn't meet your criteria, you may be able to easily alter it to do so.

farmComm:

  • Runs at boot-up under a service, which continues when users log in or out.
    • In Session 0
    • Under the user "NT AUTHORITY\SYSTEM."
  • Spawns arbitrary processes (you choose);
    • Also in Session 0
    • "Invisibly," or without showing any user interface/GUI
    • With access to graphics hardware (e.g. GPUs).
    • Responds to the active session, even if it changes, including the Secure Desktop. This is how it:
    • Only spawns processes after a user is idle for 8.5 minutes
    • Terminates spawns when a user resumes from idle

The source scripts are available here:

https://github.com/r-alex-hall/farmComm

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

Other answers here are correct: is is used for identity comparison, while == is used for equality comparison. Since what you care about is equality (the two strings should contain the same characters), in this case the is operator is simply wrong and you should be using == instead.

The reason is works interactively is that (most) string literals are interned by default. From Wikipedia:

Interned strings speed up string comparisons, which are sometimes a performance bottleneck in applications (such as compilers and dynamic programming language runtimes) that rely heavily on hash tables with string keys. Without interning, checking that two different strings are equal involves examining every character of both strings. This is slow for several reasons: it is inherently O(n) in the length of the strings; it typically requires reads from several regions of memory, which take time; and the reads fills up the processor cache, meaning there is less cache available for other needs. With interned strings, a simple object identity test suffices after the original intern operation; this is typically implemented as a pointer equality test, normally just a single machine instruction with no memory reference at all.

So, when you have two string literals (words that are literally typed into your program source code, surrounded by quotation marks) in your program that have the same value, the Python compiler will automatically intern the strings, making them both stored at the same memory location. (Note that this doesn't always happen, and the rules for when this happens are quite convoluted, so please don't rely on this behavior in production code!)

Since in your interactive session both strings are actually stored in the same memory location, they have the same identity, so the is operator works as expected. But if you construct a string by some other method (even if that string contains exactly the same characters), then the string may be equal, but it is not the same string -- that is, it has a different identity, because it is stored in a different place in memory.

Clear form fields with jQuery

$(document).ready(function() {
    $('#reset').click(function() {
    $('#compose_form').find("input[type=text] , textarea ").each(function() {
    $(this).val('');
   });
  });
});  

Adding Git-Bash to the new Windows Terminal

Adding "%PROGRAMFILES%\\Git\\bin\\bash.exe -l -i" doesn't work for me. Because of space symbol (which is separator in cmd) in %PROGRAMFILES% terminal executes command "C:\Program" instead of "C:\Program Files\Git\bin\bash.exe -l -i". The solution should be something like adding quotation marks in json file, but I didn't figure out how. The only solution is to add "C:\Program Files\Git\bin" to %PATH% and write "commandline": "bash.exe" in profiles.json

Rails 4 - passing variable to partial

Syntactically a little different but it looks cleaner in my opinion:

render 'my_partial', locals: { title: "My awesome title" }

# not a big fan of the arrow key syntax
render 'my_partial', :locals => { :title => "My awesome title" }

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4, see this answer.

For Rails 3.x, configure a logger in config/environments/test.rb:

config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR

This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.

Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile, then set up two appenders in config/environments/test.rb:

logger = Logging.logger['test']
logger.add_appenders(
    Logging.appenders.stdout,
    Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger

Is it possible to use JavaScript to change the meta-tags of the page?

Yes, it is.

E.g. to set the meta-description:

document.querySelector('meta[name="description"]').setAttribute("content", _desc);

Jquery UI tooltip does not support html content

To avoid placing HTML tags in the title attribute, another solution is to use markdown. For instance, you could use [br] to represent a line break, then perform a simple replace in the content function.

In title attribute:

"Sample Line 1[br][br]Sample Line 2"

In your content function:

content: function () {
    return $(this).attr('title').replace(/\[br\]/g,"<br />");
}

How do I get an element to scroll into view, using jQuery?

Simplest solution I have seen

var offset = $("#target-element").offset();
$('html, body').animate({
    scrollTop: offset.top,
    scrollLeft: offset.left
}, 1000);

Tutorial Here

Set Background cell color in PHPExcel

Seems like there's a bug with applyFromArray right now that won't accept color, but this worked for me:

$objPHPExcel
    ->getActiveSheet()
    ->getStyle('A1')
    ->getFill()
    ->getStartColor()
    ->setRGB('FF0000');

Fastest way to implode an associative array with keys

As an aside, I was in search to find the best way to implode an associative array but using my own seperators etc...

So I did this using PHP's array_walk() function to let me join an associative array into a list of parameters that could then be applied to a HTML tag....

// Create Params Array
$p = Array("id"=>"blar","class"=>"myclass","onclick"=>"myJavascriptFunc()");

// Join Params
array_walk($p, create_function('&$i,$k','$i=" $k=\"$i\"";'));
$p_string = implode($p,"");

// Now use $p_string for your html tag

Obviously, you could stick that in your own function somehow but it gives you an idea of how you can join an associative array using your own method. Hope that helps someone :)

How can I get Git to follow symlinks?

Hmmm, mount --bind doesn't seem to work on Darwin.

Does anyone have a trick that does?

[edited]

OK, I found the answer on Mac OS X is to make a hardlink. Except that that API is not exposed via ln, so you have to use your own tiny program to do this. Here is a link to that program:

Creating directory hard links in Mac OS X

Enjoy!

jQuery keypress() event not firing?

e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.

See http://unixpapa.com/js/key.html for more information.

jQuery UI - Draggable is not a function?

Make sure you have the jQuery object and NOT the element itself. If you select by class, you may not be getting what you expect.

Open up a console and look at what your selector code returns. In Firebug, you should see something like:

jQuery( div.draggable )

You may have to go into an array and grab the first element: $('.draggable').first() Then call draggable() on that jQuery object and you're done.

Assign a login to a user created without login (SQL Server)

Through trial and error, it seems if the user was originally created "without login" then this query

select * from sys.database_principals

will show authentication_type = 0 (NONE).

Apparently these users cannot be re-linked to any login (pre-existing or new, SQL or Windows) since this command:

alter user [TempUser] with login [TempLogin]

responds with the Remap Error "Msg 33016" shown in the question.

Also these users do not show up in classic (deprecating) SP report:

exec sp_change_users_login 'Report'

If anyone knows a way around this or how to change authentication_type, please comment.

Multiplying across in a numpy array

Normal multiplication like you showed:

>>> import numpy as np
>>> m = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> c = np.array([0,1,2])
>>> m * c
array([[ 0,  2,  6],
       [ 0,  5, 12],
       [ 0,  8, 18]])

If you add an axis, it will multiply the way you want:

>>> m * c[:, np.newaxis]
array([[ 0,  0,  0],
       [ 4,  5,  6],
       [14, 16, 18]])

You could also transpose twice:

>>> (m.T * c).T
array([[ 0,  0,  0],
       [ 4,  5,  6],
       [14, 16, 18]])

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

This happened to me in the following scenario:

I created a second project in my workspace, chose "Single View Application" for the template.

I then went to Interface Builder (main iPhone storyboard), added a UISwitch to the main view, and connected it to the view controller through both an IBOutlet and an IBAction (-valueChanged:).

On launch, the app crashes with the exception mentioned in the question. If I remove the switch from the view, it works.

After careful inspection, I realized I control-dragged the connections into the ViewController.h of another project in the same workspace. The 'Automatic' set of Interface Builder's Assistant Editor (a.k.a Tuxedo chest icon) chose as "counterpart" the wrong file (with the right name).

Hope this helps someone, specially because both 'Single View Application' and 'SpriteKit Game' project templates (in my case) create a default view controller class called "ViewController".

JSON serialization/deserialization in ASP.Net Core

You can use Newtonsoft.Json, it's a dependency of Microsoft.AspNet.Mvc.ModelBinding which is a dependency of Microsoft.AspNet.Mvc. So, you don't need to add a dependency in your project.json.

#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);

Note, using a WebAPI controller you don't need to deal with JSON.

UPDATE ASP.Net Core 3.0

Json.NET has been removed from the ASP.NET Core 3.0 shared framework.

You can use the new JSON serializer layers on top of the high-performance Utf8JsonReader and Utf8JsonWriter. It deserializes objects from JSON and serializes objects to JSON. Memory allocations are kept minimal and includes support for reading and writing JSON with Stream asynchronously.

To get started, use the JsonSerializer class in the System.Text.Json.Serialization namespace. See the documentation for information and samples.

To use Json.NET in an ASP.NET Core 3.0 project:

    services.AddMvc()
        .AddNewtonsoftJson();

Read Json.NET support in Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 for more information.

This action could not be completed. Try Again (-22421)

The problem can not be solved with xCode Upload Process. I was facing same issues few days ago when submitting few of my apps and all apps showing same error. After many tries, I used Application Loader to upload app and it worked.

First go to xcode -> product menu -> archive Select Export for Appstore Save IPA file Now Open Application loader by going to xCode -> xCode Menu -> Open Developer Tool -> Application Loader Login with the credentials of account, and select the IPA file. Submit it! It works!

Session only cookies with Javascript

Yes, that is correct.

Not putting an expires part in will create a session cookie, whether it is created in JavaScript or on the server.

See https://stackoverflow.com/a/532660/1901857

How do you find out the caller function in JavaScript?

In both ES6 and Strict mode, use the following to get the Caller function

console.log((new Error()).stack.split("\n")[2].trim().split(" ")[1])

Please note that, the above line will throw an exception, if there is no caller or no previous stack. Use accordingly.

To get callee (the current function name), use:

console.log((new Error()).stack.split("\n")[1].trim().split(" ")[1]) 

How to install Ruby 2.1.4 on Ubuntu 14.04

First of all, install the prerequisite libraries:

sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Then install rbenv, which is used to install Ruby:

cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL

rbenv install 2.3.1
rbenv global 2.3.1
ruby -v

Then (optional) tell Rubygems to not install local documentation:

echo "gem: --no-ri --no-rdoc" > ~/.gemrc

Credits: https://gorails.com/setup/ubuntu/14.10

Warning!!! There are issues with Gnome-Shell. See comment below.

Remove redundant paths from $PATH variable

  1. Just echo $PATH
  2. copy details into a text editor
  3. remove unwanted entries
  4. PATH= # pass new list of entries

HTML-encoding lost when attribute read from input field

HtmlEncodes the given value

  var htmlEncodeContainer = $('<div />');
  function htmlEncode(value) {
    if (value) {
      return htmlEncodeContainer.text(value).html();
    } else {
      return '';
    }
  }

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

You may need to go to Window -> Android SDK Manager -> Packages -> Reload to fetch latest updates and then update the SDK.

the getSource() and getActionCommand()

The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.

How do I escape the wildcard/asterisk character in bash?

I'll add a bit to this old thread.

Usually you would use

$ echo "$FOO"

However, I've had problems even with this syntax. Consider the following script.

#!/bin/bash
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1"

The * needs to be passed verbatim to curl, but the same problems will arise. The above example won't work (it will expand to filenames in the current directory) and neither will \*. You also can't quote $curl_opts because it will be recognized as a single (invalid) option to curl.

curl: option -s --noproxy * -O: is unknown
curl: try 'curl --help' or 'curl --manual' for more information

Therefore I would recommend the use of the bash variable $GLOBIGNORE to prevent filename expansion altogether if applied to the global pattern, or use the set -f built-in flag.

#!/bin/bash
GLOBIGNORE="*"
curl_opts="-s --noproxy * -O"
curl $curl_opts "$1"  ## no filename expansion

Applying to your original example:

me$ FOO="BAR * BAR"

me$ echo $FOO
BAR file1 file2 file3 file4 BAR

me$ set -f
me$ echo $FOO
BAR * BAR

me$ set +f
me$ GLOBIGNORE=*
me$ echo $FOO
BAR * BAR

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

jquery ui Dialog: cannot call methods on dialog prior to initialization

If you cannot upgrade jQuery and you are getting:

Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

You can work around it like so:

$(selector).closest('.ui-dialog-content').dialog('close');

Or if you control the view and know no other dialogs should be in use at all on the entire page, you could do:

$('.ui-dialog-content').dialog('close');

I would only recommend doing this if using closest causes a performance issue. There are likely other ways to work around it without doing a global close on all dialogs.

Difference between getAttribute() and getParameter()

The difference between getAttribute and getParameter is that getParameter will return the value of a parameter that was submitted by an HTML form or that was included in a query string. getAttribute returns an object that you have set in the request, the only way you can use this is in conjunction with a RequestDispatcher. You use a RequestDispatcher to forward a request to another resource (JSP / Servlet). So before you forward the request you can set an attribute which will be available to the next resource.

What is the difference between a port and a socket?

A socket is a data I/O mechanism. A port is a contractual concept of a communication protocol. A socket can exist without a port. A port can exist witout a specific socket (e.g. if several sockets are active on the same port, which may be allowed for some protocols).

A port is used to determine which socket the receiver should route the packet to, with many protocols, but it is not always required and the receiving socket selection can be done by other means - a port is entirely a tool used by the protocol handler in the network subsystem. e.g. if a protocol does not use a port, packets can go to all listening sockets or any socket.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Note: If you are using Bootstrap + AngularJS + UI Bootstrap, .left .right and .next classes are never added. Using the example at the following link and the CSS from Robert McKee answer works. I wanted to comment because it took 3 days to find a full solution. Hope this helps others!

https://angular-ui.github.io/bootstrap/#/carousel

Code snip from UI Bootstrap Demo at the above link.

angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope) {
  $scope.myInterval = 5000;
  var slides = $scope.slides = [];
  $scope.addSlide = function() {
    var newWidth = 600 + slides.length + 1;
    slides.push({
      image: 'http://placekitten.com/' + newWidth + '/300',
      text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
        ['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
    });
  };
  for (var i=0; i<4; i++) {
    $scope.addSlide();
  }
});

Html From UI Bootstrap, Notice I added the .fade class to the example.

<div ng-controller="CarouselDemoCtrl">
    <div style="height: 305px">
        <carousel class="fade" interval="myInterval">
          <slide ng-repeat="slide in slides" active="slide.active">
            <img ng-src="{{slide.image}}" style="margin:auto;">
            <div class="carousel-caption">
              <h4>Slide {{$index}}</h4>
              <p>{{slide.text}}</p>
            </div>
          </slide>
        </carousel>
    </div>
</div>

CSS from Robert McKee's answer above

.carousel.fade {
opacity: 1;
}
.carousel.fade .item {
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
left: 0 !important;
opacity: 0;
top:0;
position:absolute;
width: 100%;
display:block !important;
z-index:1;
}
.carousel.fade .item:first-child {
top:auto;
position:relative;
}
.carousel.fade .item.active {
opacity: 1;
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
z-index:2;
}
/*
Added z-index to raise the left right controls to the top
*/
.carousel-control {
z-index:3;
}

Iterating Over Dictionary Key Values Corresponding to List in Python

Dictionaries have a built in function called iterkeys().

Try:

for team in league.iterkeys():
    runs_scored = float(league[team][0])
    runs_allowed = float(league[team][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

PowerShell script to check the status of a URL

For people that have PowerShell 3 or later (i.e. Windows Server 2012+ or Windows Server 2008 R2 with the Windows Management Framework 4.0 update), you can do this one-liner instead of invoking System.Net.WebRequest:

$statusCode = wget http://stackoverflow.com/questions/20259251/ | % {$_.StatusCode}

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

Linux : Search for a Particular word in a List of files under a directory

You can use this command:

grep -rn "string" *

n for showing line number with the filename r for recursive

How can I extract the folder path from file path in Python?

You were almost there with your use of the split function. You just needed to join the strings, like follows.

>>> import os
>>> '\\'.join(existGDBPath.split('\\')[0:-1])
'T:\\Data\\DBDesign'

Although, I would recommend using the os.path.dirname function to do this, you just need to pass the string, and it'll do the work for you. Since, you seem to be on windows, consider using the abspath function too. An example:

>>> import os
>>> os.path.dirname(os.path.abspath(existGDBPath))
'T:\\Data\\DBDesign'

If you want both the file name and the directory path after being split, you can use the os.path.split function which returns a tuple, as follows.

>>> import os
>>> os.path.split(os.path.abspath(existGDBPath))
('T:\\Data\\DBDesign', 'DBDesign_93_v141b.mdb')

What is the best way to implement constants in Java?

A single, generic constants class is a bad idea. Constants should be grouped together with the class they're most logically related to.

Rather than using variables of any kind (especially enums), I would suggest that you use methods. Create a method with the same name as the variable and have it return the value you assigned to the variable. Now delete the variable and replace all references to it with calls to the method you just created. If you feel that the constant is generic enough that you shouldn't have to create an instance of the class just to use it, then make the constant method a class method.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

I face this issue because I messed return keyword in custom rendering in Columns section

columns: [
    {....
        'data': function(row, type, val, meta) {
            if (row.LetterStatus)
                 return '@CultureHelper.GetCurrentCulture()' == 'ar'? row.LetterStatus.NameInArabic: row.LetterStatus.NameInEnglish;
            else row.LetterStatusID.toString();// here is the problem because I messed the Return key keyword
          },
     ......
    }

the problem in my code is because I messed the Return keyword in the else clause

so I changed it to

....
else return row.LetterStatusID.toString();// messed return keyword added
.....

How to mention C:\Program Files in batchfile

use this as somethink

"C:/Program Files (x86)/Nox/bin/nox_adb" install -r app.apk

where

"path_to_executable" commands_argument

Is there a Python caching library?

Try redis, it is one of the cleanest and easiest solutions for applications to share data in a atomic way or if you have got some web server platform. Its very easy to setup, you will need a python redis client http://pypi.python.org/pypi/redis

mysql Foreign key constraint is incorrectly formed error

Try running following:

show create table Parent

//and check if type for both tables are the same, like myISAM or innoDB, etc
//Other aspects to check with this error message: the columns used as foreign 
keys must be indexed, they must be of the same type 
(if i.e one is of type smallint(5) and the other of type smallint(6), 
it won't work), and, if they are integers, they should be unsigned.

//or check for charsets
show variables like "character_set_database";
show variables like "collation_database";

//edited: try something like this
ALTER TABLE table2
ADD CONSTRAINT fk_IdTable2
FOREIGN KEY (Table1_Id)
REFERENCES Table1(Table1_Id)
ON UPDATE CASCADE 
ON DELETE CASCADE;

What is the difference between React Native and React?

React is a framework for building applications using JavaScript. React Native is an entire platform allowing you to build native, cross-platform mobile apps, and React.js is a JavaScript library you use for constructing a high performing UI layer. React.js is the heart of React Native, and it embodies all React’s principles and syntax, so the learning curve is easy. The platform is what gave rise to their technical differences. Like the browser code in React is rendered through Virtual DOM while React Native uses Native API’s to render components on mobile. React uses HTML and with React Native, you need to familiarize yourself with React Native syntax. React Native doesn’t use CSS either. This means you’ll have to use the animated API which comes with React Native to animate different components of your application.

Bottom line, React is ideal for building dynamic, high performing, responsive UI for your web interfaces, while React Native is meant to give your mobile apps a truly native feel.

Reff: what-is-the-difference-between-react-js-and-react-native

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

Is this a console program project or a Windows project? I'm asking because for a Win32 and similar project, the entry point is WinMain().

  1. Right-click the Project (not the Solution) on the left side.
  2. Then click Properties -> Configuration Properties -> Linker -> System

If it says Subsystem Windows your entry point should be WinMain(), i.e.

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
   your code here ...
}

Besides, speaking of the comments. This is a compile (or more precisely a Link) error, not a run-time error. When you start to debug, the compiler needs to make a complete program (not just to compile your module) and that is when the error occurs.

It does not even get to the point being loaded and run.

Using multiple .cpp files in c++ program?

In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h" to your main.cpp file.

In second.h you just declare like this void yourFunction(); In second.cpp you implement it like

void yourFunction() { 
   doSomethng(); 
}

Don't forget to #include "second.h" also in the beginning of second.cpp

Hope this helps:)

Rename master branch for both local and remote Git repositories

Assuming you are currently on master:

git push origin master:master-old        # 1
git branch master-old origin/master-old  # 2
git reset --hard $new_master_commit      # 3
git push -f origin                       # 4
  1. First make a master-old branch in the origin repository, based off of the master commit in the local repository.
  2. Create a new local branch for this new origin/master-old branch (which will automatically be set up properly as a tracking branch).
  3. Now point your local master to whichever commit you want it to point to.
  4. Finally, force-change master in the origin repository to reflect your new local master.

(If you do it in any other way, you need at least one more step to ensure that master-old is properly set up to track origin/master-old. None of the other solutions posted at the time of this writing include that.)

Increment variable value by 1 ( shell programming)

These are the methods I know:

ichramm@NOTPARALLEL ~$ i=10; echo $i;
10
ichramm@NOTPARALLEL ~$ ((i+=1)); echo $i;
11
ichramm@NOTPARALLEL ~$ ((i=i+1)); echo $i;
12
ichramm@NOTPARALLEL ~$ i=`expr $i + 1`; echo $i;
13

Note the spaces in the last example, also note that's the only one that uses $i.

Select all child elements recursively in CSS

Use a white space to match all descendants of an element:

div.dropdown * {
    color: red;
}

x y matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.

The asterisk * matches any element.

Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors

How to declare variable and use it in the same Oracle SQL script?

Just want to add Matas' answer. Maybe it's obvious, but I've searched for a long time to figure out that the variable is accessible only inside the BEGIN-END construction, so if you need to use it in some code later, you need to put this code inside the BEGIN-END block.

Note that these blocks can be nested:

DECLARE x NUMBER;
BEGIN
    SELECT PK INTO x FROM table1 WHERE col1 = 'test';

    DECLARE y NUMBER;
    BEGIN
        SELECT PK INTO y FROM table2 WHERE col2 = x;

        INSERT INTO table2 (col1, col2)
        SELECT y,'text'
        FROM dual
        WHERE exists(SELECT * FROM table2);

        COMMIT;
    END;
END;

Find unique rows in numpy.array

None of these answers worked for me. I'm assuming as my unique rows contained strings and not numbers. However this answer from another thread did work:

Source: https://stackoverflow.com/a/38461043/5402386

You can use .count() and .index() list's methods

coor = np.array([[10, 10], [12, 9], [10, 5], [12, 9]])
coor_tuple = [tuple(x) for x in coor]
unique_coor = sorted(set(coor_tuple), key=lambda x: coor_tuple.index(x))
unique_count = [coor_tuple.count(x) for x in unique_coor]
unique_index = [coor_tuple.index(x) for x in unique_coor]

Android Preventing Double Click On A Button

There is a native debounce click listener in Java

view.setOnClickListener(new DebouncedOnClickListener(1000) { //in milisecs
            @Override
            public void onDebouncedClick(View v) {
                //action
            }
        });

How do I make the text box bigger in HTML/CSS?

If you want to make them a lot bigger, like for multiple lines of input, you may want to use a textarea tag instead of the input tag. This allows you to put in number of rows and columns you want on your textarea without messing with css (e.g. <textarea rows="2" cols="25"></textarea>).

Text areas are resizable by default. If you want to disable that, just use the resize css rule:

#signin textarea {
    resize: none;
}

A simple solution to your question about default text that disappears when the user clicks is to use the placeholder attribute. This will work for <input> tags as well.

<textarea rows="2" cols="25" placeholder="This is the default text"></textarea>

This text will disappear when the user enters information rather than when they click, but that is common functionality for this kind of thing.

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

XAMPP Start automatically on Windows 7 startup

Try to run Your XAMPP Control Panel as Run as administrator, then install Apache and MySQL.

enter image description here

When XAMPP opens, ensure that Apache and MySQL services are stopped.

enter image description here

Now just check/tick on Apache and Mysql service module.

enter image description here

Now Apache and MySQL will be added to window services. You can set these services to start when Windows boots.

PHP - remove all non-numeric characters from a string

You can use preg_replace in this case;

$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

$res return 6 in this case.

If want also to include decimal separator or thousand separator check this example:

$res = preg_replace("/[^0-9.]/", "", "$ 123.099");

$res returns "123.099" in this case

Include period as decimal separator or thousand separator: "/[^0-9.]/"

Include coma as decimal separator or thousand separator: "/[^0-9,]/"

Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"

Clip/Crop background-image with CSS

Another option is to use linear-gradient() to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...

_x000D_
_x000D_
.flair {_x000D_
  min-width: 50px; /* width larger than sprite */_x000D_
  text-indent: 60px;_x000D_
  height: 25px;_x000D_
  display: inline-block;_x000D_
  background:_x000D_
    linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
    url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;_x000D_
}_x000D_
_x000D_
.flair-classic {_x000D_
  background-position: 50px 0, 0 -25px;_x000D_
}_x000D_
_x000D_
.flair-r2 {_x000D_
  background-position: 50px 0, -50px -175px;_x000D_
}_x000D_
_x000D_
.flair-smite {_x000D_
  text-indent: 35px;_x000D_
  background-position: 25px 0, -50px -25px;_x000D_
}
_x000D_
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />
_x000D_
_x000D_
_x000D_

I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before or ::after elements because I'm already using them for another hack.

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

Anaconda does not use the PYTHONPATH. One should however note that if the PYTHONPATH is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a

unset PYTHONPATH

For instance this PYTHONPATH points to an incorrect pandas lib:

export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
    from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8

unsetting the PYTHONPATH prevents the wrong pandas lib from being loaded:

unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>

How to calculate the number of occurrence of a given character in each row of a column of strings?

You could just use string division

require(roperators)
my_strings <- c('apple', banana', 'pear', 'melon')
my_strings %s/% 'a'

Which will give you 1, 3, 1, 0. You can also use string division with regular expressions and whole words.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

Another option is using Google Guava's com.google.common.base.CaseFormat

George Hawkins left a comment with this example of usage:

CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

SQL Server add auto increment primary key to existing table

When we add and identity column in an existing table it will automatically populate no need to populate it manually.

jQuery: count number of rows in a table

I needed a way to do this in an AJAX return, so I wrote this piece:

<p id="num_results">Number of results: <span></span></p>

<div id="results"></div>

<script type="text/javascript">
$(function(){
    ajax();
})

//Function that makes Ajax call out to receive search results
var ajax = function() {
    //Setup Ajax
    $.ajax({
        url: '/path/to/url', //URL to load
        type: 'GET', //Type of Ajax call
        dataType: 'html', //Type of data to be expected on return
        success: function(data) { //Function that manipulates the returned AJAX'ed data
            $('#results').html(data); //Load the data into a HTML holder
            var $el = $('#results'); //jQuery Object that is holding the results
            setTimeout(function(){ //Custom callback function to count the number of results
                callBack($el);
            });
        }
    });
}

//Custom Callback function to return the number of results
var callBack = function(el) {
    var length = $('tr', $(el)).not('tr:first').length; //Count all TR DOM elements, except the first row (which contains the header information)
    $('#num_results span').text(length); //Write the counted results to the DOM
}
</script>

Obviously this is a quick example, but it may be helpful.

.ssh directory not being created

I am assuming that you have enough permissions to create this directory.

To fix your problem, you can either ssh to some other location:

ssh [email protected]

and accept new key - it will create directory ~/.ssh and known_hosts underneath, or simply create it manually using

mkdir ~/.ssh
chmod 700 ~/.ssh

Note that chmod 700 is an important step!

After that, ssh-keygen should work without complaints.

What are some great online database modeling tools?

I've used DBDesigner before. It is an open source tool. You might check that out. Not sure if it fits your needs.

Best of luck!

What does "-ne" mean in bash?

This is one of those things that can be difficult to search for if you don't already know where to look.

[ is actually a command, not part of the bash shell syntax as you might expect. It happens to be a Bash built-in command, so it's documented in the Bash manual.

There's also an external command that does the same thing; on many systems, it's provided by the GNU Coreutils package.

[ is equivalent to the test command, except that [ requires ] as its last argument, and test does not.

Assuming the bash documentation is installed on your system, if you type info bash and search for 'test' or '[' (the apostrophes are part of the search), you'll find the documentation for the [ command, also known as the test command. If you use man bash instead of info bash, search for ^ *test (the word test at the beginning of a line, following some number of spaces).

Following the reference to "Bash Conditional Expressions" will lead you to the description of -ne, which is the numeric inequality operator ("ne" stands for "not equal). By contrast, != is the string inequality operator.

You can also find bash documentation on the web.

The official definition of the test command is the POSIX standard (to which the bash implementation should conform reasonably well, perhaps with some extensions).

Differences between Octave and MATLAB?

Nested functions and closures are now supported by many languages, including MATLAB. JavaScript promotes closures as a first class design principle.

Sadly, Octave does not support closures (nested functions with lexical scoping).

According http://osdir.com/ml/octave-bug-tracker/2013-06/msg00210.html one might even get the impression that the developers do not want or are unable to get it right.

This will break a lot of code, both ways. No workaround.

Uncaught ReferenceError: $ is not defined

Root problem is a ReferenceError. MDN indicates that a try/catch block is the proper tool for the job. In my case, I was getting uncaught reference error for a payment sdk/library. The below works for me.

try {
  var stripe = Stripe('pk_test_---------');
} catch (e) {
    stripe = null;
}

if(stripe){
  //we are good to go now
}

Obviously the fix is to load whatever SDK/library, e.g. jQuery, prior to calling its methods but the try/catch does keep your shared JavaScript from barfing up errors in case you run that shared script on a page that doesn't load whatever library you use on a subset of pages.

Excel SUMIF between dates

this works, and can be adapted for weeks or anyother frequency i.e. weekly, quarterly etc...

=SUMIFS(B12:B11652,A12:A11652,">="&DATE(YEAR(C12),MONTH(C12),1),A12:A11652,"<"&DATE(YEAR(C12),MONTH(C12)+1,1))

Laravel 5 not finding css files

If you are using laravel 5 or 6:

  1. Inside Public folder create .css, .js, images... folders

enter image description here

  1. Then inside your blade file you can display an images using this code :

_x000D_
_x000D_
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link src="/images/test.png">
<!-- / is important and dont write public folder-->
_x000D_
_x000D_
_x000D_

What to use now Google News API is deprecated?

I'm running into the same issue with one of my own apps. So far I've found the only non-deprecated way to access Google News data is through their RSS feeds. They have a feed for each section and also a useful search function. However, these are only for noncommercial use.

As for viable alternatives I'll be trying out these two services: Feedzilla, Daylife

What are the differences between Pandas and NumPy+SciPy in Python?

Numpy is required by pandas (and by virtually all numerical tools for Python). Scipy is not strictly required for pandas but is listed as an "optional dependency". I wouldn't say that pandas is an alternative to Numpy and/or Scipy. Rather, it's an extra tool that provides a more streamlined way of working with numerical and tabular data in Python. You can use pandas data structures but freely draw on Numpy and Scipy functions to manipulate them.

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

There's a wrapper around the flock(2) system call called, unimaginatively, flock(1). This makes it relatively easy to reliably obtain exclusive locks without worrying about cleanup etc. There are examples on the man page as to how to use it in a shell script.

How to change Visual Studio 2012,2013 or 2015 License Key?

See my UPDATE at the end, before reading the following answer.

I have windows 8 and another pc with windows 8.1

I had License error saying "Prerelease software. License expired".

The only solution that I found which is inspired by the above solutions (Thanks!) was to run process monitor and see the exact registry keys that are accessed when I start the VS2013 which were:

HKCR\Licenses\E79B3F9C-6543-4897-BBA5-5BFB0A02BB5C

like what are mentioned in the previous posts. However the process monitor said that this registry is access denied.

So I opened regedit and found that registry key and I could not open it. It says I have no permission to see it.

SO I had to change its permission:

  1. Right click on the "HKCR\Licenses\E79B3F9C-6543-4897-BBA5-5BFB0A02BB5C" key
  2. Permissions
  3. Add
  4. In "Enter object names to select" I have added my windows user name. Ok.
  5. check on Full control
  6. Advanced
  7. Owner click on "Change"
  8. In "Enter object names to select" I have added my windows user name. Ok.
  9. Ok. Ok. Ok.

I found that this registry key has several sub keys, however you have to restart regedit to see them.

By seeing which other registry keys are access denied in process monitor , I knew that VS2013 will specifically deal with these subkeys which are ACCESS DENIED also: 06181 0bcad

and these subkeys should be changed their permissions as well like above.

After making these permission changes everything worked well.

The same thing has been done to Microsoft visual studio 2010 because an error in the license as well and the solution worked well.

UPDATE : It turned out that starting visual studio as administrator solved this issue without this registry massage. Seems that this happened to my pc after changing the 'required password to login' removed in the user settings. (I wanted to let the pc start running without any password after restart from a crash or anything else). This made a lot of programs not able to write into some folders like temp folders unless I start the application as admin. Even printing from excel would not work, if excel is not started as admin.

How to run (not only install) an android application using .apk file?

if you're looking for the equivalent of "adb run myapp.apk"

you can use the script shown in this answer

(linux and mac only - maybe with cygwin on windows)

linux/mac users can also create a script to run an apk with something like the following:

create a file named "adb-run.sh" with these 3 lines:

pkg=$(aapt dump badging $1|awk -F" " '/package/ {print $2}'|awk -F"'" '/name=/ {print $2}')
act=$(aapt dump badging $1|awk -F" " '/launchable-activity/ {print $2}'|awk -F"'" '/name=/ {print $2}')
adb shell am start -n $pkg/$act

then "chmod +x adb-run.sh" to make it executable.

now you can simply:

adb-run.sh myapp.apk

The benefit here is that you don't need to know the package name or launchable activity name. Similarly, you can create "adb-uninstall.sh myapp.apk"

Note: This requires that you have aapt in your path. You can find it under the new build tools folder in the SDK

jQuery preventDefault() not triggered

If e.preventDefault(); is not working you must use e.stopImmediatePropagation(); instead.

For further informations take a look at : What's the difference between event.stopPropagation and event.preventDefault?

$("div.subtab_left li.notebook a").click(function(e) {
    e.stopImmediatePropagation();
    return false;
});

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

The question is already answered, Updating answer to add the PyCharm bin directory to $PATH var, so that pycharm editor can be opened from anywhere(path) in terminal.

Edit the bashrc file,

nano .bashrc

Add following line at the end of bashrc file

export PATH="<path-to-unpacked-pycharm-installation-directory>/bin:$PATH"

Now you can open pycharm from anywhere in terminal

pycharm.sh

How to call function of one php file from another php file and pass parameters to it?

Yes include the first file into the second. That's all.

See an example below,

File1.php :

<?php
  function first($int, $string){ //function parameters, two variables.
    return $string;  //returns the second argument passed into the function
  }
?>

Now Using include (http://php.net/include) to include the File1.php to make its content available for use in the second file:

File2.php :

<?php
  include 'File1.php';
  echo first(1,"omg lol"); //returns omg lol;
?>

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

There is no standard unfortunately, this is one of the perils of installing from source. Some Makefiles will include an "uninstall", so

make uninstall

from the source directory may work. Otherwise, it may be a matter of manually undoing whatever the make install did.

make clean usually just cleans up the source directory - removing generated/compiled files and the like, probably not what you're after.

Rounded corner for textview in android

Beside radius, there are some property to round corner like topRightRadius, topLeftRadius, bottomRightRadius, bottomLeftRadius

Example TextView with red border with corner and gray background

bg_rounded.xml (in the drawables folder)

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="10dp"
        android:color="#f00" />

    <solid android:color="#aaa" />

    <corners
        android:radius="5dp"
        android:topRightRadius="100dp" />
</shape>

TextView

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_rounded"
    android:text="Text"
    android:padding="20dp"
    android:layout_margin="10dp"
    />

Result

enter image description here

Why do python lists have pop() but not push()

FYI, it's not terribly difficult to make a list that has a push method:

>>> class StackList(list):
...     def push(self, item):
...             self.append(item)
... 
>>> x = StackList([1,2,3])
>>> x
[1, 2, 3]
>>> x.push(4)
>>> x
[1, 2, 3, 4]

A stack is a somewhat abstract datatype. The idea of "pushing" and "popping" are largely independent of how the stack is actually implemented. For example, you could theoretically implement a stack like this (although I don't know why you would):

l = [1,2,3]
l.insert(0, 1)
l.pop(0)

...and I haven't gotten into using linked lists to implement a stack.

Write a file in UTF-8 using FileWriter (Java)?

Since Java 7 there is an easy way to handle character encoding of BufferedWriter and BufferedReaders. You can create a BufferedWriter directly by using the Files class instead of creating various instances of Writer. You can simply create a BufferedWriter, which considers character encoding, by calling:

Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8);

You can find more about it in JavaDoc:

How to Delete Session Cookie?

There are known issues with IE and Opera not removing session cookies when setting the expire date to the past (which is what the jQuery cookie plugin does)

This works fine in Safari and Mozilla/FireFox.

Transition of background-color

Another way of accomplishing this is using animation which provides more control.

#content #nav a {
    background-color: #FF0;
    
    /* only animation-duration here is required, rest are optional (also animation-name but it will be set on hover)*/
    animation-duration: 1s; /* same as transition duration */
    animation-timing-function: linear; /* kind of same as transition timing */
    animation-delay: 0ms; /* same as transition delay */
    animation-iteration-count: 1; /* set to 2 to make it run twice, or Infinite to run forever!*/
    animation-direction: normal; /* can be set to "alternate" to run animation, then run it backwards.*/
    animation-fill-mode: none; /* can be used to retain keyframe styling after animation, with "forwards" */
    animation-play-state: running; /* can be set dynamically to pause mid animation*/
    
    /* declaring the states of the animation to transition through */
    /* optionally add other properties that will change here, or new states (50% etc) */
    @keyframes onHoverAnimation {
    0% {
      background-color: #FF0;  
    }
    100% {
      background-color: #AD310B;
    }
  }
}

#content #nav a:hover {
    /* animation wont run unless the element is given the name of the animation. This is set on hover */
    animation-name: onHoverAnimation;
}

Is it possible to auto-format your code in Dreamweaver?

Following works perfectly for me: -*click on COMMAND and click on APPLY SOURCE FORMATTING - *And click on Clean Up HTML

Thank you PEKA

Java: How to convert String[] to List or Set

The easiest way is through

Arrays.asList(stringArray);

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

I think I know why you want to avoid that. But maybe try & catch !== try & catch. ;o) This came into my mind:

var json_verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};

So you may also dirty clip to the JSON object, like:

JSON.verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};

As this as encapsuled as possible, it may not break on error.

Javascript : natural sort of alphanumerical strings

The most fully-featured library to handle this as of 2019 seems to be natural-orderby.

const { orderBy } = require('natural-orderby')

const unordered = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12'
]

const ordered = orderBy(unordered)

// [ '19asd',
//   '123asd',
//   '12345asd',
//   'asd12',
//   'asd123' ]

It not only takes arrays of strings, but also can sort by the value of a certain key in an array of objects. It can also automatically identify and sort strings of: currencies, dates, currency, and a bunch of other things.

Surprisingly, it's also only 1.6kB when gzipped.

How to keep the console window open in Visual C++?

Put a breakpoint on the return line.

You are running it in the debugger, right?

Swift - How to detect orientation changes

Swift 3 Above code updated:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    } else {
        print("Portrait")
    }
}

If you can decode JWT, how are they secure?

Ref - JWT Structure and Security

It is important to note that JWT are used for authorization and not authentication. So a JWT will be created for you only after you have been authenticated by the server by may be specifying the credentials. Once JWT has been created for all future interactions with server JWT can be used. So JWT tells that server that this user has been authenticated, let him access the particular resource if he has the role.
Information in the payload of the JWT is visible to everyone. There can be a "Man in the Middle" attack and the contents of the JWT can be changed. So we should not pass any sensitive information like passwords in the payload. We can encrypt the payload data if we want to make it more secure. If Payload is tampered with server will recognize it.
So suppose a user has been authenticated and provided with a JWT. Generated JWT has a claim specifying role of Admin. Also the Signature is generated with

enter image description here

This JWT is now tampered with and suppose the role is changed to Super Admin
Then when the server receives this token it will again generate the signature using the secret key(which only the server has) and the payload. It will not match the signature in the JWT. So the server will know that the JWT has been tampered with.

posting hidden value

You have to use $_POST['date'] instead of $date if it's coming from a POST request ($_GET if it's a GET request).

Check if bash variable equals 0

Specifically: ((depth)). By example, the following prints 1.

declare -i x=0
((x)) && echo $x

x=1
((x)) && echo $x

Create a Bitmap/Drawable from file path

you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.

declare a HashMap somewhere in your class:

private static HashMap<String, Integer> images = null;

//Then initialize it in your constructor:

public myClass() {
  if (images == null) {
    images = new HashMap<String, Integer>();
    images.put("Human1Arm", R.drawable.human_one_arm);
    // for all your images - don't worry, this is really fast and will only happen once
  }
}

Now for access -

String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);

How to use ConcurrentLinkedQueue?

The ConcurentLinkedQueue is a very efficient wait/lock free implementation (see the javadoc for reference), so not only you don't need to synchronize, but the queue will not lock anything, thus being virtually as fast as a non synchronized (not thread safe) one.

Rails: How to run `rails generate scaffold` when the model already exists?

For the ones starting a rails app with existing database there is a cool gem called schema_to_scaffold to generate a scaffold script. it outputs:

rails g scaffold users fname:string lname:string bdate:date email:string encrypted_password:string

from your schema.rb our your renamed schema.rb. Check it

Python JSON dump / append to .txt with each variable on new line

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

How to customize the background color of a UITableViewCell?

Here is the most efficient way I have come across to solve this problem, use the willDisplayCell delegate method (this takes care of the white color for the text label background as well when using cell.textLabel.text and/or cell.detailTextLabel.text):

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { ... }

When this delegate method is called the color of the cell is controlled via the cell rather than the table view, as when you use:

- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath { ... }

So within the body of the cell delegate method add the following code to alternate colors of cells or just use the function call to make all the cells of the table the same color.

if (indexPath.row % 2)
{
    [cell setBackgroundColor:[UIColor colorWithRed:.8 green:.8 blue:1 alpha:1]];
}
else [cell setBackgroundColor:[UIColor clearColor]];

This solution worked well in my circumstance...

Remove all special characters except space from a string using JavaScript

I tried Seagul's very creative solution, but found it treated numbers also as special characters, which did not suit my needs. So here is my (failsafe) tweak of Seagul's solution...

//return true if char is a number
function isNumber (text) {
  if(text) {
    var reg = new RegExp('[0-9]+$');
    return reg.test(text);
  }
  return false;
}

function removeSpecial (text) {
  if(text) {
    var lower = text.toLowerCase();
    var upper = text.toUpperCase();
    var result = "";
    for(var i=0; i<lower.length; ++i) {
      if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '')) {
        result += text[i];
      }
    }
    return result;
  }
  return '';
}

Returning the product of a list

I remember some long discussions on comp.lang.python (sorry, too lazy to produce pointers now) which concluded that your original product() definition is the most Pythonic.

Note that the proposal is not to write a for loop every time you want to do it, but to write a function once (per type of reduction) and call it as needed! Calling reduction functions is very Pythonic - it works sweetly with generator expressions, and since the sucessful introduction of sum(), Python keeps growing more and more builtin reduction functions - any() and all() are the latest additions...

This conclusion is kinda official - reduce() was removed from builtins in Python 3.0, saying:

"Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable."

See also The fate of reduce() in Python 3000 for a supporting quote from Guido (and some less supporting comments by Lispers that read that blog).

P.S. if by chance you need product() for combinatorics, see math.factorial() (new 2.6).

How do I measure time elapsed in Java?

If you prefer using Java's Calendar API you can try this,

Date startingTime = Calendar.getInstance().getTime();
//later on
Date now = Calendar.getInstance().getTime();
long timeElapsed = now.getTime() - startingTime.getTime();

How to run Conda?

If you have installed Anaconda but are not able to load the correct versions of python and ipython, or if you see conda: command not found when trying to use conda, this may be an issue with your PATH environment variable. At the prompt, type:

export PATH=~/anaconda/bin:$PATH

For this example, it is assumed that Anaconda is installed in the default ~/anaconda location.

How to import existing Git repository into another?

The simple way to do that is to use git format-patch.

Assume we have 2 git repositories foo and bar.

foo contains:

  • foo.txt
  • .git

bar contains:

  • bar.txt
  • .git

and we want to end-up with foo containing the bar history and these files:

  • foo.txt
  • .git
  • foobar/bar.txt

So to do that:

 1. create a temporary directory eg PATH_YOU_WANT/patch-bar
 2. go in bar directory
 3. git format-patch --root HEAD --no-stat -o PATH_YOU_WANT/patch-bar --src-prefix=a/foobar/ --dst-prefix=b/foobar/
 4. go in foo directory
 5. git am PATH_YOU_WANT/patch-bar/*

And if we want to rewrite all message commits from bar we can do, eg on Linux:

git filter-branch --msg-filter 'sed "1s/^/\[bar\] /"' COMMIT_SHA1_OF_THE_PARENT_OF_THE_FIRST_BAR_COMMIT..HEAD

This will add "[bar] " at the beginning of each commit message.

How to access model hasMany Relation with where condition?

If you want to apply condition on the relational table you may use other solutions as well.. This solution is working from my end.

public static function getAllAvailableVideos() {
        $result = self::with(['videos' => function($q) {
                        $q->select('id', 'name');
                        $q->where('available', '=', 1);
                    }])                    
                ->get();
        return $result;
    }

What's the simplest way of detecting keyboard input in a script from the terminal?

This worked for me on macOS Sierra and Python 2.7.10 and 3.6.3

import sys,tty,os,termios
def getkey():
    old_settings = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    try:
        while True:
            b = os.read(sys.stdin.fileno(), 3).decode()
            if len(b) == 3:
                k = ord(b[2])
            else:
                k = ord(b)
            key_mapping = {
                127: 'backspace',
                10: 'return',
                32: 'space',
                9: 'tab',
                27: 'esc',
                65: 'up',
                66: 'down',
                67: 'right',
                68: 'left'
            }
            return key_mapping.get(k, chr(k))
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
try:
    while True:
        k = getkey()
        if k == 'esc':
            quit()
        else:
            print(k)
except (KeyboardInterrupt, SystemExit):
    os.system('stty sane')
    print('stopping.')

Which version of C# am I using

Useful tip for finding the C# version:

To know what language version you're currently using, put #error version (case sensitive) in your code. This makes the compiler produce a diagnostic, CS8304, with a message containing the compiler version being used and the current selected language version.

From C# language versioning in MS docs.

You can drop #error version anywhere in your code. It will generate an error so you'll need to remove it after you've used it. The error gives details of the compiler and language versions, eg:

Error   CS8304  Compiler version: '3.7.0-6.20459.4 (7ee7c540)'. Language version: 8.0.

In VS 2019, at least, you don't need to compile your code for #error version to give you the version number. Just mousing over it in your code will bring up the same error details you would see when you compile the code.

What is mapDispatchToProps?

It's basically a shorthand. So instead of having to write:

this.props.dispatch(toggleTodo(id));

You would use mapDispatchToProps as shown in your example code, and then elsewhere write:

this.props.onTodoClick(id);

or more likely in this case, you'd have that as the event handler:

<MyComponent onClick={this.props.onTodoClick} />

There's a helpful video by Dan Abramov on this here: https://egghead.io/lessons/javascript-redux-generating-containers-with-connect-from-react-redux-visibletodolist

how to use substr() function in jquery?

Extract characters from a string:

var str = "Hello world!";
var res = str.substring(1,4);

The result of res will be:

ell

http://www.w3schools.com/jsref/jsref_substring.asp

$('.dep_buttons').mouseover(function(){
    $(this).text().substring(0,25);
    if($(this).text().length > 30) {
        $(this).stop().animate({height:"150px"},150);
    }
    $(".dep_buttons").mouseout(function(){
        $(this).stop().animate({height:"40px"},150);
    });
});

Append data frames together in a for loop

Again maRtin is correct but for this to work you have start with a dataframe that already has at least one column

model <- #some processing
df <- data.frame(col1=model)

for (i in 2:17)
{
     model <- # some processing
     nextcol <-  data.frame(model)
     colnames(nextcol) <- c(paste("col", i, sep="")) # rename the comlum
     df <- cbind(df, nextcol)
}

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

How can I refresh or reload the JFrame?

Here's a short code that might help.

    <yourJFrameName> main = new <yourJFrameName>();    

    main.setVisible(true);
    this.dispose();

where...

main.setVisible(true);

will run the JFrame again.

this.dispose();

will terminate the running window.

Latex - Change margins of only a few pages

I was struggling a lot with different solutions including \vspace{-Xmm} on the top and bottom of the page and dealing with warnings and errors. Finally I found this answer:

You can change the margins of just one or more pages and then restore it to its default:

\usepackage{geometry}
...
... 
...
\newgeometry{top=5mm, bottom=10mm}     % use whatever margins you want for left, right, top and bottom.
...
... %<The contents of enlarged page(s)>
...    
\restoregeometry     %so it does not affect the rest of the pages.
...
... 
...

PS:

1- This can also fix the following warning:

LaTeX Warning: Float too large for page by ...pt on input line ...

2- For more detailed answer look at this.

3- I just found that this is more elaboration on Kevin Chen's answer.

Multiprocessing vs Threading Python

Other answers have focused more on the multithreading vs multiprocessing aspect, but in python Global Interpreter Lock (GIL) has to be taken into account. When more number (say k) of threads are created, generally they will not increase the performance by k times, as it will still be running as a single threaded application. GIL is a global lock which locks everything out and allows only single thread execution utilizing only a single core. The performance does increase in places where C extensions like numpy, Network, I/O are being used, where a lot of background work is done and GIL is released.
So when threading is used, there is only a single operating system level thread while python creates pseudo-threads which are completely managed by threading itself but are essentially running as a single process. Preemption takes place between these pseudo threads. If the CPU runs at maximum capacity, you may want to switch to multiprocessing.
Now in case of self-contained instances of execution, you can instead opt for pool. But in case of overlapping data, where you may want processes communicating you should use multiprocessing.Process.

How can I add raw data body to an axios request?

There many methods to send raw data with a post request. I personally like this one.

    const url = "your url"
    const data = {key: value}
    const headers = {
        "Content-Type": "application/json"
    }
    axios.post(url, data, headers)

href around input type submit

I agree with Quentin. It doesn't make sense as to why you want to do it like that. It's part of the Semantic Web concept. You have to plan out the objects of your web site for future integration/expansion. Another web app or web site cannot interact with your content if it doesn't follow the proper use-case.

IE and Firefox are two different beasts. There are a lot of things that IE allows that Firefox and other standards-aware browsers reject.

If you're trying to create buttons without actually submitting data then use a combination of DIV/CSS.

Fixed positioned div within a relative parent div

Sample solution. Check, if this is what you need.

<div class="container">
   <div class="relative">      
      <div class="absolute"></div>      
      <div class="content">
        <p>
          Content here
        </p>
      </div>
    </div>
 </div>

And for CSS

.relative { 
  position: relative;
}

.absolute {
  position: absolute;
  top: 15px;
  left: 25px;   
}

See it on codepen https://codepen.io/FelySpring/pen/jXENXY

Is there Unicode glyph Symbol to represent "Search"

Use the ? symbol (encoded as &#9906; or &#x26B2;), and rotate it to achieve the desired effect:

<div style="-webkit-transform: rotate(45deg); 
               -moz-transform: rotate(45deg); 
                 -o-transform: rotate(45deg);
                    transform: rotate(45deg);">
    &#9906;
</div>

It rotates a symbol :)

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

This worked perfectly for me : sValue = sValue.trim().replaceAll("\\s+", " ");

Improve subplot size/spacing with many subplots in matplotlib

I found that subplots_adjust(hspace = 0.001) is what ended up working for me. When I use space = None, there is still white space between each plot. Setting it to something very close to zero however seems to force them to line up. What I've uploaded here isn't the most elegant piece of code, but you can see how the hspace works.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tic

fig = plt.figure()

x = np.arange(100)
y = 3.*np.sin(x*2.*np.pi/100.)

for i in range(5):
    temp = 510 + i
    ax = plt.subplot(temp)
    plt.plot(x,y)
    plt.subplots_adjust(hspace = .001)
    temp = tic.MaxNLocator(3)
    ax.yaxis.set_major_locator(temp)
    ax.set_xticklabels(())
    ax.title.set_visible(False)

plt.show()

enter image description here

Change a HTML5 input's placeholder color with CSS

You can use this for input and focus style:

input::-webkit-input-placeholder  { color:#666;}
input:-moz-placeholder  { color:#666;}
input::-moz-placeholder { color:#666;}
input:-ms-input-placeholder  { color:#666;}
/* focus */
input:focus::-webkit-input-placeholder { color:#eee; }
input:focus:-moz-placeholder { color:#eee } /* FF 4-18 */
input:focus::-moz-placeholder { color:#eee } /* FF 19+ */
input:focus:-ms-input-placeholder { color:#eee } /* IE 10+ */

How to use mysql JOIN without ON condition?

MySQL documentation covers this topic.

Here is a synopsis. When using join or inner join, the on condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join. Similarly, you can use an on clause with cross join, which also differs from standard SQL.

A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.

In practice, if you want to do a cross join, then use cross join:

from A cross join B

is much better than:

from A, B

and:

from A join B -- with no on clause

The on clause is required for a right or left outer join, so the discussion is not relevant for them.

If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.