Programs & Examples On #Vimeo

Vimeo is a video-sharing website on which users can upload, share, and view videos.

Get img thumbnails from Vimeo?

If you don't need an automated solution, you can find the thumbnail URL by entering the vimeo ID here: http://video.depone.eu/

Android: how to handle button click

Option 1 and 2 involves using inner class that will make the code kind of clutter. Option 2 is sort of messy because there will be one listener for every button. If you have small number of button, this is okay. For option 4 I think this will be harder to debug as you will have to go back and fourth the xml and java code. I personally use option 3 when I have to handle multiple button clicks.

Convert a String to int?

So basically you want to convert a String into an Integer right! here is what I mostly use and that is also mentioned in official documentation..

fn main() {

    let char = "23";
    let char : i32 = char.trim().parse().unwrap();
    println!("{}", char + 1);

}

This works for both String and &str Hope this will help too.

How to disable an input box using angular.js

<input data-ng-model="userInf.username"  class="span12 editEmail" type="text"  placeholder="[email protected]"  pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" required ng-disabled="true"/>

problem with php mail 'From' header

It turns out the original poster's server (blueHost) has a FAQ concerning this very question.

Article 206.


This is because our servers require you (or your script) to use a properly formatted, valid From: field in the email's header. If the From: field is not formatted correctly, empty or the email address does not exist in the cPanel, the From: address will be changed to username@box###.bluehost.com.

You must change the script you are using to correctly use a valid From: header.

Examples of headers that should work would be:

From: [email protected]
From: "user" <[email protected]>

Examples of headers that will NOT work:

From: "[email protected]"
From: user @ domain.com
From: [email protected] <[email protected]>

Our servers will not accept the name for the email address and the email address to be the same. It will not accept a double declaration of the email address.

For scripts such as Joomla and Wordpress, you will need to follow their documentation for formatting the from fields properly. Wordpress will require the Mail From plugin.

Note: The email address you use must be a valid created account in the cPanel.

After installing with pip, "jupyter: command not found"

Here what I did on Linux mint 19:

I installed jupyter with:

pip install jupyter

and command:

jupyter notebook

didn't work, so with:

sudo apt install jupyter-notebook

I fixed the issue, jupyter notebook worked then.

How to create a directory if it doesn't exist using Node.js?

The mkdir method has the ability to recursively create any directories in a path that don't exist, and ignore the ones that do.

From the Node v10/11 docs:

// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
    if (err) throw err;
});

NOTE: You'll need to import the built-in fs module first.

Now here's a little more robust example that leverages native ES Modules (with flag enabled and .mjs extension), handles non-root paths, and accounts for full pathnames:

import fs from 'fs';
import path from 'path';

createDirectories(pathname) {
   const __dirname = path.resolve();
   pathname = pathname.replace(/^\.*\/|\/?[^\/]+\.[a-z]+|\/$/g, ''); // Remove leading directory markers, and remove ending /file-name.extension
   fs.mkdir(path.resolve(__dirname, pathname), { recursive: true }, e => {
       if (e) {
           console.error(e);
       } else {
           console.log('Success');
       }
    });
}

You can use it like createDirectories('/components/widget/widget.js');.

And of course, you'd probably want to get more fancy by using promises with async/await to leverage file creation in a more readable synchronous-looking way when the directories are created; but, that's beyond the question's scope.

Access parent DataContext from DataTemplate

Yes, you can solve it using the ElementName=Something as suggested by Juve.

BUT!

If a child element (on which you use this kind of binding) is a user control which uses the same element name as you specify in the parent control, then the binding goes to the wrong object!!

I know this post is not a solution but I thought everyone who uses the ElementName in the binding should know this, since it's a possible runtime bug.

<UserControl x:Class="MyNiceControl"
             x:Name="TheSameName">
   the content ...
</UserControl>

<UserControl x:Class="AnotherUserControl">
        <ListView x:Name="TheSameName">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <MyNiceControl Width="{Binding DataContext.Width, ElementName=TheSameName}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</UserControl>

How to Check whether Session is Expired or not in asp.net

Check if it is null or not e.g

if(Session["mykey"] != null)
{
  // Session is not expired
}
else
{
  //Session is expired
}

How do I delete a local repository in git?

Delete the .git directory in the root-directory of your repository if you only want to delete the git-related information (branches, versions).

If you want to delete everything (git-data, code, etc), just delete the whole directory.

.git directories are hidden by default, so you'll need to be able to view hidden files to delete it.

How to know if a DateTime is between a DateRange in C#

Following on from Sergey's answer, I think this more generic version is more in line with Fowler's Range idea, and resolves some of the issues with that answer such as being able to have the Includes methods within a generic class by constraining T as IComparable<T>. It's also immutable like what you would expect with types that extend the functionality of other value types like DateTime.

public struct Range<T> where T : IComparable<T>
{
    public Range(T start, T end)
    {
        Start = start;
        End = end;
    }

    public T Start { get; }

    public T End { get; }

    public bool Includes(T value) => Start.CompareTo(value) <= 0 && End.CompareTo(value) >= 0;

    public bool Includes(Range<T> range) => Start.CompareTo(range.Start) <= 0 && End.CompareTo(range.End) >= 0;
}

How to figure out the SMTP server host?

generally smtp servers name are smtp.yourdomain.com or mail.yourdomain.com open command prompt try to run following two commands

  1. >ping smtp.yourdomain.com
  2. >ping mail.yourdomain.com

you will most probably get response from any one from the above two commands.and that will be your smtp server

If this doesn't work open your cpanel --> go to your mailing accounts -- > click on configure mail account -- > there somewhere in the page you will get the information about your smtp server

it will be written like this way may be :

Incoming Server:    mail.yourdomain.com
IMAP Port: ---
POP3 Port: ---
Outgoing Server:    mail.yourdomain.com
SMTP Port: ---

How to use PHP's password_hash to hash and verify passwords

Using password_hash is the recommended way to store passwords. Don't separate them to DB and files.

Let's say we have the following input:

$password = $_POST['password'];

You first hash the password by doing this:

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

Then see the output:

var_dump($hashed_password);

As you can see it's hashed. (I assume you did those steps).

Now you store this hashed password in your database, ensuring your password column is large enough to hold the hashed value (at least 60 characters or longer). When a user asks to log them in, you check the password input with this hash value in the database, by doing this:

// Query the database for username and password
// ...

if(password_verify($password, $hashed_password)) {
    // If the password inputs matched the hashed password in the database
    // Do something, you know... log them in.
} 

// Else, Redirect them back to the login page.

Official Reference

How to Check if value exists in a MySQL database

SELECT
    IF city='C7'
    THEN city
    ELSE 'somethingelse'
    END as `city`
FROM `table` WHERE `city` = 'c7'

Access denied for user 'root'@'localhost' with PHPMyAdmin

Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:

$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

Merge DLL into EXE?

I answered a similar question for VB.NET. It shouldn't however be too hard to convert. You embedd the DLL's into your Ressource folder and on the first usage, the AppDomain.CurrentDomain.AssemblyResolve event gets fired.

If you want to reference it during development, just add a normal DLL reference to your project.

Embedd a DLL into a project

Submit form using a button outside the <form> tag

A solution that works great for me, is still missing here. It requires having a visually hidden <submit> or <input type="submit"> element whithin the <form>, and an associated <label> element outside of it. It would look like this:

<form method="get" action="something.php">
     <input type="text" name="name" />
     <input type="submit" id="submit-form" class="hidden" />
</form>

<label for="submit-form" tabindex="0">Submit</label>

Now this link enables you to 'click' the form <submit> element by clicking the <label> element.

Laravel Eloquent - distinct() and count() not working properly together

A more generic answer that would have saved me time, and hopefully others:

Does not work (returns count of all rows):

DB::table('users')
            ->select('first_name')
            ->distinct()
            ->count();

The fix:

DB::table('users')
            ->distinct()
            ->count('first_name');

nodeJS - How to create and read session with express

I need to point out here that you're incorrectly adding middleware to the application. The app.use calls should not be done within the app.get request handler, but outside of it. Simply call them directly after createServer, or take a look at the other examples in the docs.

The secret you pass to express.session should be a string constant, or perhaps something taken from a configuration file. Don't feed it something the client might know, that's actually dangerous. It's a secret only the server should know about.

If you want to store the email address in the session, simply do something along the lines of:

req.session.email = req.param('email');

With that out of the way...


If I understand correctly, what you're trying to do is handle one or more HTTP requests and keep track of a session, then later on open a Socket.IO connection from which you need the session data as well.

What's tricky about this problem is that Socket.IO's means of making the magic work on any http.Server is by hijacking the request event. Thus, Express' (or rather Connect's) session middleware is never called on the Socket.IO connection.

I believe you can make this work, though, with some trickery.

You can get to Connect's session data; you simply need to get a reference to the session store. The easiest way to do that is to create the store yourself before calling express.session:

// A MemoryStore is the default, but you probably want something
// more robust for production use.
var store = new express.session.MemoryStore;
app.use(express.session({ secret: 'whatever', store: store }));

Every session store has a get(sid, callback) method. The sid parameter, or session ID, is stored in a cookie on the client. The default name of that cookie is connect.sid. (But you can give it any name by specifying a key option in your express.session call.)

Then, you need to access that cookie on the Socket.IO connection. Unfortunately, Socket.IO doesn't seem to give you access to the http.ServerRequest. A simple work around would be to fetch the cookie in the browser, and send it over the Socket.IO connection.

Code on the server would then look something like the following:

var io      = require('socket.io'),
    express = require('express');

var app    = express.createServer(),
    socket = io.listen(app),
    store  = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({ secret: 'something', store: store }));

app.get('/', function(req, res) {
  var old = req.session.email;
  req.session.email = req.param('email');

  res.header('Content-Type', 'text/plain');
  res.send("Email was '" + old + "', now is '" + req.session.email + "'.");
});

socket.on('connection', function(client) {
  // We declare that the first message contains the SID.
  // This is where we handle the first message.
  client.once('message', function(sid) {
    store.get(sid, function(err, session) {
      if (err || !session) {
        // Do some error handling, bail.
        return;
      }

      // Any messages following are your chat messages.
      client.on('message', function(message) {
        if (message.email === session.email) {
          socket.broadcast(message.text);
        }
      });
    });
  });
});

app.listen(4000);

This assumes you only want to read an existing session. You cannot actually create or delete sessions, because Socket.IO connections may not have a HTTP response to send the Set-Cookie header in (think WebSockets).

If you want to edit sessions, that may work with some session stores. A CookieStore wouldn't work for example, because it also needs to send a Set-Cookie header, which it can't. But for other stores, you could try calling the set(sid, data, callback) method and see what happens.

Not receiving Google OAuth refresh token

Using offline access and prompt:consent worked well to me:

   auth2 = gapi.auth2.init({
                    client_id: '{cliend_id}' 
   });

   auth2.grantOfflineAccess({prompt:'consent'}).then(signInCallback); 

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

How to make a form close when pressing the escape key?

If you have a cancel button on your form, you can set the Form.CancelButton property to that button and then pressing escape will effectively 'click the button'.

If you don't have such a button, check out the Form.KeyPreview property.

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

Try this (it's VB-Code :-):

Try

Catch exp As WebException
  Dim sResponse As String = New StreamReader(exp.Response.GetResponseStream()).ReadToEnd
End Try

What's a good (free) visual merge tool for Git? (on windows)

I've also used Meld. It's written in python. There is an official installer for Windows that works well.

Install it and then set it as your default mergetool.

$ git config --global merge.tool "meld"
$ git config --global mergetool.meld.path "C:\Program Files (x86)\Meld\Meld.exe"

If using a GUI GIT client, try the following (instructions for SourceTree, adjust accordingly)

  • In SourceTree, go to Tools/Options/Diff
  • In External Diff Tool, choose Custom
  • Enter C:\Program Files (x86)\Meld\meld.exe in Diff Command and $LOCAL $REMOTE in Arguments
  • In Merge Tool, choose Custom
  • Enter C:\Program Files (x86)\Meld\meld.exe in Diff Command and $LOCAL $MERGED $REMOTE in Arguments

AngularJs: Reload page

Angular 2+

I found this while searching for Angular 2+, so here is the way:

$window.location.reload();

What Language is Used To Develop Using Unity

Unity3d supports C#, Boo and JavaScript. The framework translates this into its intermediate format and later to the desired platform (IOS/Android/Linux/Windows)

Keep in mind, C# Scripts are compiled first, followed by JS and Boo Hence if you want a C# script to interact with a JS, you ll have to keep the JS in the Standard Assets Folder.

How do I manually configure a DataSource in Java?

Basically in JDBC most of these properties are not configurable in the API like that, rather they depend on implementation. The way JDBC handles this is by allowing the connection URL to be different per vendor.

So what you do is register the driver so that the JDBC system can know what to do with the URL:

 DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());

Then you form the URL:

 String url = "jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]"

And finally, use it to get a connection:

 Connection c = DriverManager.getConnection(url);

In more sophisticated JDBC, you get involved with connection pools and the like, and application servers often have their own way of registering drivers in JNDI and you look up a DataSource from there, and call getConnection on it.

In terms of what properties MySQL supports, see here.

EDIT: One more thought, technically just having a line of code which does Class.forName("com.mysql.jdbc.Driver") should be enough, as the class should have its own static initializer which registers a version, but sometimes a JDBC driver doesn't, so if you aren't sure, there is little harm in registering a second one, it just creates a duplicate object in memeory.

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

If you trust the host, either add the valid certificate, specify --no-check-certificate or add:

check_certificate = off

into your ~/.wgetrc.

In some rare cases, your system time could be out-of-sync therefore invalidating the certificates.

How to get primary key column in Oracle?

Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;

(This will list the primary key and then)

Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’; 

(This will give you the column, here PK_XYZ is the primay key name)

How do you create a static class in C++?

One case where namespaces may not be so useful for achieving "static classes" is when using these classes to achieve composition over inheritance. Namespaces cannot be friends of classes and so cannot access private members of a class.

class Class {
 public:
  void foo() { Static::bar(*this); }    

 private:
  int member{0};
  friend class Static;
};    

class Static {
 public:
  template <typename T>
  static void bar(T& t) {
    t.member = 1;
  }
};

How may I sort a list alphabetically using jQuery?

improvement based on Jeetendra Chauhan's answer

$('ul.menu').each(function(){
    $(this).children('li').sort((a,b)=>a.innerText.localeCompare(b.innerText)).appendTo(this);
});

why i consider it an improvement:

  1. using each to support running on more than one ul

  2. using children('li') instead of ('ul li') is important because we only want to process direct children and not descendants

  3. using the arrow function (a,b)=> just looks better (IE not supported)

  4. using vanilla innerText instead of $(a).text() for speed improvement

  5. using vanilla localeCompare improves speed in case of equal elements (rare in real life usage)

  6. using appendTo(this) instead of using another selector will make sure that even if the selector catches more than one ul still nothing breaks

cvc-elt.1: Cannot find the declaration of element 'MyElement'

I had this error for my XXX element and it was because my XSD was wrongly formatted according to javax.xml.bind v2.2.11 . I think it's using an older XSD format but I didn't bother to confirm.

My initial wrong XSD was alike the following:

<xs:element name="Document" type="Document"/>
...
<xs:complexType name="Document">
    <xs:sequence>
        <xs:element name="XXX" type="XXX_TYPE"/>
    </xs:sequence>
</xs:complexType>

The good XSD format for my migration to succeed was the following:

<xs:element name="Document">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="XXX"/>
        </xs:sequence>
    </xs:complexType>        
</xs:element>
...
<xs:element name="XXX" type="XXX_TYPE"/>

And so on for every similar XSD nodes.

Difference between java HH:mm and hh:mm on SimpleDateFormat

h/H = 12/24 hours means you will write hh:mm = 12 hours format and HH:mm = 24 hours format

How to choose multiple files using File Upload Control?

There are other options you can use these controls which have multiple upload options and these controls have also Ajax support

1) Flajxian
2) Valums
3) Subgurim FileUpload

JavaScript Editor Plugin for Eclipse

Complete the following steps in Eclipse to get plugins for JavaScript files:

  1. Open Eclipse -> Go to "Help" -> "Install New Software"
  2. Select the repository for your version of Eclipse. I have Juno so I selected http://download.eclipse.org/releases/juno
  3. Expand "Programming Languages" -> Check the box next to "JavaScript Development Tools"
  4. Click "Next" -> "Next" -> Accept the Terms of the License Agreement -> "Finish"
  5. Wait for the software to install, then restart Eclipse (by clicking "Yes" button at pop up window)
  6. Once Eclipse has restarted, open "Window" -> "Preferences" -> Expand "General" and "Editors" -> Click "File Associations" -> Add ".js" to the "File types:" list, if it is not already there
  7. In the same "File Associations" dialog, click "Add" in the "Associated editors:" section
  8. Select "Internal editors" radio at the top
  9. Select "JavaScript Viewer". Click "OK" -> "OK"

To add JavaScript Perspective: (Optional)
10. Go to "Window" -> "Open Perspective" -> "Other..."
11. Select "JavaScript". Click "OK"

To open .html or .js file with highlighted JavaScript syntax:
12. (Optional) Select JavaScript Perspective
13. Browse and Select .html or .js file in Script Explorer in [JavaScript Perspective] (Or Package Explorer [Java Perspective] Or PyDev Package Explorer [PyDev Perspective] Don't matter.)
14. Right-click on .html or .js file -> "Open With" -> "Other..."
15. Select "Internal editors"
16. Select "Java Script Editor". Click "OK" (see JavaScript syntax is now highlighted )

How can I select the first day of a month in SQL?

Get First Date and Last Date in the Date we pass as parameter in SQL

     @date DATETIME
    SELECT @date = GETDATE()
    SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@date)-1),@date),105) AS value,
    'First Day of Current Month' AS name
    UNION
    SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@date))),
    DATEADD(mm,1,@date)),105),
    'Last Day of Current Month'
    GO


      **OutPut**

12/01/2019  First Day of Current Month
12/31/2019  Last Day of Current Month

eslint: error Parsing error: The keyword 'const' is reserved

If using Visual Code one option is to add this to the settings.json file:

"eslint.options": {
    "useEslintrc": false,
    "parserOptions": {
        "ecmaVersion": 2017
    },
    "env": {
        "es6": true
    }
}

How can I use UserDefaults in Swift?

ref: NSUserdefault objectTypes

Swift 3 and above

Store

UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key")  //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject

Retrieve

 UserDefaults.standard.bool(forKey: "Key")
 UserDefaults.standard.integer(forKey: "Key")
 UserDefaults.standard.string(forKey: "Key")

Remove

 UserDefaults.standard.removeObject(forKey: "Key")

Remove all Keys

 if let appDomain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: appDomain)
 }

Swift 2 and below

Store

NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "yourkey")
NSUserDefaults.standardUserDefaults().synchronize()

Retrieve

  var returnValue: [NSString]? = NSUserDefaults.standardUserDefaults().objectForKey("yourkey") as? [NSString]

Remove

 NSUserDefaults.standardUserDefaults().removeObjectForKey("yourkey")


Register

registerDefaults: adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a "fallback" value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them.

Default values from Defaults Configuration Files will automatically be registered.

for example detect the app from launch , create the struct for save launch

struct DetectLaunch {
static let keyforLaunch = "validateFirstlunch"
static var isFirst: Bool {
    get {
        return UserDefaults.standard.bool(forKey: keyforLaunch)
    }
    set {
        UserDefaults.standard.set(newValue, forKey: keyforLaunch)
    }
}
}

Register default values on app launch:

UserDefaults.standard.register(defaults: [
        DetectLaunch.isFirst: true
    ])

remove the value on app termination:

func applicationWillTerminate(_ application: UIApplication) {
    DetectLaunch.isFirst = false

}

and check the condition as

if DetectLaunch.isFirst {
  // app launched from first
}

UserDefaults suite name

another one property suite name, mostly its used for App Groups concept, the example scenario I taken from here :

The use case is that I want to separate my UserDefaults (different business logic may require Userdefaults to be grouped separately) by an identifier just like Android's SharedPreferences. For example, when a user in my app clicks on logout button, I would want to clear his account related defaults but not location of the the device.

let user = UserDefaults(suiteName:"User")

use of userDefaults synchronize, the detail info has added in the duplicate answer.

Arrays.asList() of an array

this is from Java API "sort

public static void sort(List list) Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list)."

it has to do with implementing the Comparable interface

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

In my case, I was using a View that I´ve converted to partial view and I forgot to remove the template from "@section scripts". Removing the section block, solved my problem. This is because the sections aren´t rendered in partial views.

C++ - Decimal to binary converting

The following is a recursive function which takes a positive integer and prints its binary digits to the console.

Alex suggested, for efficiency, you may want to remove printf() and store the result in memory... depending on storage method result may be reversed.

/**
 * Takes a unsigned integer, converts it into binary and prints it to the console.
 * @param n the number to convert and print
 */
void convertToBinary(unsigned int n)
{
    if (n / 2 != 0) {
        convertToBinary(n / 2);
    }
    printf("%d", n % 2);
}

Credits to UoA ENGGEN 131

*Note: The benefit of using an unsigned int is that it can't be negative.

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

An alternative to jcoby's proposal would be:

class NilClass
  def nil_or_empty?
    true
  end
end

class String
  def nil_or_empty?
    empty?
  end
end

ORACLE and TRIGGERS (inserted, updated, deleted)

From Using Triggers:

Detecting the DML Operation That Fired a Trigger

If more than one type of DML operation can fire a trigger (for example, ON INSERT OR DELETE OR UPDATE OF Emp_tab), the trigger body can use the conditional predicates INSERTING, DELETING, and UPDATING to check which type of statement fire the trigger.

So

IF DELETING THEN ... END IF;

should work for your case.

How to check how many letters are in a string in java?

If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:

String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e

The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc

sample.codePointCount(0, sample.length()) // returns 5

http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

Android intent for playing video?

from the debug info, it seems that the VideoIntent from the MainActivity cannot send the path of the video to VideoActivity. It gives a NullPointerException error from the uriString. I think some of that code from VideoActivity:

Intent myIntent = getIntent();
String uri = myIntent.getStringExtra("uri");
Bundle b = myIntent.getExtras();

startVideo(b.getString(uri));

Cannot receive the uri from here:

public void playsquirrelmp4(View v) {
    Intent VideoIntent = (new Intent(this, VideoActivity.class));
    VideoIntent.putExtra("android.resource://" + getPackageName()
        + "/"+   R.raw.squirrel, uri);
    startActivity(VideoIntent);
}

Get total number of items on Json object?

That's an Object and you want to count the properties of it.

Object.keys(jsonArray).length

References:

What is the difference between XML and XSD?

XSD:
XSD (XML Schema Definition) specifies how to formally describe the elements in an Extensible Markup Language (XML) document.
Xml:
XML was designed to describe data.It is independent from software as well as hardware.
It enhances the following things.
-Data sharing.
-Platform independent.
-Increasing the availability of Data.

Differences:

  1. XSD is based and written on XML.

  2. XSD defines elements and structures that can appear in the document, while XML does not.

  3. XSD ensures that the data is properly interpreted, while XML does not.

  4. An XSD document is validated as XML, but the opposite may not always be true.

  5. XSD is better at catching errors than XML.

An XSD defines elements that can be used in the documents, relating to the actual data with which it is to be encoded.
for eg:
A date that is expressed as 1/12/2010 can either mean January 12 or December 1st. Declaring a date data type in an XSD document, ensures that it follows the format dictated by XSD.

#1292 - Incorrect date value: '0000-00-00'

You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.

Find the division remainder of a number

You can find remainder using modulo operator Example

a=14
b=10
print(a%b)

It will print 4

Convert Python ElementTree to string

Non-Latin Answer Extension

Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.

Input

xml = ElementTree.fromstring('<Person Name="???" />')
xml = ElementTree.Element("Person", Name="???")  # Read Note about Python 2

NOTE: In Python 2, when calling the toString(...) code, assigning xml with ElementTree.Element("Person", Name="???")will raise an error...

UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 0: ordinal not in range(128)

Output

ElementTree.tostring(xml)
# Python 3 (???): b'<Person Name="&#53356;&#47532;&#49828;" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />


ElementTree.tostring(xml, encoding='unicode')
# Python 3 (???): <Person Name="???" />             <-------- Python 3
# Python 3 (John): <Person Name="John" />

# Python 2 (???): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (???): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="???" />             <-------- Python 2
# Python 2 (John): <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 3 (John): <Person Name="John" />

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />

How to use a BackgroundWorker?

You can update progress bar only from ProgressChanged or RunWorkerCompleted event handlers as these are synchronized with the UI thread.

The basic idea is. Thread.Sleep just simulates some work here. Replace it with your real routing call.

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.WorkerReportsProgress = true;
}

private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);
    }
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

What is /dev/null 2>&1?

/dev/null is a standard file that discards all you write to it, but reports that the write operation succeeded.

1 is standard output and 2 is standard error.

2>&1 redirects standard error to standard output. &1 indicates file descriptor (standard output), otherwise (if you use just 1) you will redirect standard error to a file named 1. [any command] >>/dev/null 2>&1 redirects all standard error to standard output, and writes all of that to /dev/null.

Best Practice: Access form elements by HTML id or name attribute?

Form 2 is ok, and form 3 is also recommended.
Redundancy between name and id is caused by the need to keep compatibility, on html 5 some elements (as img, form, iframe and such) will lose their "name" attribute, and it's recommended to use just their id to reference them from now on :)

What does jQuery.fn mean?

jQuery.fn is defined shorthand for jQuery.prototype. From the source code:

jQuery.fn = jQuery.prototype = {
    // ...
}

That means jQuery.fn.jquery is an alias for jQuery.prototype.jquery, which returns the current jQuery version. Again from the source code:

// The current version of jQuery being used
jquery: "@VERSION",

WMI "installed" query different from add/remove programs list?

Installed products consist of installed software elements and features so it's worth checking wmic alias's for PRODUCT as well as checking SOFTWAREELEMENT and SOFTWAREFEATURE:

wmic product get name,version

wmic softwareelement get name,version

wmic softwarefeature get name,version

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

It is not python related but for C# or dotnet users you might specify driver version in nuget packages. For instance Selenium.WebDriver.ChromeDriver is a good start point. It should match browser version. In chrome you can check version by accessing

chrome://settings/help

Be informed that it will also affect chrome version on pipeline agents and other developer's computers.

How to get past the login page with Wget?

You can install this plugin in Firefox: https://addons.mozilla.org/en-US/firefox/addon/cliget/?src=cb-dl-toprated Start downloading what you want and click on the plugin. It gives you the whole command either for wget or curl to download the file on the serer. Very easy!

How to make a submit out of a <a href...>...</a> link?

Something like this page ?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>BSO Communication</title>

<style type="text/css">
.submit {
    border : 0;
    background : url(ok.gif) left top no-repeat;
    height : 24px;
    width : 24px;
    cursor : pointer;
    text-indent : -9999px;
}
html:first-child .submit {
    padding-left : 1000px;
}
</style>
<!--[if IE]>
<style type="text/css">
.submit {
    text-indent : 0;
    color : expression(this.value = '');
}
</style>
<![endif]-->
</head>

<body>
    <h1>Display input submit as image with CSS</h1>

    <p>Take a look at <a href="/2007/07/26/afficher-un-input-submit-comme-une-image/">the related article</a> (in french).</p>
    <form action="" method="get">
        <fieldset>
            <legend>Some form</legend>
            <p class="field">
                <label for="input">Some value</label>

                <input type="text" id="input" name="value" />
                <input type="submit" class="submit" />
            </p>
        </fieldset>
    </form>

    <hr />
    <p>This page is part of the <a href="http://www.bsohq.fr">BSO Communication blog</a>.</p>

</body>
</html>

Nesting CSS classes

Not possible with vanilla CSS. However you can use something like:

Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.

Or

Rather than constructing long selector names to specify inheritance, in Less you can simply nest selectors inside other selectors. This makes inheritance clear and style sheets shorter.

Example:

#header {
  color: red;
  a {
    font-weight: bold;
    text-decoration: none;
  }
}

Should have subtitle controller already set Mediaplayer error Android

To remove message on logcat, i add a subtitle to track. On windows, right click on track -> Property -> Details -> insert a text on subtitle. Done :)

How to insert close button in popover for Bootstrap

I found the code below very useful (taken from https://www.emanueletessore.com/twitter-bootstrap-popover-add-close-button/):

$('[data-toggle="popover"]').popover({
  title: function(){
    return $(this).data('title')+'<span class="close" style="margin-top: -5px">&times;</span>';
  }
}).on('shown.bs.popover', function(e){
  var popover = $(this);
  $(this).parent().find('div.popover .close').on('click', function(e){
    popover.popover('hide');
  });
});

How to Convert the value in DataTable into a string array in c#

Perhaps something like this, assuming that there are many of these rows inside of the datatable and that each row is row:

List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
 MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}

You could then access one:

MyStringArrays.ElementAt(0)[1]

If you use linqpad, here is a very simple scenario of your example:

class Datatable
{
 public List<data> rows { get; set; }
 public Datatable(){
  rows = new List<data>();
 }
}

class data
{
 public string Name { get; set; }
 public string Address { get; set; }
 public int Age { get; set; }
}

void Main()
{
 var datatable = new Datatable();
 var r = new data();
 r.Name = "Jim";
 r.Address = "USA";
 r.Age = 23;
 datatable.rows.Add(r);
 List<string[]> MyStringArrays = new List<string[]>();
 foreach( var row in datatable.rows )//or similar
 {
  MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
 }
 var s = MyStringArrays.ElementAt(0)[1];
 Console.Write(s);//"USA"
}

Show Hide div if, if statement is true

This does not need jquery, you could set a variable inside the if and use it in html or pass it thru your template system if any

<?php
$showDivFlag=false
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
if ($numrows > 0){
    $fvisit = mysql_fetch_array($result3);
    $showDivFlag=true;
 }else {

 }

?>

later in html

  <div id="results" <?php if ($showDivFlag===false){?>style="display:none"<?php } ?>>

How to use putExtra() and getExtra() for string data

It is very easy to implement intent in Android.. It takes you to move from one activity to another activity,we have to two method putExtra(); and getExtra();Now I am showing you the example..

    Intent intent = new Intent(activity_registration.this, activity_Login.class);
                intent.putExtra("AnyKeyName", Email.getText().toString());  // pass your values and retrieve them in the other Activity using AnyKeyName
                        startActivity(intent);

Now we have to get the value from AnyKeyName parameter,the below mentioned code will help in doing this

       String data = getIntent().getExtras().getString("AnyKeyName");
        textview.setText(data);

We can easily set the receiving value from Intent,wherever we required.

How can I increase the JVM memory?

Right click on project -> Run As -> Run Configurations..-> Select Arguments tab -> In VM Arguments you can increase your JVM memory allocation. Java HotSpot document will help you to setup your VM Argument HERE

I will not prefer to make any changes into eclipse.ini as minor mistake cause lot of issues. It's easier to play with VM Args

Docker official registry (Docker Hub) URL

You're able to get the current registry-url using docker info:

...
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
...

That's also the url you may use to run your self hosted-registry:

docker run -d -p 5000:5000 --name registry -e REGISTRY_PROXY_REMOTEURL=https://index.docker.io registry:2

Grep & use it right away:

$ echo $(docker info | grep -oP "(?<=Registry: ).*")
https://index.docker.io/v1/

How to redirect Valgrind's output to a file?

valgrind --log-file="filename"

How to write to the Output window in Visual Studio?

OutputDebugString function will do it.

example code

    void CClass::Output(const char* szFormat, ...)
{
    char szBuff[1024];
    va_list arg;
    va_start(arg, szFormat);
    _vsnprintf(szBuff, sizeof(szBuff), szFormat, arg);
    va_end(arg);

    OutputDebugString(szBuff);
}

Hash function for a string

-- The way to go these days --

Use SipHash. For your own protection.

-- Old and Dangerous --

unsigned int RSHash(const std::string& str)
{
    unsigned int b    = 378551;
    unsigned int a    = 63689;
    unsigned int hash = 0;

    for(std::size_t i = 0; i < str.length(); i++)
    {
        hash = hash * a + str[i];
        a    = a * b;
    }

    return (hash & 0x7FFFFFFF);
 }

 unsigned int JSHash(const std::string& str)
 {
      unsigned int hash = 1315423911;

      for(std::size_t i = 0; i < str.length(); i++)
      {
          hash ^= ((hash << 5) + str[i] + (hash >> 2));
      }

      return (hash & 0x7FFFFFFF);
 }

Ask google for "general purpose hash function"

Position Absolute + Scrolling

So gaiour is right, but if you're looking for a full height item that doesn't scroll with the content, but is actually the height of the container, here's the fix. Have a parent with a height that causes overflow, a content container that has a 100% height and overflow: scroll, and a sibling then can be positioned according to the parent size, not the scroll element size. Here is the fiddle: http://jsfiddle.net/M5cTN/196/

and the relevant code:

html:

<div class="container">
  <div class="inner">
    Lorem ipsum ...
  </div>
  <div class="full-height"></div>
</div>

css:

.container{
  height: 256px;
  position: relative;
}
.inner{
  height: 100%;
  overflow: scroll;
}
.full-height{
  position: absolute;
  left: 0;
  width: 20%;
  top: 0;
  height: 100%;
}

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

Comparing two arrays & get the values which are not common

PS > $c = Compare-Object -ReferenceObject (1..5) -DifferenceObject (1..6) -PassThru
PS > $c
6

Can I set the cookies to be used by a WKWebView?

set cookie

self.webView.evaluateJavaScript("document.cookie='access_token=your token';domain='your domain';") { (data, error) -> Void in
        self.webView.reload()
}

delete cookie

self.webView.evaluateJavaScript("document.cookie='access_token=';domain='your domain';") { (data, error) -> Void in
        self.webView.reload()
}

Comparing date part only without comparing time in JavaScript

This JS will change the content after the set date here's the same thing but on w3schools

_x000D_
_x000D_
date1 = new Date()_x000D_
date2 = new Date(2019,5,2) //the date you are comparing_x000D_
_x000D_
date1.setHours(0,0,0,0)_x000D_
_x000D_
var stockcnt = document.getElementById('demo').innerHTML;_x000D_
if (date1 > date2){_x000D_
document.getElementById('demo').innerHTML="yes"; //change if date is > set date (date2)_x000D_
}else{_x000D_
document.getElementById('demo').innerHTML="hello"; //change if date is < set date (date2)_x000D_
}
_x000D_
<p id="demo">hello</p> <!--What will be changed-->_x000D_
<!--if you check back in tomorrow, it will say yes instead of hello... or you could change the date... or change > to <-->
_x000D_
_x000D_
_x000D_

How to return data from PHP to a jQuery ajax call

It's an argument passed to your success function:

$.ajax({
  type: "POST",
  url: "somescript.php",
  datatype: "html",
  data: dataString,
  success: function(data) {
    alert(data);
    }
});

The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)

Circular gradient in android

<!-- Drop Shadow Stack -->
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#00CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#10CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#20CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#30CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#50CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>

<!-- Background -->
<item>
    <shape android:shape="oval">
        <gradient
            android:startColor="@color/colorAccent_1"
            android:centerColor="@color/colorAccent_2"
            android:endColor="@color/colorAccent_3"
            android:angle="45"
            />
        <corners android:radius="3dp" />
    </shape>
</item>

<color name="colorAccent_1">#6f64d6</color>
<color name="colorAccent_2">#7668F8</color>
<color name="colorAccent_3">#6F63FF</color>

Run two async tasks in parallel and collect results in .NET 4.5

You should use Task.Delay instead of Sleep for async programming and then use Task.WhenAll to combine the task results. The tasks would run in parallel.

public class Program
    {
        static void Main(string[] args)
        {
            Go();
        }
        public static void Go()
        {
            GoAsync();
            Console.ReadLine();
        }
        public static async void GoAsync()
        {

            Console.WriteLine("Starting");

            var task1 = Sleep(5000);
            var task2 = Sleep(3000);

            int[] result = await Task.WhenAll(task1, task2);

            Console.WriteLine("Slept for a total of " + result.Sum() + " ms");

        }

        private async static Task<int> Sleep(int ms)
        {
            Console.WriteLine("Sleeping for {0} at {1}", ms, Environment.TickCount);
            await Task.Delay(ms);
            Console.WriteLine("Sleeping for {0} finished at {1}", ms, Environment.TickCount);
            return ms;
        }
    }

How to generate a random String in Java

I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.

public class RandomNumberGenerator {

private static final Set<String> generatedNumbers = new HashSet<String>();

public RandomNumberGenerator() {
}

public static void main(String[] args) {
    final int maxLength = 7;
    final int maxTry = 10;

    for (int i = 0; i < 10; i++) {
        System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry));
    }
}

public static String getRandomId(final int maxLength, final int maxTry) {
    final Random random = new Random(System.nanoTime());
    final int max = (int) Math.pow(10, maxLength);
    final int maxMin = (int) Math.pow(10, maxLength-1);
    int i = 0;
    boolean unique = false;
    int randomId = -1;
    while (i < maxTry) {
        randomId = random.nextInt(max - maxMin - 1) + maxMin;

        synchronized (generatedNumbers) {
            if (generatedNumbers.contains(randomId) == false) {
                unique = true;
                break;
            }
        }
        i++;
    }
    if (unique == false) {
        throw new RuntimeException("Cannot generate unique id!");
    }

    synchronized (generatedNumbers) {
        generatedNumbers.add(String.valueOf(randomId));
    }

    return String.valueOf(randomId);
}

}

Internal vs. Private Access Modifiers

private - encapsulations in class/scope/struct ect'.

internal - encapsulation in assemblies.

Regex number between 1 and 100

Just for the sake of delivering the shortest solution, here is mine:

^([1-9]\d?|100)$

working fiddle

MS-access reports - The search key was not found in any record - on save

Thew problem is because of spaces in the titles(Headers). Remove spaces in all headers and it works fine.

How do I perform an IF...THEN in an SQL SELECT?

 SELECT
   CASE 
      WHEN OBSOLETE = 'N' or InStock = 'Y' THEN 'TRUE' 
      ELSE 'FALSE' 
   END AS Salable,
   * 
FROM PRODUCT

Setting custom UITableViewCells height

in a custom UITableViewCell -controller add this

-(void)layoutSubviews {  

    CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);

    self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
    self.frame = newCellViewFrame;

    [super layoutSubviews];
}

In the UITableView -controller add this

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [indexPath row] * 1.5; // your dynamic height...
}

Add Whatsapp function to website, like sms, tel

Check this link out Launching Your iPhone App Via Custom URL Scheme

and more on the whats up url scheme document

I did a quick mock up and tried it on my iphone with a link like this from a webpage and it opened the app on my iphone.

<a href="whatsapp://send?text=Hello%2C%20World!">whatsapp</a>

I could not try to send a message as I don't have a current Whatsapp account sorry.

Add user name using abid parameter

let's say your whatsapp username was username then it would be

<a href="whatsapp://send?abid=username&text=Hello%2C%20World!">whatsapp</a>

once again sorry I can't test this. Also I have no idea what would happen if the username is the actual user of the current mobile device. eg. You try to whatsapp yourself.

SQLAlchemy: how to filter date field?

from app import SQLAlchemyDB as db

Chance.query.filter(Chance.repo_id==repo_id, 
                    Chance.status=="1", 
                    db.func.date(Chance.apply_time)<=end, 
                    db.func.date(Chance.apply_time)>=start).count()

it is equal to:

select
   count(id)
from
   Chance
where
   repo_id=:repo_id 
   and status='1'
   and date(apple_time) <= end
   and date(apple_time) >= start

wish can help you.

Remove duplicate rows in MySQL

MySQL has restrictions about referring to the table you are deleting from. You can work around that with a temporary table, like:

create temporary table tmpTable (id int);

insert  into tmpTable
        (id)
select  id
from    YourTable yt
where   exists
        (
        select  *
        from    YourTabe yt2
        where   yt2.title = yt.title
                and yt2.company = yt.company
                and yt2.site_id = yt.site_id
                and yt2.id > yt.id
        );

delete  
from    YourTable
where   ID in (select id from tmpTable);

From Kostanos' suggestion in the comments:
The only slow query above is DELETE, for cases where you have a very large database. This query could be faster:

DELETE FROM YourTable USING YourTable, tmpTable WHERE YourTable.id=tmpTable.id

Implementing multiple interfaces with Java - is there a way to delegate?

Unfortunately: NO.

We're all eagerly awaiting the Java support for extension methods

Java: Literal percent sign in printf statement

You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.

String delimiter in string.split method

Pipe (|) is a special character in regex. to escape it, you need to prefix it with backslash (\). But in java, backslash is also an escape character. so again you need to escape it with another backslash. So your regex should be \\|\\| e.g, String[] tokens = myString.split("\\|\\|");

Conditionally formatting cells if their value equals any value of another column

I unable to comment on the top answer, but Excel actually lets you do this without adding the ugly conditional logic.

Conditional formatting is automatically applied to any input that isn't an error, so you can achieve the same effect as:

=NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))

With this:

= MATCH(A1,$B$1:$B$1000,0)))

If the above is applied to your data, A1 will be formatted if it matches any cell in $B$1:$B$1000, as any non-match will return an error.

Unknown Column In Where Clause

select u_name as user_name from users where u_name = "john";

Think of it like this, your where clause evaluates first, to determine which rows (or joined rows) need to be returned. Once the where clause is executed, the select clause runs for it.

To put it a better way, imagine this:

select distinct(u_name) as user_name from users where u_name = "john";

You can't reference the first half without the second. Where always gets evaluated first, then the select clause.

Bash loop ping successful

This can also be done with a timeout:

# Ping until timeout or 1 successful packet
ping -w (timeout) -c 1

mysql update multiple columns with same now()

If you really need to be sure that now() has the same value you can run two queries (that will answer to your second question too, in that case you are asking to update last_monitor = to last_update but last_update hasn't been updated yet)

you could do something like:

mysql> update table set last_update=now() where id=1;
mysql> update table set last_monitor = last_update where id=1;

anyway I think that mysql is clever enough to ask for now() only once per query.

How do I save a stream to a file in C#?

I don't get all of the answers using CopyTo, where maybe the systems using the app might not have been upgraded to .NET 4.0+. I know some would like to force people to upgrade, but compatibility is also nice, too.

Another thing, I don't get using a stream to copy from another stream in the first place. Why not just do:

byte[] bytes = myOtherObject.InputStream.ToArray();

Once you have the bytes, you can easily write them to a file:

public static void WriteFile(string fileName, byte[] bytes)
{
    string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    if (!path.EndsWith(@"\")) path += @"\";

    if (File.Exists(Path.Combine(path, fileName)))
        File.Delete(Path.Combine(path, fileName));

    using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.CreateNew, FileAccess.Write))
    {
        fs.Write(bytes, 0, (int)bytes.Length);
        //fs.Close();
    }
}

This code works as I've tested it with a .jpg file, though I admit I have only used it with small files (less than 1 MB). One stream, no copying between streams, no encoding needed, just write the bytes! No need to over-complicate things with StreamReader if you already have a stream you can convert to bytes directly with .ToArray()!

Only potential downsides I can see in doing it this way is if there's a large file you have, having it as a stream and using .CopyTo() or equivalent allows FileStream to stream it instead of using a byte array and reading the bytes one by one. It might be slower doing it this way, as a result. But it shouldn't choke since the .Write() method of the FileStream handles writing the bytes, and it's only doing it one byte at a time, so it won't clog memory, except that you will have to have enough memory to hold the stream as a byte[] object. In my situation where I used this, getting an OracleBlob, I had to go to a byte[], it was small enough, and besides, there was no streaming available to me, anyway, so I just sent my bytes to my function, above.

Another option, using a stream, would be to use it with Jon Skeet's CopyStream function that was in another post - this just uses FileStream to take the input stream and create the file from it directly. It does not use File.Create, like he did (which initially seemed to be problematic for me, but later found it was likely just a VS bug...).

/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }    
}

public static void WriteFile(string fileName, Stream inputStream)
{
    string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    if (!path.EndsWith(@"\")) path += @"\";

    if (File.Exists(Path.Combine(path, fileName)))
        File.Delete(Path.Combine(path, fileName));

    using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.CreateNew, FileAccess.Write)
    {
        CopyStream(inputStream, fs);
    }

    inputStream.Close();
    inputStream.Flush();
}

Reading a date using DataReader

If the query's column has an appropriate type then

var dateString = MyReader.GetDateTime(MyReader.GetOrdinal("column")).ToString(myDateFormat)

If the query's column is actually a string then see other answers.

Difference between xcopy and robocopy

They are both rubbish! XCOPY was older and unreliable, so Microsoft replaced it with ROBOCOPY, which is still rubbish.

http://answers.microsoft.com/en-us/windows/forum/windows_8-files/robocopy-appears-to-be-broken-in-windows-8/9a7634c4-3a9d-4f2d-97ae-093002a638a9

Don't worry though, it is a long-standing tradition that was started by the original COPY command, which to this day, still needs the /B switch to get it to actually copy properly!

path.join vs path.resolve with __dirname

Yes there is a difference between the functions but the way you are using them in this case will result in the same outcome.

path.join returns a normalized path by merging two paths together. It can return an absolute path, but it doesn't necessarily always do so.

For instance:

path.join('app/libs/oauth', '/../ssl')

resolves to app/libs/ssl

path.resolve, on the other hand, will resolve to an absolute path.

For instance, when you run:

path.resolve('bar', '/foo');

The path returned will be /foo since that is the first absolute path that can be constructed.

However, if you run:

path.resolve('/bar/bae', '/foo', 'test');

The path returned will be /foo/test again because that is the first absolute path that can be formed from right to left.

If you don't provide a path that specifies the root directory then the paths given to the resolve function are appended to the current working directory. So if your working directory was /home/mark/project/:

path.resolve('test', 'directory', '../back');

resolves to

/home/mark/project/test/back

Using __dirname is the absolute path to the directory containing the source file. When you use path.resolve or path.join they will return the same result if you give the same path following __dirname. In such cases it's really just a matter of preference.

Bind TextBox on Enter-key press

Answered here quite elegantly using attached behaviors, my preferred method for almost anything.

WPF how to make textbox lose focus after hitting enter

What is a good alternative to using an image map generator?

This one is in my opinion the best one for online (offline however dreamweaver is best): http://www.maschek.hu/imagemap/imgmap

Apache won't run in xampp

There are 2 ways to solving this problem.

  1. If you want to run Apache in another port then:Replace in xampp/apache/conf/httpd.conf "ServerName localhost:80" by "ServerName localhost:81" At line 184. After that even it may not work.Then replace
#Listen 0.0.0.0:80
#Listen [::]:80
Listen 80 

by

#Listen 0.0.0.0:81
#Listen [::]:81
Listen 81

at line 45

  1. If you want to use port 80. Then follow this. In Windows 8 “World Wide Publishing Service is using this port and stopping this service will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop. If you don't find there then Then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.

If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80

enter image description here

And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.

Python DNS module import error

This issue can be generated by Symantec End Point Protection (SEP). And I suspect most EPP products could potentially impact your running of scripts.

If SEP is disabled, the script will run instantly.

Therefore you may need to update the SEP policy to not block python scripts accessing stuff.

Capitalize the first letter of string in AngularJs

For the AngularJS from meanjs.org, I place the custom filters in modules/core/client/app/init.js

I needed a custom filter to capitalize each word in a sentence, here is how I do so:

angular.module(ApplicationConfiguration.applicationModuleName).filter('capitalize', function() {
return function(str) {
    return str.split(" ").map(function(input){return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() :         ''}).join(" ");

}
});

The credit of the map function goes to @Naveen raj

jQuery lose focus event

Use blur event to call your function when element loses focus :

$('#filter').blur(function() {
  $('#options').hide();
});

What Regex would capture everything from ' mark to the end of a line?

In your example I'd go for the following pattern:

'([^\n]+)$

use multiline and global options to match all occurences.

To include the linefeed in the match you could use:

'[^\n]+\n

But this might miss the last line if it has no linefeed.

For a single line, if you don't need to match the linefeed I'd prefer to use:

'[^$]+$

Centering FontAwesome icons vertically and horizontally

I just managed how to center icons and and making them a container instead of putting them into one.

.fas {
    position: relative;
    color: #EEE;
    font-size: 16px;
}
.fas:before {
    position: absolute;
    left: calc(50% - .5em);
    top: calc(50% - .5em);
}
.fas.fa-icon {
    width: 60px;
    height: 60px;
    color: white;
    background-color: black;
}

How do you append to a file?

You need to open the file in append mode, by setting "a" or "ab" as the mode. See open().

When you open with "a" mode, the write position will always be at the end of the file (an append). You can open with "a+" to allow reading, seek backwards and read (but all writes will still be at the end of the file!).

Example:

>>> with open('test1','wb') as f:
        f.write('test')
>>> with open('test1','ab') as f:
        f.write('koko')
>>> with open('test1','rb') as f:
        f.read()
'testkoko'

Note: Using 'a' is not the same as opening with 'w' and seeking to the end of the file - consider what might happen if another program opened the file and started writing between the seek and the write. On some operating systems, opening the file with 'a' guarantees that all your following writes will be appended atomically to the end of the file (even as the file grows by other writes).


A few more details about how the "a" mode operates (tested on Linux only). Even if you seek back, every write will append to the end of the file:

>>> f = open('test','a+') # Not using 'with' just to simplify the example REPL session
>>> f.write('hi')
>>> f.seek(0)
>>> f.read()
'hi'
>>> f.seek(0)
>>> f.write('bye') # Will still append despite the seek(0)!
>>> f.seek(0)
>>> f.read()
'hibye'

In fact, the fopen manpage states:

Opening a file in append mode (a as the first character of mode) causes all subsequent write operations to this stream to occur at end-of-file, as if preceded the call:

fseek(stream, 0, SEEK_END);

Old simplified answer (not using with):

Example: (in a real program use with to close the file - see the documentation)

>>> open("test","wb").write("test")
>>> open("test","a+b").write("koko")
>>> open("test","rb").read()
'testkoko'

How can one see content of stack with GDB?

You need to use gdb's memory-display commands. The basic one is x, for examine. There's an example on the linked-to page that uses

gdb> x/4xw $sp

to print "four words (w ) of memory above the stack pointer (here, $sp) in hexadecimal (x)". The quotation is slightly paraphrased.

javascript code to check special characters

If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.

var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
    alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
    return false;
}

Creating Threads in python

You can use the target argument in the Thread constructor to directly pass in a function that gets called instead of run.

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

How to change content on hover

This exact example is present on mozilla developers page:

::after

As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);, and store it in data-descr="ADD" attribute of your HTML tag (which is nice because you can e.g translate it)

CSS content can only be usef with :after and :before pseudo-elements, so you can try to proceed with something like this:

.item a p.new-label span:after{
  position: relative;
  content: 'NEW'
}
.item:hover a p.new-label span:after {
  content: 'ADD';
}

The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.

Is it possible to open a Windows Explorer window from PowerShell?

This is the only thing that fit my unique constraints of wanting the folder to open as a Quizo Tab in any existing Explorer window.

$objShell = New-Object -ComObject "Shell.Application"
$objShell.Explore("path")

Python: Making a beep noise

The cross-platform way to do this is to print('\a'). This will send the ASCII Bell character to stdout, and will hopefully generate a beep (a for 'alert'). Note that many modern terminal emulators provide the option to ignore bell characters.

Since you're on Windows, you'll be happy to hear that Windows has its own (brace yourself) Beep API, which allows you to send beeps of arbitrary length and pitch. Note that this is a Windows-only solution, so you should probably prefer print('\a') unless you really care about Hertz and milliseconds.

The Beep API is accessed through the winsound module: http://docs.python.org/library/winsound.html

NSURLErrorDomain error codes description

IN SWIFT 3. Here are the NSURLErrorDomain error codes description in a Swift 3 enum: (copied from answer above and converted what i can).

enum NSURLError: Int {
    case unknown = -1
    case cancelled = -999
    case badURL = -1000
    case timedOut = -1001
    case unsupportedURL = -1002
    case cannotFindHost = -1003
    case cannotConnectToHost = -1004
    case connectionLost = -1005
    case lookupFailed = -1006
    case HTTPTooManyRedirects = -1007
    case resourceUnavailable = -1008
    case notConnectedToInternet = -1009
    case redirectToNonExistentLocation = -1010
    case badServerResponse = -1011
    case userCancelledAuthentication = -1012
    case userAuthenticationRequired = -1013
    case zeroByteResource = -1014
    case cannotDecodeRawData = -1015
    case cannotDecodeContentData = -1016
    case cannotParseResponse = -1017
    //case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
    case fileDoesNotExist = -1100
    case fileIsDirectory = -1101
    case noPermissionsToReadFile = -1102
    //case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103

    // SSL errors
    case secureConnectionFailed = -1200
    case serverCertificateHasBadDate = -1201
    case serverCertificateUntrusted = -1202
    case serverCertificateHasUnknownRoot = -1203
    case serverCertificateNotYetValid = -1204
    case clientCertificateRejected = -1205
    case clientCertificateRequired = -1206
    case cannotLoadFromNetwork = -2000

    // Download and file I/O errors
    case cannotCreateFile = -3000
    case cannotOpenFile = -3001
    case cannotCloseFile = -3002
    case cannotWriteToFile = -3003
    case cannotRemoveFile = -3004
    case cannotMoveFile = -3005
    case downloadDecodingFailedMidStream = -3006
    case downloadDecodingFailedToComplete = -3007

    /*
     case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018
     case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019
     case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020
     case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021

     case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
     case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
     case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
     */
}

Direct link to URLError.Code in the Swift github repository, which contains the up to date list of error codes being used (github link).

Using Vim's tabs like buffers

Looking at :help tabs it doesn't look like vim wants to work the way you do...

Buffers are shared across tabs, so it doesn't seem possible to lock a given buffer to appear only on a certain tab.

It's a good idea, though.

You could probably get the effect you want by using a terminal that supports tabs, like multi-gnome-terminal, then running vim instances in each terminal tab. Not perfect, though...

Renaming a directory in C#

You should move it:

Directory.Move(source, destination);

How to get number of rows inserted by a transaction

I found the answer to may previous post. Here it is.

CREATE TABLE #TempTable (id int) 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 1,2 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 3,4 

SELECT * FROM #TempTable --this select will chage @@ROWCOUNT value

unexpected T_VARIABLE, expecting T_FUNCTION

Use access modifier before the member definition:

    private $connection;

As you cannot use function call in member definition in PHP, do it in constructor:

 public function __construct() {
      $this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
 }

How would you count occurrences of a string (actually a char) within a string?

For anyone wanting a ready to use String extension method,

here is what I use which was based on the best of the posted answers:

public static class StringExtension
{    
    /// <summary> Returns the number of occurences of a string within a string, optional comparison allows case and culture control. </summary>
    public static int Occurrences(this System.String input, string value, StringComparison stringComparisonType = StringComparison.Ordinal)
    {
        if (String.IsNullOrEmpty(value)) return 0;

        int count    = 0;
        int position = 0;

        while ((position = input.IndexOf(value, position, stringComparisonType)) != -1)
        {
            position += value.Length;
            count    += 1;
        }

        return count;
    }

    /// <summary> Returns the number of occurences of a single character within a string. </summary>
    public static int Occurrences(this System.String input, char value)
    {
        int count = 0;
        foreach (char c in input) if (c == value) count += 1;
        return count;
    }
}

How can I make a button redirect my page to another page?

This is here:

 <button onClick="window.location='page_name.php';" value="click here" />

Sending and receiving data over a network using TcpClient

First of all, TCP does not guarantee that everything that you send will be received with the same read at the other end. It only guarantees that all bytes that you send will arrive and in the correct order.

Therefore, you will need to keep building up a buffer when reading from the stream. You will also have to know how large each message is.

The simplest ever is to use a non-typeable ASCII character to mark the end of the packet and look for it in the received data.

Alternative to the HTML Bold tag

you could also do <p style="font-weight:bold;"> bold text here </p>

Difference between string and char[] types in C++

Think of (char *) as string.begin(). The essential difference is that (char *) is an iterator and std::string is a container. If you stick to basic strings a (char *) will give you what std::string::iterator does. You could use (char *) when you want the benefit of an iterator and also compatibility with C, but that's the exception and not the rule. As always, be careful of iterator invalidation. When people say (char *) isn't safe this is what they mean. It's as safe as any other C++ iterator.

What is the best way to do a substring in a batch file?

Nicely explained above!

For all those who may suffer like me to get this working in a localized Windows (mine is XP in Slovak), you may try to replace the % with a !

So:

SET TEXT=Hello World
SET SUBSTRING=!TEXT:~3,5!
ECHO !SUBSTRING!

How can I create 2 separate log files with one log4j config file?

Modify your log4j.properties file accordingly:

log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog

Change the log levels for each logger depending to your needs.

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

Add leading zeroes/0's to existing Excel values to certain length

=TEXT(A1,"0000")

However the TEXT function is able to do other fancy stuff like date formating, aswell.

Proper way to exit iPhone application?

My App has been rejected recently bc I've used an undocumented method. Literally:

"Unfortunately it cannot be added to the App Store because it is using a private API. Use of non-public APIs, which as outlined in the iPhone Developer Program License Agreement section 3.3.1 is prohibited:

"3.3.1 Applications may only use Documented APIs in the manner prescribed by Apple and must not use or call any private APIs."

The non-public API that is included in your application is terminateWithSuccess"

How to validate Google reCAPTCHA v3 on server side?

Check below example

<script src='https://www.google.com/recaptcha/api.js'></script>
<script>

function get_action(form) 
{
    var v = grecaptcha.getResponse();
    if(v.length == 0)
    {
        document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
        return false;
    }
    else
    {
         document.getElementById('captcha').innerHTML="Captcha completed";
        return true; 
    }
}

</script>
<form autocomplete="off" method="post" action=submit.php">

    <input type="text" name="name">
    <input type="text" name="email">
    <div class="g-recaptcha" id="rcaptcha"  data-sitekey="site key"></div>
    <span id="captcha" style="color:red" /></span> <!-- this will show captcha errors -->
    <input type="submit" id="sbtBrn" value="Submit" name="sbt" class="btn btn-info contactBtn" />
</form>

Image resizing in React Native

In my case I could not set 'width' and 'height' to null because I'm using TypeScript.

The way I fixed it was by setting them to '100%':

backgroundImage: {
    flex: 1,
    width: '100%',
    height: '100%',
    resizeMode: 'cover',        
}

Using momentjs to convert date to epoch then back to date

There are a few things wrong here:

  • First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".

  • .unix() returns Unix Time in whole seconds, but the default moment constructor accepts a timestamp in milliseconds. You should instead use .valueOf() to return milliseconds. Note that calling .unix()*1000 would also work, but it would result in a loss of precision.

  • You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:

    moment("10/15/2014 9:00", "M/D/YYYY H:mm")
    
  • .calendar() has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format() function instead. Again, you may want to pass a format specifier.

  • To answer your questions in comments, No - you don't need to call .local() or .utc().

Putting it all together:

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);

On my machine, in the US Pacific time zone, it results in:

Values are: ts = 1413388800000, s = 10/15/2014 9:00

Since the input value is interpreted in terms of local time, you will get a different value for ts if you are in a different time zone.

Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix() to return the timestamp in whole seconds, and moment.unix(ts) to parse it back to a moment.

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);

Facebook Open Graph not clearing cache

I had the same issues using og:image, several attempts to rename the file or clear FB cache did not work either via the facebook debugger or testing via an actual account.

The new facebook guidelines state the image size should be 1200 x 630 or having that aspect ratio, this seems to be wrong, the only thing that worked for me was using an image with square dimensions.

Edit* Afew hours I went back to use 1200 x 630 and it magically worked, it was magical.

I also renamed the files to f*^*kfacebook.jpg, not sure it helped but it felt good.

PHP PDO returning single row

$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1 ORDER BY x LIMIT 1" );

$STH -> execute();
$result = $STH -> fetch();
echo $result ["figure"];

$DBH = null;

You can use fetch and LIMIT together. LIMIT has the effect that the database returns only one entry so PHP has to handle very less data. With fetch you get the first (and only) result entry from the database reponse.

You can do more optimizing by setting the fetching type, see http://www.php.net/manual/de/pdostatement.fetch.php. If you access it only via column names you need to numbered array.

Be aware of the ORDER clause. Use ORDER or WHERE to get the needed row. Otherwise you will get the first row in the table alle the time.

How do I enable C++11 in gcc?

If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.

{
    "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",

    "variants":
    [
        {
            "name": "Run",
            "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
        }
    ]
}

Hibernate: How to set NULL query-parameter value with HQL?

Here is the solution I found on Hibernate 4.1.9. I had to pass a parameter to my query that can have value NULL sometimes. So I passed the using:

setParameter("orderItemId", orderItemId, new LongType())

After that, I use the following where clause in my query:

where ((:orderItemId is null) OR (orderItem.id != :orderItemId))

As you can see, I am using the Query.setParameter(String, Object, Type) method, where I couldn't use the Hibernate.LONG that I found in the documentation (probably that was on older versions). For a full set of options of type parameter, check the list of implementation class of org.hibernate.type.Type interface.

Hope this helps!

Oracle SQL Developer: Unable to find a JVM

“C:\Users\admin\Downloads\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf” is misleading, it’s not the file which sets the Java Home variable. The actually file used is”%AppData%\sqldeveloper{PRODUCT_VERSION}\product.conf” [in my case it is "%AppData%\sqldeveloper\1.0.0.0.0\product.conf"]

Create a directory if it doesn't exist

Use the WINAPI CreateDirectory() function to create a folder.

You can use this function without checking if the directory already exists as it will fail but GetLastError() will return ERROR_ALREADY_EXISTS:

if (CreateDirectory(OutputFolder.c_str(), NULL) ||
    ERROR_ALREADY_EXISTS == GetLastError())
{
    // CopyFile(...)
}
else
{
     // Failed to create directory.
}

The code for constructing the target file is incorrect:

string(OutputFolder+CopiedFile).c_str()

this would produce "D:\testEmploi Nam.docx": there is a missing path separator between the directory and the filename. Example fix:

string(OutputFolder+"\\"+CopiedFile).c_str()

Selecting rows where remainder (modulo) is 1 after division by 2?

select * from table where value % 2 = 1 works fine in mysql.

In Java, what does NaN mean?

NaN means "Not a number." It's a special floating point value that means that the result of an operation was not defined or not representable as a real number.

See here for more explanation of this value.

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

How to stretch in width a WPF user control to its window?

Is the Canvas crucial in your window? If not, try removing it and keep the Grid as the main panel. Canvas has no size unless specified, while a Grid normally takes up all available space. Inside the Canvas, the Grid will have no available space.

How to select all records from one table that do not exist in another table?

I'm going to repost (since I'm not cool enough yet to comment) in the correct answer....in case anyone else thought it needed better explaining.

SELECT temp_table_1.name
FROM original_table_1 temp_table_1
LEFT JOIN original_table_2 temp_table_2 ON temp_table_2.name = temp_table_1.name
WHERE temp_table_2.name IS NULL

And I've seen syntax in FROM needing commas between table names in mySQL but in sqlLite it seemed to prefer the space.

The bottom line is when you use bad variable names it leaves questions. My variables should make more sense. And someone should explain why we need a comma or no comma.

Add carriage return to a string

Environment.NewLine should be used as Dan Rigby said but there is one problem with the String.Empty. It will remain always empty no matter if it is read before or after it reads. I had a problem in my project yesterday with that. I removed it and it worked the way it was supposed to. It's better to declare the variable and then call it when it's needed. String.Empty will always keep it empty unless the variable needs to be initialized which only then should you use String.Empty. Thought I would throw this tid-bit out for everyone as I've experienced it.

DataTables fixed headers misaligned with columns in wide tables

Add table-layout: fixed to your table's style (css or style attribute).

The browser will stop applying its custom algorithm to solve size constraints.

Search the web for infos about handling column widths in a fixed table layout (here are 2 simple SO questions : here and here)

Obviously: the downside will be that your columns' width won't adapt to their content.


[Edit] My answer worked when I used the FixedHeader plugin, but a post on the datatable's forum seem to indicate that other problems arise when using the sScrollX option :

bAutoWidth and sWidth ignored when sScrollX is set (v1.7.5)

I'll try to find a way to go around this.

Modify tick label text

I noticed that all the solutions posted here that use set_xticklabels() are not preserving the offset, which is a scaling factor applied to the ticks values to create better-looking tick labels. For instance, if the ticks are on the order of 0.00001 (1e-5), matplotlib will automatically add a scaling factor (or offset) of 1e-5, so the resultant tick labels may end up as 1 2 3 4, rather than 1e-5 2e-5 3e-5 4e-5.

Below gives an example:

The x array is np.array([1, 2, 3, 4])/1e6, and y is y=x**2. So both are very small values.

Left column: manually change the 1st and 3rd labels, as suggested by @Joe Kington. Note that the offset is lost.

Mid column: similar as @iipr suggested, using a FuncFormatter.

Right column: My suggested offset-preserving solution.

Figure here: enter image description here

Complete code here:

import matplotlib.pyplot as plt
import numpy as np

# create some *small* data to plot
x = np.arange(5)/1e6
y = x**2

fig, axes = plt.subplots(1, 3, figsize=(10,6))

#------------------The set_xticklabels() solution------------------
ax1 = axes[0]
ax1.plot(x, y)
fig.canvas.draw()
labels = [item.get_text() for item in ax1.get_xticklabels()]

# Modify specific labels
labels[1] = 'Testing'
labels[3] = 'Testing2'
ax1.set_xticklabels(labels)
ax1.set_title('set_xticklabels()')

#--------------FuncFormatter solution--------------
import matplotlib.ticker as mticker

def update_ticks(x, pos):
    if pos==1:
        return 'testing'
    elif pos==3:
        return 'testing2'
    else:
        return x

ax2=axes[1]
ax2.plot(x,y)
ax2.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
ax2.set_title('Func Formatter')

#-------------------My solution-------------------
def changeLabels(axis, pos, newlabels):
    '''Change specific x/y tick labels

    Args:
        axis (Axis): .xaxis or .yaxis obj.
        pos (list): indices for labels to change.
        newlabels (list): new labels corresponding to indices in <pos>.
    '''

    if len(pos) != len(newlabels):
        raise Exception("Length of <pos> doesn't equal that of <newlabels>.")

    ticks = axis.get_majorticklocs()
    # get the default tick formatter
    formatter = axis.get_major_formatter()
    # format the ticks into strings
    labels = formatter.format_ticks(ticks)

    # Modify specific labels
    for pii, lii in zip(pos, newlabels):
        labels[pii] = lii

    # Update the ticks and ticklabels. Order is important here.
    # Need to first get the offset (1e-6 in this case):
    offset = formatter.get_offset()
    # Then set the modified labels:
    axis.set_ticklabels(labels)
    # In doing so, matplotlib creates a new FixedFormatter and sets it to the xaxis
    # and the new FixedFormatter has no offset. So we need to query the
    # formatter again and re-assign the offset:
    axis.get_major_formatter().set_offset_string(offset)

    return

ax3 = axes[2]
ax3.plot(x, y)

changeLabels(ax3.xaxis, [1, 3], ['Testing', 'Testing2'])
ax3.set_title('With offset')

fig.show()
plt.savefig('tick_labels.png')

Caveat: it appears that solutions that use set_xticklabels(), including my own, relies on FixedFormatter, which is static and doesn't respond to figure resizing. To observe the effect, change the figure to a smaller size, e.g. fig, axes = plt.subplots(1, 3, figsize=(6,6)) and enlarge the figure window. You will notice that that only the mid column responds to resizing and adds more ticks as the figure gets larger. The left and right column will have empty tick labels (see figure below).

Caveat 2: I also noticed that if your tick values are floats, calling set_xticklabels(ticks) directly might give you ugly-looking strings, like 1.499999999998 instead of 1.5.

enter image description here

ASP.Net which user account running Web Service on IIS 7?

Look at the Identity of the Application Pool that's running your application. By default it will be the Network Service account, but you can change this.

At least that's how it works on 2003 server, don't know if some details have changed for 2008 server.

How do I share variables between different .c files?

In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.

In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.

In those few rare cases when you need to share a variable between files, do like this:

// file.h
extern int my_var;

// file.c
#include "file.h"
int my_var = something;

// main.c
#include "file.h"
use(my_var);

Never put any form of variable definition in a h-file.

html form - make inputs appear on the same line

A more modern solution:

Using display: flex and flex-direction: row

_x000D_
_x000D_
form {_x000D_
  display: flex; /* 2. display flex to the rescue */_x000D_
  flex-direction: row;_x000D_
}_x000D_
_x000D_
label, input {_x000D_
  display: block; /* 1. oh noes, my inputs are styled as block... */_x000D_
}
_x000D_
<form>_x000D_
  <label for="name">Name</label>_x000D_
  <input type="text" id="name" />_x000D_
  <label for="address">Address</label>_x000D_
  <input type="text" id="address" />_x000D_
  <button type="submit">_x000D_
    Submit_x000D_
  </button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Carriage Return\Line feed in Java

The method newLine() ensures a platform-compatible new line is added (0Dh 0Ah for DOS, 0Dh for older Macs, 0Ah for Unix/Linux). Java has no way of knowing on which platform you are going to send the text. This conversion should be taken care of by the mail sending entities.

Call a Class From another class

Class2 class2 = new Class2();

Instead of calling the main, perhaps you should call individual methods where and when you need them.

Adding an HTTP Header to the request in a servlet filter

You'll have to use an HttpServletRequestWrapper:

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
        @Override
        public String getHeader(String name) {
            final String value = request.getParameter(name);
            if (value != null) {
                return value;
            }
            return super.getHeader(name);
        }
    };
    chain.doFilter(wrapper, response);
}

Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.

Make hibernate ignore class variables that are not mapped

For folks who find this posting through the search engines, another possible cause of this problem is from importing the wrong package version of @Transient. Make sure that you import javax.persistence.transient and not some other package.

SQL: parse the first, middle and last name from a fullname field

Here is a self-contained example, with easily manipulated test data.

With this example, if you have a name with more than three parts, then all the "extra" stuff will get put in the LAST_NAME field. An exception is made for specific strings that are identified as "titles", such as "DR", "MRS", and "MR".

If the middle name is missing, then you just get FIRST_NAME and LAST_NAME (MIDDLE_NAME will be NULL).

You could smash it into a giant nested blob of SUBSTRINGs, but readability is hard enough as it is when you do this in SQL.

Edit-- Handle the following special cases:

1 - The NAME field is NULL

2 - The NAME field contains leading / trailing spaces

3 - The NAME field has > 1 consecutive space within the name

4 - The NAME field contains ONLY the first name

5 - Include the original full name in the final output as a separate column, for readability

6 - Handle a specific list of prefixes as a separate "title" column

SELECT
  FIRST_NAME.ORIGINAL_INPUT_DATA
 ,FIRST_NAME.TITLE
 ,FIRST_NAME.FIRST_NAME
 ,CASE WHEN 0 = CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)
       THEN NULL  --no more spaces?  assume rest is the last name
       ELSE SUBSTRING(
                       FIRST_NAME.REST_OF_NAME
                      ,1
                      ,CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)-1
                     )
       END AS MIDDLE_NAME
 ,SUBSTRING(
             FIRST_NAME.REST_OF_NAME
            ,1 + CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)
            ,LEN(FIRST_NAME.REST_OF_NAME)
           ) AS LAST_NAME
FROM
  (  
  SELECT
    TITLE.TITLE
   ,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME)
         THEN TITLE.REST_OF_NAME --No space? return the whole thing
         ELSE SUBSTRING(
                         TITLE.REST_OF_NAME
                        ,1
                        ,CHARINDEX(' ',TITLE.REST_OF_NAME)-1
                       )
    END AS FIRST_NAME
   ,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME)  
         THEN NULL  --no spaces @ all?  then 1st name is all we have
         ELSE SUBSTRING(
                         TITLE.REST_OF_NAME
                        ,CHARINDEX(' ',TITLE.REST_OF_NAME)+1
                        ,LEN(TITLE.REST_OF_NAME)
                       )
    END AS REST_OF_NAME
   ,TITLE.ORIGINAL_INPUT_DATA
  FROM
    (   
    SELECT
      --if the first three characters are in this list,
      --then pull it as a "title".  otherwise return NULL for title.
      CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')
           THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,1,3)))
           ELSE NULL
           END AS TITLE
      --if you change the list, don't forget to change it here, too.
      --so much for the DRY prinicple...
     ,CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')
           THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,4,LEN(TEST_DATA.FULL_NAME))))
           ELSE LTRIM(RTRIM(TEST_DATA.FULL_NAME))
           END AS REST_OF_NAME
     ,TEST_DATA.ORIGINAL_INPUT_DATA
    FROM
      (
      SELECT
        --trim leading & trailing spaces before trying to process
        --disallow extra spaces *within* the name
        REPLACE(REPLACE(LTRIM(RTRIM(FULL_NAME)),'  ',' '),'  ',' ') AS FULL_NAME
       ,FULL_NAME AS ORIGINAL_INPUT_DATA
      FROM
        (
        --if you use this, then replace the following
        --block with your actual table
              SELECT 'GEORGE W BUSH' AS FULL_NAME
        UNION SELECT 'SUSAN B ANTHONY' AS FULL_NAME
        UNION SELECT 'ALEXANDER HAMILTON' AS FULL_NAME
        UNION SELECT 'OSAMA BIN LADEN JR' AS FULL_NAME
        UNION SELECT 'MARTIN J VAN BUREN SENIOR III' AS FULL_NAME
        UNION SELECT 'TOMMY' AS FULL_NAME
        UNION SELECT 'BILLY' AS FULL_NAME
        UNION SELECT NULL AS FULL_NAME
        UNION SELECT ' ' AS FULL_NAME
        UNION SELECT '    JOHN  JACOB     SMITH' AS FULL_NAME
        UNION SELECT ' DR  SANJAY       GUPTA' AS FULL_NAME
        UNION SELECT 'DR JOHN S HOPKINS' AS FULL_NAME
        UNION SELECT ' MRS  SUSAN ADAMS' AS FULL_NAME
        UNION SELECT ' MS AUGUSTA  ADA   KING ' AS FULL_NAME      
        ) RAW_DATA
      ) TEST_DATA
    ) TITLE
  ) FIRST_NAME

Nodejs - Redirect url

The logic of determining a "wrong" url is specific to your application. It could be a simple file not found error or something else if you are doing a RESTful app. Once you've figured that out, sending a redirect is as simple as:

response.writeHead(302, {
  'Location': 'your/404/path.html'
  //add other headers here...
});
response.end();

Regex to match only uppercase "words" with some exceptions

I'm not a regex guru by any means. But try:

<[A-Z0-9][A-Z0-9]+>

<           start of word
[A-Z0-9]    one character
[A-Z0-9]+   and one or more of them
>           end of word

I won't try for the bonus points of the whole upper case sentence. hehe

Why "no projects found to import"?

This answer is same as Laura's answer , however, in new eclipse versions you will not be able to see a "create project from existing source" option.

Hence you can do this instead:

  • Goto File > New > Project

  • Select the type of project, click Next

  • Uncheck Use default location

  • Click on Browse to navigate to your source folder, or type in the path to your source

  • Click Finish

Taken from this discussion forum in eclipse.org

How to make cross domain request

Do a cross-domain AJAX call

Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Check the following for more information

Make cross-domain ajax JSONP request with jQuery

Comparing Arrays of Objects in JavaScript

As serialization doesn't work generally (only when the order of properties matches: JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1})) you have to check the count of properties and compare each property as well:

_x000D_
_x000D_
const objectsEqual = (o1, o2) =>_x000D_
    Object.keys(o1).length === Object.keys(o2).length _x000D_
        && Object.keys(o1).every(p => o1[p] === o2[p]);_x000D_
_x000D_
const obj1 = { name: 'John', age: 33};_x000D_
const obj2 = { age: 33, name: 'John' };_x000D_
const obj3 = { name: 'John', age: 45 };_x000D_
        _x000D_
console.log(objectsEqual(obj1, obj2)); // true_x000D_
console.log(objectsEqual(obj1, obj3)); // false
_x000D_
_x000D_
_x000D_

If you need a deep comparison, you can call the function recursively:

_x000D_
_x000D_
const obj1 = { name: 'John', age: 33, info: { married: true, hobbies: ['sport', 'art'] } };_x000D_
const obj2 = { age: 33, name: 'John', info: { hobbies: ['sport', 'art'], married: true } };_x000D_
const obj3 = { name: 'John', age: 33 };_x000D_
_x000D_
const objectsEqual = (o1, o2) => _x000D_
    typeof o1 === 'object' && Object.keys(o1).length > 0 _x000D_
        ? Object.keys(o1).length === Object.keys(o2).length _x000D_
            && Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))_x000D_
        : o1 === o2;_x000D_
        _x000D_
console.log(objectsEqual(obj1, obj2)); // true_x000D_
console.log(objectsEqual(obj1, obj3)); // false
_x000D_
_x000D_
_x000D_

Then it's easy to use this function to compare objects in arrays:

const arr1 = [obj1, obj1];
const arr2 = [obj1, obj2];
const arr3 = [obj1, obj3];

const arraysEqual = (a1, a2) => 
   a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));

console.log(arraysEqual(arr1, arr2)); // true
console.log(arraysEqual(arr1, arr3)); // false

Perform Segue programmatically and pass parameters to the destination view

I understand the problem of performing the segue at one place and maintaining the state to send parameters in prepare for segue.

I figured out a way to do this. I've added a property called userInfoDict to ViewControllers using a category. and I've override perform segue with identifier too, in such a way that If the sender is self(means the controller itself). It will pass this userInfoDict to the next ViewController.

Here instead of passing the whole UserInfoDict you can also pass the specific params, as sender and override accordingly.

1 thing you need to keep in mind. don't forget to call super method in ur performSegue method.

Android camera intent

I found a pretty simple way to do this. Use a button to open it using an on click listener to start the function openc(), like this:

String fileloc;
private void openc()
{
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File f = null;
    try 
    {
        f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {               
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
            fileloc = Uri.fromFile(f)+"";
            Log.d("texts", "openc: "+fileloc);
            startActivityForResult(takePictureIntent, 3);
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 3 && resultCode == RESULT_OK) {
        Log.d("texts", "onActivityResult: "+fileloc);
        // fileloc is the uri of the file so do whatever with it
    }
}

You can do whatever you want with the uri location string. For instance, I send it to an image cropper to crop the image.

How do I get the dialer to open with phone number displayed?

As @ashishduh mentioned above, using android:autoLink="phone is also a good solution. But this option comes with one drawback, it doesn't work with all phone number lengths. For instance, a phone number of 11 numbers won't work with this option. The solution is to prefix your phone numbers with the country code.

Example:

08034448845 won't work

but +2348034448845 will

C char* to int conversion

Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}

How do you read from stdin?

I had some issues when getting this to work for reading over sockets piped to it. When the socket got closed it started returning empty string in an active loop. So this is my solution to it (which I only tested in linux, but hope it works in all other systems)

import sys, os
sep=os.linesep

while sep == os.linesep:
    data = sys.stdin.readline()               
    sep = data[-len(os.linesep):]
    print '> "%s"' % data.strip()

So if you start listening on a socket it will work properly (e.g. in bash):

while :; do nc -l 12345 | python test.py ; done

And you can call it with telnet or just point a browser to localhost:12345

How to pop an alert message box using PHP?

Create function for alert

<?php
alert("Hello World");

function alert($msg) {
    echo "<script type='text/javascript'>alert('$msg');</script>";
}
?>

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

Unsupported operation :not writeable python

You open the variable "file" as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the 'w' flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

SQL Server - transactions roll back on error?

If one of the inserts fail, or any part of the command fails, does SQL server roll back the transaction?

No, it does not.

If it does not rollback, do I have to send a second command to roll it back?

Sure, you should issue ROLLBACK instead of COMMIT.

If you want to decide whether to commit or rollback the transaction, you should remove the COMMIT sentence out of the statement, check the results of the inserts and then issue either COMMIT or ROLLBACK depending on the results of the check.

C string append

man page of strcat says that arg1 and arg2 are appended to arg1.. and returns the pointer of s1. If you dont want disturb str1,str2 then you have write your own function.

char * my_strcat(const char * str1, const char * str2)
{
   char * ret = malloc(strlen(str1)+strlen(str2));

   if(ret!=NULL)
   {
     sprintf(ret, "%s%s", str1, str2);
     return ret;
   }
   return NULL;    
}

Hope this solves your purpose

Artisan migrate could not find driver

whilst sometimes you might have multiple php versions, you might also have a held-back version of php-mysql.. do a sudo dpkg -l | grep mysql | grep php and compare what you get from php -v

Using a BOOL property

There's no benefit to using properties with primitive types. @property is used with heap allocated NSObjects like NSString*, NSNumber*, UIButton*, and etc, because memory managed accessors are created for free. When you create a BOOL, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking is simply the popular way of expressing the state of a boolean value.

In another OO language you would make a variable private bool working; and two accessors: SetWorking for the setter and IsWorking for the accessor.

WebAPI Multiple Put/Post parameters

We passed Json object by HttpPost method, and parse it in dynamic object. it works fine. this is sample code:

webapi:

[HttpPost]
public string DoJson2(dynamic data)
{
   //whole:
   var c = JsonConvert.DeserializeObject<YourObjectTypeHere>(data.ToString()); 

   //or 
   var c1 = JsonConvert.DeserializeObject< ComplexObject1 >(data.c1.ToString());

   var c2 = JsonConvert.DeserializeObject< ComplexObject2 >(data.c2.ToString());

   string appName = data.AppName;
   int appInstanceID = data.AppInstanceID;
   string processGUID = data.ProcessGUID;
   int userID = data.UserID;
   string userName = data.UserName;
   var performer = JsonConvert.DeserializeObject< NextActivityPerformers >(data.NextActivityPerformers.ToString());

   ...
}

The complex object type could be object, array and dictionary.

ajaxPost:
...
Content-Type: application/json,
data: {"AppName":"SamplePrice",
       "AppInstanceID":"100",
       "ProcessGUID":"072af8c3-482a-4b1c??-890b-685ce2fcc75d",
       "UserID":"20",
       "UserName":"Jack",
       "NextActivityPerformers":{
           "39??c71004-d822-4c15-9ff2-94ca1068d745":[{
                 "UserID":10,
                 "UserName":"Smith"
           }]
       }}
...

Django: Model Form "object has no attribute 'cleaned_data'"

At times, if we forget the

return self.cleaned_data 

in the clean function of django forms, we will not have any data though the form.is_valid() will return True.

Create local maven repository

If maven is not creating Local Repository i.e .m2/repository folder then try below step.

In your Eclipse\Spring Tool Suite, Go to Window->preferences-> maven->user settings-> click on Restore Defaults-> Apply->Apply and close

Android: Expand/collapse animation

This is really simple with droidQuery. For starts, consider this layout:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/v1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="View 1" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/v2"
        android:layout_width="wrap_content"
        android:layout_height="0dp" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="View 2" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="View 3" />
    </LinearLayout>
</LinearLayout>

We can animate the height to the desired value - say 100dp - using the following code:

//convert 100dp to pixel value
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());

Then use droidQuery to animate. The simplest way is with this:

$.animate("{ height: " + height + "}", new AnimationOptions());

To make the animation more appealing, consider adding an easing:

$.animate("{ height: " + height + "}", new AnimationOptions().easing($.Easing.BOUNCE));

You can also change the duration on AnimationOptions using the duration() method, or handle what happens when the animation ends. For a complex example, try:

$.animate("{ height: " + height + "}", new AnimationOptions().easing($.Easing.BOUNCE)
                                                             .duration(1000)
                                                             .complete(new Function() {
                                                                 @Override
                                                                 public void invoke($ d, Object... args) {
                                                                     $.toast(context, "finished", Toast.LENGTH_SHORT);
                                                                 }
                                                             }));

In Bootstrap 3,How to change the distance between rows in vertical?

Instead of adding any tag which is never a good solution. You can always use margin property with the required element.

You can add the margin on row class itself. So it will affect globally.

.row{
  margin-top: 30px;
  margin-bottom: 30px
}

Update: Better solution in all cases would be to introduce a new class and then use it along with .row class.

.row-m-t{
  margin-top : 20px
}

Then use it wherever you want

<div class="row row-m-t"></div>

When to use Interface and Model in TypeScript / Angular

I personally use interfaces for my models, There hoewver are 3 schools regarding this question, and choosing one is most often based on your requirements:

1- Interfaces:

interface is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes. Once your code is transpiled to its target language, it will be stripped from its interfaces - JavaScript isn’t typed.

interface User {
 id: number;
 username: string;
}
// inheritance
interface UserDetails extends User {
 birthdate: Date;
 biography?: string;  // use the '?' annotation to mark this property as optionnal
}

Mapping server response to an interface is straight forward if you are using HttpClient from HttpClientModule if you are using Angular 4.3.x and above.

getUsers() :Observable<User[]> {
 return this.http.get<User[]>(url); // no need for '.map((res: Response) => res.json())' 
}

when to use interfaces:

  • You only need the definition for the server data without introducing additional overhead for the final output.
  • You only need to transmit data without any behaviors or logic (constructor initialization, methods)
  • You do not instantiate/create objects from your interface very often
    • Using simple object-literal notationlet instance: FooInterface = { ... };, you risk having semi-instances all over the place.
    • That doesn't enforce the constraints given by a class ( constructor or initialization logic, validation, encapsulation of private fields...Etc)
  • You need to define contracts/configurations for your systems (global configurations)

2- Classes:

A class defines the blueprints of an object. They express the logic, methods, and properties these objects will inherit.

class User {
 id: number;
 username: string;
 constructor(id :number, username: string)  {
  this.id = id;
  this.username = username.replace(/^\s+|\s+$/g, ''); // trim whitespaces and new lines
 }
}
// inheritance
class UserDetails extends User {
 birthdate: Date;
 biography?: string;  
 constructor(id :number, username: string, birthdate:Date, biography? :string )  {
   super(id,username);
  this.birthdate = ...;
 }
}

when to use classes:

  • You instantiate your class and change the instances state over time.
  • Instances of your class will need methods to query or mutate its state
  • When you want to associate behaviors with data more closely;
  • You enforce constraints on the creation of your instaces.
  • If you only write a bunch of properties assignments in your class, you might consider using a type instead.

2- Types:

With the latest versions of typescript, interfaces and types becoming more similar. types do not express logic or state inside your application. It is best to use types when you want to describe some form of information. They can describe varying shapes of data, ranging from simple constructs like strings, arrays, and objects. Like interfaces, types are only virtual structures that don't transpile to any javascript, they just help the compiler making our life easier.

type User = {
 id: number;
 username: string;
}
// inheritance
type UserDetails = User & {
  birthDate :Date;
  biography?:string;
}

when to use types:

  • pass it around as concise function parameters
  • describe a class constructor parameters
  • document small or medium objects coming in or out from an API.
  • they don't carry state nor behavior

How do I move a redis database from one server to another?

If you have the connectivity between servers it is better to set up replication (which is trivial, unlike with SQL) with the new instance as a slave node - then you can switch the new node to master with a single command and do the move with zero downtime.

Shorten string without cutting words in JavaScript

'Pasta with tomato and spinach'

if you do not want to cut the word in half

first iteration:

acc:0 / acc +cur.length = 5 / newTitle = ['Pasta'];

second iteration:

acc:5 / acc + cur.length = 9 / newTitle = ['Pasta', 'with'];

third iteration:

acc:9 / acc + cur.length = 15 / newTitle = ['Pasta', 'with', 'tomato'];

fourth iteration:

acc:15 / acc + cur.length = 18(limit bound) / newTitle = ['Pasta', 'with', 'tomato'];

const limitRecipeTitle = (title, limit=17)=>{
    const newTitle = [];
    if(title.length>limit){
        title.split(' ').reduce((acc, cur)=>{
            if(acc+cur.length <= limit){
                newTitle.push(cur);
            }
            return acc+cur.length;
        },0);
    }

    return `${newTitle.join(' ')} ...`
}

output: Pasta with tomato ...

How do I revert to a previous package in Anaconda?

I had to use the install function instead:

conda install pandas=0.13.1

What's a good hex editor/viewer for the Mac?

On http://www.synalysis.net/ you can get the hex editor I'm developing for the Mac - Synalyze It!. It costs 7 € / 40 € (Pro version) and offers some extra features like histogram, incremental search, support of many text encodings and interactive definition of a "grammar" for your file format.

The grammar helps to interpret the files and colors the hex view for easier analysis.

Synalyze It!

nodemon not working: -bash: nodemon: command not found

I'm using macOS/Linux, the solution that works for me is

npx nodemon index.js 

I have tried every possibility, like uninstalling and installing nodemon, installing nodemon globally. restart the terminal, but it won't work.

don't try such things to waste your time.

Modifying location.hash without page scrolling

Use history.replaceState or history.pushState* to change the hash. This will not trigger the jump to the associated element.

Example

$(document).on('click', 'a[href^=#]', function(event) {
  event.preventDefault();
  history.pushState({}, '', this.href);
});

Demo on JSFiddle

* If you want history forward and backward support

History behaviour

If you are using history.pushState and you don't want page scrolling when the user uses the history buttons of the browser (forward/backward) check out the experimental scrollRestoration setting (Chrome 46+ only).

history.scrollRestoration = 'manual';

Browser Support

Animate change of view background color on Android

add a folder animator into res folder. (the name must be animator). Add an animator resource file. For example res/animator/fade.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:propertyName="backgroundColor"
        android:duration="1000"
        android:valueFrom="#000000"
        android:valueTo="#FFFFFF"
        android:startOffset="0"
        android:repeatCount="-1"
        android:repeatMode="reverse" />
</set>

Inside Activity java file, call this

View v = getWindow().getDecorView().findViewById(android.R.id.content);
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.fade);
set.setTarget(v);
set.start();

Why do access tokens expire?

It is essentially a security measure. If your app is compromised, the attacker will only have access to the short-lived access token and no way to generate a new one.

Refresh tokens also expire but they are supposed to live much longer than the access token.

Hidden Features of Java

I just (re)learned today that $ is a legal name for a method or variable in Java. Combined with static imports it can make for some slightly more readable code, depending on your view of readable:

http://garbagecollected.org/2008/04/06/dollarmaps/

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

Below pattern perfectly works in case of leap year and as well as with normal dates. The date format is : YYYY-MM-DD

<input type="text"  placeholder="YYYY-MM-DD" pattern="(?:19|20)(?:(?:[13579][26]|[02468][048])-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))|(?:[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:29|30))|(?:(?:0[13578]|1[02])-31)))" class="form-control "  name="eventDate" id="" required autofocus autocomplete="nope">

I got this solution from http://html5pattern.com/Dates. Hope it may help someone.

How to do a num_rows() on COUNT query in codeigniter?

As per CI Docs we can use the following,

$this->db->where('account_status', $i); // OTHER CONDITIONS IF ANY
$this->db->from('account_status'); //TABLE NAME
echo $this->db->count_all_results();

If we want to get total rows in the table without any condition, simple use

echo $this->db->count_all_results('table_name'); // returns total_rows presented in the table

How to programmatically set style attribute in a view

First of all, you don't need to use a layout inflater to create a simple Button. You can just use:

button = new Button(context);

If you want to style the button you have 2 choices: the simplest one is to just specify all the elements in code, like many of the other answers suggest:

button.setTextColor(Color.RED);
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

The other option is to define the style in XML, and apply it to the button. In the general case, you can use a ContextThemeWrapper for this:

ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext, R.style.MyStyle);
button = new Button(newContext);

To change the text-related attributes on a TextView (or its subclasses like Button) there is a special method:

button.setTextAppearance(R.style.MyTextStyle);

Or, if you need to support devices pre API-23 (Android 6.0)

button.setTextAppearance(context, R.style.MyTextStyle);

This method cannot be used to change all attributes; for example to change padding you need to use a ContextThemeWrapper. But for text color, size, etc. you can use setTextAppearance.

Interfaces vs. abstract classes

Abstract classes and interfaces are semantically different, although their usage can overlap.

An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.

An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.

WPF: ItemsControl with scrollbar (ScrollViewer)

Put your ScrollViewer in a DockPanel and set the DockPanel MaxHeight property

[...]
<DockPanel MaxHeight="700">
  <ScrollViewer VerticalScrollBarVisibility="Auto">
   <ItemsControl ItemSource ="{Binding ...}">
     [...]
   </ItemsControl>
  </ScrollViewer>
</DockPanel>
[...]

What is the purpose of a self executing function in javascript?

I can't believe none of the answers mention implied globals.

The (function(){})() construct does not protect against implied globals, which to me is the bigger concern, see http://yuiblog.com/blog/2006/06/01/global-domination/

Basically the function block makes sure all the dependent "global vars" you defined are confined to your program, it does not protect you against defining implicit globals. JSHint or the like can provide recommendations on how to defend against this behavior.

The more concise var App = {} syntax provides a similar level of protection, and may be wrapped in the function block when on 'public' pages. (see Ember.js or SproutCore for real world examples of libraries that use this construct)

As far as private properties go, they are kind of overrated unless you are creating a public framework or library, but if you need to implement them, Douglas Crockford has some good ideas.

error: passing xxx as 'this' argument of xxx discards qualifiers

Let's me give a more detail example. As to the below struct:

struct Count{
    uint32_t c;

    Count(uint32_t i=0):c(i){}

    uint32_t getCount(){
        return c;
    }

    uint32_t add(const Count& count){
        uint32_t total = c + count.getCount();
        return total;
    }
};

enter image description here

As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object. In the method add count is declared as const object, but the method getCount is not const method, so count.getCount() may change the members in count.

Compile error as below(core message in my compiler):

error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]

To solve the above problem, you can:

  1. change the method uint32_t getCount(){...} to uint32_t getCount() const {...}. So count.getCount() won't change the members in count.

or

  1. change uint32_t add(const Count& count){...} to uint32_t add(Count& count){...}. So count don't care about changing members in it.

As to you problem, objects in the std::set are stored as const StudentT, but the method getId and getName are not const, so you give the above error.

You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.

Regular expression to match non-ASCII characters?

I had a problem with \p working as expected, so I just used a different strategy like:

([^\t]+)\t

Find anything that is not a tab character until the next tab character... obviously this depends on your search source, but you get the idea. Now I don't have to figure out what unicode characters work and don't work etc.

nginx - read custom header from upstream server

Use $http_MY_CUSTOM_HEADER

You can write some-thing like

set my_header $http_MY_CUSTOM_HEADER;
if($my_header != 'some-value') {
#do some thing;
}

numbers not allowed (0-9) - Regex Expression in javascript

You could try something like this in javascript:
var regex = /[^a-zA-Z]/g;

and have a keyup event.
$("#nameofInputbox").value.replace(regex, "");

How to upload files on server folder using jsp

I found the similar problem and found the solution and i have blogged about how to upload the file using JSP , In that example i have used the absolute path. Note that if you want to route to some other URL based location you can put a ESB like WSO2 ESB