Programs & Examples On #Synchronous

Synchronous means that the caller of a function waits for the response or completion of the function before returning control to the main program

jQuery: Performing synchronous AJAX requests

As you're making a synchronous request, that should be

function getRemote() {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false
    }).responseText;
}

Example - http://api.jquery.com/jQuery.ajax/#example-3

PLEASE NOTE: Setting async property to false is deprecated and in the process of being removed (link). Many browsers including Firefox and Chrome have already started to print a warning in the console if you use this:

Chrome:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Firefox:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/

How to force Sequential Javascript Execution?

Another way to look at this is to daisy chain from one function to another. Have an array of functions that is global to all your called functions, say:

arrf: [ f_final
       ,f
       ,another_f
       ,f_again ],

Then setup an array of integers to the particular 'f''s you want to run, e.g

var runorder = [1,3,2,0];

Then call an initial function with 'runorder' as a parameter, e.g. f_start(runorder);

Then at the end of each function, just pop the index to the next 'f' to execute off the runorder array and execute it, still passing 'runorder' as a parameter but with the array reduced by one.

var nextf = runorder.shift();
arrf[nextf].call(runorder);

Obviously this terminates in a function, say at index 0, that does not chain onto another function. This is completely deterministic, avoiding 'timers'.

asynchronous vs non-blocking

A nonblocking call returns immediately with whatever data are available: the full number of bytes requested, fewer, or none at all.

An asynchronous call requests a transfer that will be performed in its whole(entirety) but will complete at some future time.

JavaScript: Global variables after Ajax requests

The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after the request completes, like you are expecting.

What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,

var it_works = false;

$.ajax({
  url: 'some_file.php',
  async: false,  # makes request synchronous
  success: function() {
    it_works = true;
  }
});

alert(it_works);

Asynchronous vs synchronous execution, what does it really mean?

A synchronous operation does its work before returning to the caller.

An asynchronous operation does (most or all of) its work after returning to the caller.

How to make JQuery-AJAX request synchronous

From jQuery.ajax()

async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

So in your request, you must do async: false instead of async: "false".

Update:

The return value of ajaxSubmit is not the return value of the success: function(){...}. ajaxSubmit returns no value at all, which is equivalent to undefined, which in turn evaluates to true.

And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.

If you want to submit the form only, when the response is "Successful", you must return false from ajaxSubmit and then submit the form in the success function, as @halilb already suggested.

Something along these lines should work

function ajaxSubmit() {
    var password = $.trim($('#employee_password').val());
    $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(response) {
            if(response == "Successful")
            {
                $('form').removeAttr('onsubmit'); // prevent endless loop
                $('form').submit();
            }
        }
    });

    return false;
}

What is the difference between synchronous and asynchronous programming (in node.js)

The main difference is with asynchronous programming, you don't stop execution otherwise. You can continue executing other code while the 'request' is being made.

Simplest way to wait some asynchronous tasks complete, in Javascript?

Use Promises.

var mongoose = require('mongoose');

mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;

var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
  return new Promise(function(resolve, reject) {
    var collection = conn.collection(name);
    collection.drop(function(err) {
      if (err) { return reject(err); }
      console.log('dropped ' + name);
      resolve();
    });
  });
});

Promise.all(promises)
.then(function() { console.log('all dropped)'); })
.catch(console.error);

This drops each collection, printing “dropped” after each one, and then prints “all dropped” when complete. If an error occurs, it is displayed to stderr.


Previous answer (this pre-dates Node’s native support for Promises):

Use Q promises or Bluebird promises.

With Q:

var Q = require('q');
var mongoose = require('mongoose');

mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;

var promises = ['aaa','bbb','ccc'].map(function(name){
    var collection = conn.collection(name);
    return Q.ninvoke(collection, 'drop')
      .then(function() { console.log('dropped ' + name); });
});

Q.all(promises)
.then(function() { console.log('all dropped'); })
.fail(console.error);

With Bluebird:

var Promise = require('bluebird');
var mongoose = Promise.promisifyAll(require('mongoose'));

mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;

var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
  return conn.collection(name).dropAsync().then(function() {
    console.log('dropped ' + name);
  });
});

Promise.all(promises)
.then(function() { console.log('all dropped'); })
.error(console.error);

document.createElement("script") synchronously

This is way late but for future reference to anyone who'd like to do this, you can use the following:

function require(file,callback){
    var head=document.getElementsByTagName("head")[0];
    var script=document.createElement('script');
    script.src=file;
    script.type='text/javascript';
    //real browsers
    script.onload=callback;
    //Internet explorer
    script.onreadystatechange = function() {
        if (this.readyState == 'complete') {
            callback();
        }
    }
    head.appendChild(script);
}

I did a short blog post on it some time ago http://crlog.info/2011/10/06/dynamically-requireinclude-a-javascript-file-into-a-page-and-be-notified-when-its-loaded/

How to wrap async function calls into a sync function in Node.js or Javascript?

Javascript is a single threaded language, you don't want to block your whole server! Async code eliminates, race conditions by making dependencies explicit.

Learn to love asynchronous code!

Have a look at promises for asynchronous code without creating a pyramid of callback hell. I recommend the promiseQ library for node.js

httpGet(url.parse("http://example.org/")).then(function (res) {
    console.log(res.statusCode);  // maybe 302
    return httpGet(url.parse(res.headers["location"]));
}).then(function (res) {
    console.log(res.statusCode);  // maybe 200
});

http://howtonode.org/promises

EDIT: this is by far my most controversial answer, node now has yield keyword, which allows you to treat async code as if it were sychronous. http://blog.alexmaccaw.com/how-yield-will-transform-node

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

How to save a bitmap on internal storage

Modify onClick() as follows:

@Override
public void onClick(View v) {
    if(v == btn) {
        canvas=sv.getHolder().lockCanvas();
        if(canvas!=null) {
            canvas.drawBitmap(bitmap, 100, 100, null);
            sv.getHolder().unlockCanvasAndPost(canvas);
        }
    } else if(v == btn1) {
        saveBitmapToInternalStorage(bitmap);
    }
}

There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.

I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:

if(v == btn) {
    ...
    btn1.setEnabled(true);
}

Adding attributes to an XML node

If you serialize the object that you have, you can do something like this by using "System.Xml.Serialization.XmlAttributeAttribute" on every property that you want to be specified as an attribute in your model, which in my opinion is a lot easier:

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class UserNode
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string userName { get; set; }

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string passWord { get; set; }

    public int Age { get; set; }
    public string Name { get; set; }         
 }

 public class LoginNode 
 {
    public UserNode id { get; set; }
 }

Then you just serialize to XML an instance of LoginNode called "Login", and that's it!

Here you have a few examples to serialize and object to XML, but I would suggest to create an extension method in order to be reusable for other objects.

REST API - file (ie images) processing - best practices

There are several decisions to make:

  1. The first about resource path:

    • Model the image as a resource on its own:

      • Nested in user (/user/:id/image): the relationship between the user and the image is made implicitly

      • In the root path (/image):

        • The client is held responsible for establishing the relationship between the image and the user, or;

        • If a security context is being provided with the POST request used to create an image, the server can implicitly establish a relationship between the authenticated user and the image.

    • Embed the image as part of the user

  2. The second decision is about how to represent the image resource:

    • As Base 64 encoded JSON payload
    • As a multipart payload

This would be my decision track:

  • I usually favor design over performance unless there is a strong case for it. It makes the system more maintainable and can be more easily understood by integrators.
  • So my first thought is to go for a Base64 representation of the image resource because it lets you keep everything JSON. If you chose this option you can model the resource path as you like.
    • If the relationship between user and image is 1 to 1 I'd favor to model the image as an attribute specially if both data sets are updated at the same time. In any other case you can freely choose to model the image either as an attribute, updating the it via PUT or PATCH, or as a separate resource.
  • If you choose multipart payload I'd feel compelled to model the image as a resource on is own, so that other resources, in our case, the user resource, is not impacted by the decision of using a binary representation for the image.

Then comes the question: Is there any performance impact about choosing base64 vs multipart?. We could think that exchanging data in multipart format should be more efficient. But this article shows how little do both representations differ in terms of size.

My choice Base64:

  • Consistent design decision
  • Negligible performance impact
  • As browsers understand data URIs (base64 encoded images), there is no need to transform these if the client is a browser
  • I won't cast a vote on whether to have it as an attribute or standalone resource, it depends on your problem domain (which I don't know) and your personal preference.

Attempt to set a non-property-list object as an NSUserDefaults

Swift 5: The Codable protocol can be used instead of NSKeyedArchiever.

struct User: Codable {
    let id: String
    let mail: String
    let fullName: String
}

The Pref struct is custom wrapper around the UserDefaults standard object.

struct Pref {
    static let keyUser = "Pref.User"
    static var user: User? {
        get {
            if let data = UserDefaults.standard.object(forKey: keyUser) as? Data {
                do {
                    return try JSONDecoder().decode(User.self, from: data)
                } catch {
                    print("Error while decoding user data")
                }
            }
            return nil
        }
        set {
            if let newValue = newValue {
                do {
                    let data = try JSONEncoder().encode(newValue)
                    UserDefaults.standard.set(data, forKey: keyUser)
                } catch {
                    print("Error while encoding user data")
                }
            } else {
                UserDefaults.standard.removeObject(forKey: keyUser)
            }
        }
    }
}

So you can use it this way:

Pref.user?.name = "John"

if let user = Pref.user {...

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Your json contains an array, but you're trying to parse it as an object. This error occurs because objects must start with {.

You have 2 options:

  1. You can get rid of the ShopContainer class and use Shop[] instead

    ShopContainer response  = restTemplate.getForObject(
        url, ShopContainer.class);
    

    replace with

    Shop[] response  = restTemplate.getForObject(url, Shop[].class);
    

    and then make your desired object from it.

  2. You can change your server to return an object instead of a list

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
    

    replace with

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
        new ShopContainer(list));
    

Regular expression for extracting tag attributes

Just to agree with everyone else: don't parse HTML using regexp.

It isn't possible to create an expression that will pick out attributes for even a correct piece of HTML, never mind all the possible malformed variants. Your regexp is already pretty much unreadable even without trying to cope with the invalid lack of quotes; chase further into the horror of real-world HTML and you will drive yourself crazy with an unmaintainable blob of unreliable expressions.

There are existing libraries to either read broken HTML, or correct it into valid XHTML which you can then easily devour with an XML parser. Use them.

PHP Warning: Division by zero

A lot of the answers here do not work for (string)"0.00".

Try this:

if (isset($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

Or even more strict:

if (isset($_POST['num1']) && is_numeric($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

How can I get the average (mean) of selected columns

Try using rowMeans:

z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)

  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

Fixing Sublime Text 2 line endings?

The comment states

// Determines what character(s) are used to terminate each line in new files.
// Valid values are 'system' (whatever the OS uses), 'windows' (CRLF) and
// 'unix' (LF only).

You are setting

"default_line_ending": "LF",

You should set

"default_line_ending": "unix",

Remove leading and trailing spaces?

Should be noted that strip() method would trim any leading and trailing whitespace characters from the string (if there is no passed-in argument). If you want to trim space character(s), while keeping the others (like newline), this answer might be helpful:

sample = '  some string\n'
sample_modified = sample.strip(' ')

print(sample_modified)  # will print 'some string\n'

strip([chars]): You can pass in optional characters to strip([chars]) method. Python will look for occurrences of these characters and trim the given string accordingly.

C++ printing spaces or tabs given a user input integer

Appending single space to output file with stream variable.

// declare output file stream varaible and open file ofstream fout; fout.open("flux_capacitor.txt"); fout << var << " ";

Multiplying Two Columns in SQL Server

select InitialPayment * MonthlyPayRate as SomeRandomCalculation from Payment

Jinja2 shorthand conditional

Yes, it's possible to use inline if-expressions:

{{ 'Update' if files else 'Continue' }}

javascript date + 7 days

Without declaration

To return timestamp

new Date().setDate(new Date().getDate() + 7)

To return date

new Date(new Date().setDate(new Date().getDate() + 7))

Save results to csv file with Python

I know the question is asking about your "csv" package implementation, but for your information, there are options that are much simpler — numpy, for instance.

import numpy as np
np.savetxt('data.csv', (col1_array, col2_array, col3_array), delimiter=',')

(This answer posted 6 years later, for posterity's sake.)

In a different case similar to what you're asking about, say you have two columns like this:

names = ['Player Name', 'Foo', 'Bar']
scores = ['Score', 250, 500]

You could save it like this:

np.savetxt('scores.csv', [p for p in zip(names, scores)], delimiter=',', fmt='%s')

scores.csv would look like this:

Player Name,Score
Foo,250
Bar,500

What is Express.js?

  1. Express.js is a modular web framework for Node.js
  2. It is used for easier creation of web applications and services
  3. Express.js simplifies development and makes it easier to write secure, modular and fast applications. You can do all that in plain old Node.js, but some bugs can (and will) surface, including security concerns (eg. not escaping a string properly)
  4. Redis is an in-memory database system known for its fast performance. No, but you can use it with Express.js using a redis client

I couldn't be more concise than this. For all your other needs and information, Google is your friend.

How to compare if two structs, slices or maps are equal?

Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb

func compare(a, b T) bool {
  if &a == &b {
    return true
  }
  if a.X != b.X || a.Y != b.Y {
    return false
  }
  if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
    return false
  }
  for i, v := range a.Z {
    if b.Z[i] != v {
      return false
    }
  }
  for k, v := range a.M {
    if b.M[k] != v {
      return false
    }
  }
  return true
}

What difference does .AsNoTracking() make?

AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers).

This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.

For these cases the "key" can be set to any non-nullable column but then AsNoTracking() must be used with every query else records (duplicate by key) will be skipped.

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

it should help:

android {
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

To avoid missing link errors add to dependencies

dependencies {
    provided 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}

or

dependencies {
    compileOnly 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}

because

Warning: Configuration 'provided' is obsolete and has been replaced with 'compileOnly'.

Android: Creating a Circular TextView?

This my actually working solution

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    >
    <!-- The fill color -->
    <solid android:color="#ffff" />
    <!-- Just to add a border -->
    <stroke
        android:color="#8000"
        android:width="2dp"
    />
</shape>

Make sure your TextView width and height match (be the same in dp), if you want a perfect (unstretched) circle.

Make sure that the text fits into a circle, by either shortening your text OR enlarging your circle OR making your text size smaller OR reduce your padding/s, if any. OR a combination of the above suggestions.

[EDIT]

For what I can see in your pictures, you want to add too much text on a line, for pure circles.
Consider that the text should have a square aspect, so you can either wrap it (use \n) or just put the numbers inside the circles and put the writings above or uder the corresponding circle.

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

I also tried deleting the database again, called update-database and then add-migration. I ended up with an additional migration that seems not to change anything (see below)

Based on above details, I think you have done last thing first. If you run Update database before Add-migration, it won't update the database with your migration schemas. First you need to add the migration and then run update command.

Try them in this order using package manager console.

PM> Enable-migrations //You don't need this as you have already done it
PM> Add-migration Give_it_a_name
PM> Update-database

How to get the index of an item in a list in a single step?

If you don't want to use LINQ, then:

int index;
for (int i = 0; i < myList.Count; i++)
{
    if (myList[i].Prop == oProp)
    {
       index = i;
       break;
    }
}

this way you are iterating list only once.

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

I use Apache server, so I've used mod_proxy module. Enable modules:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Then add:

ProxyPass /your-proxy-url/ http://service-url:serviceport/

Finally, pass proxy-url to your script.

How to set text color to a text view programmatically

yourTextView.setTextColor(color);

Or, in your case: yourTextView.setTextColor(0xffbdbdbd);

How can I change the current URL?

Simple assigning to window.location or window.location.href should be fine:

window.location = newUrl;

However, your new URL will cause the browser to load the new page, but it sounds like you'd like to modify the URL without leaving the current page. You have two options for this:

  1. Use the URL hash. For example, you can go from example.com to example.com#foo without loading a new page. You can simply set window.location.hash to make this easy. Then, you should listen to the HTML5 hashchange event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers.

  2. You could use HTML5 History to modify the path without reloading the page. This will allow you to change from example.com/foo to example.com/bar. Using this is easy:

    window.history.pushState("example.com/foo");

    When the user presses "back", you'll receive the window's popstate event, which you can easily listen to (jQuery):

    $(window).bind("popstate", function(e) { alert("location changed"); });

    Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.

Log.INFO vs. Log.DEBUG

Also remember that all info(), error(), and debug() logging calls provide internal documentation within any application.

How to build a RESTful API?

(1) How do I ... build those URI's? Do I need to write a PHP code at that URI?

There is no standard for how an API URI scheme should be set up, but it's common to have slash-separated values. For this you can use...

$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));

...to get an array of slash-separated values in the URI after the file name.

Example: Assuming you have an API file api.php in your application somewhere and you do a request for api.php/members/3, then $apiArgArray will be an array containing ['members', '3']. You can then use those values to query your database or do other processing.

(2) How do I build the JSON objects to return as a response?

You can take any PHP object and turn it into JSON with json_encode. You'll also want to set the appropriate header.

header('Content-Type: application/json');
$myObject = (object) array( 'property' => 'value' ); // example
echo json_encode($myObject); // outputs JSON text

All this is good for an API that returns JSON, but the next question you should ask is:

(3) How do I make my API RESTful?

For that we'll use $_SERVER['REQUEST_METHOD'] to get the method being used, and then do different things based on that. So the final result is something like...

header('Content-Type: application/json');
$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
$returnObject = (object) array();
/* Based on the method, use the arguments to figure out
   whether you're working with an individual or a collection, 
   then do your processing, and ultimately set $returnObject */
switch ($_SERVER['REQUEST_METHOD']) {
  case 'GET':
    // List entire collection or retrieve individual member
    break;
  case 'PUT':       
    // Replace entire collection or member
    break;  
  case 'POST':      
    // Create new member
    break;
  case 'DELETE':    
    // Delete collection or member
    break;
}
echo json_encode($returnObject);

Sources: https://stackoverflow.com/a/897311/1766230 and http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services

RecyclerView - Get view at particular position

This is what you're looking for.

I had this problem too. And like you, the answer is very hard to find. But there IS an easy way to get the ViewHolder from a specific position (something you'll probably do a lot in the Adapter).

myRecyclerView.findViewHolderForAdapterPosition(pos);

NOTE: If the View has been recycled, this will return null. Thanks to Michael for quickly catching my important omission.

Convert Select Columns in Pandas Dataframe to Numpy Array

The fastest and easiest way is to use .as_matrix(). One short line:

df.iloc[:,[1,2,3]].as_matrix()

Gives:

array([[3, 2, 0.816497],
   [0, 'NaN', 'NaN'],
   [2, 51, 50.0]], dtype=object)

By using indices of the columns, you can use this code for any dataframe with different column names.

Here are the steps for your example:

import pandas as pd
columns = ['viz', 'a1_count', 'a1_mean', 'a1_std']
index = [0,1,2]
vals = {'viz': ['n','n','n'], 'a1_count': [3,0,2], 'a1_mean': [2,'NaN', 51], 'a1_std': [0.816497, 'NaN', 50.000000]}
df = pd.DataFrame(vals, columns=columns, index=index)

Gives:

   viz  a1_count a1_mean    a1_std
0   n         3       2  0.816497
1   n         0     NaN       NaN
2   n         2      51        50

Then:

x1 = df.iloc[:,[1,2,3]].as_matrix()

Gives:

array([[3, 2, 0.816497],
   [0, 'NaN', 'NaN'],
   [2, 51, 50.0]], dtype=object)

Where x1 is numpy.ndarray.

Passing parameters to JavaScript files

You can pass parameters with arbitrary attributes. This works in all recent browsers.

<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>

Inside somefile.js you can get passed variables values this way:

........

var this_js_script = $('script[src*=somefile]'); // or better regexp to get the file name..

var my_var_1 = this_js_script.attr('data-my_var_1');   
if (typeof my_var_1 === "undefined" ) {
   var my_var_1 = 'some_default_value';
}
alert(my_var_1); // to view the variable value

var my_var_2 = this_js_script.attr('data-my_var_2');   
if (typeof my_var_2 === "undefined" ) {
   var my_var_2 = 'some_default_value';
}
alert(my_var_2); // to view the variable value

...etc...

How to convert Java String into byte[]?

I know I'm a little late tothe party but thisworks pretty neat (our professor gave it to us)

public static byte[] asBytes (String s) {                   
           String tmp;
           byte[] b = new byte[s.length() / 2];
           int i;
           for (i = 0; i < s.length() / 2; i++) {
             tmp = s.substring(i * 2, i * 2 + 2);
             b[i] = (byte)(Integer.parseInt(tmp, 16) & 0xff);
           }
           return b;                                            //return bytes
    }

Java String new line

Try:

System.out.println("I\nam\na\nboy");

What is the best way to modify a list in a 'foreach' loop?

You should really use for() instead of foreach() in this case.

C#: Printing all properties of an object

Regarding TypeDescriptor from Sean's reply (I can't comment because I have a bad reputation)... one advantage to using TypeDescriptor over GetProperties() is that TypeDescriptor has a mechanism for dynamically attaching properties to objects at runtime and normal reflection will miss these.

For example, when working with PowerShell's PSObject, which can have properties and methods added at runtime, they implemented a custom TypeDescriptor which merges these members in with the standard member set. By using TypeDescriptor, your code doesn't need to be aware of that fact.

Components, controls, and I think maybe DataSets also make use of this API.

PHPExcel auto size column width

foreach(range('B','G') as $columnID)
{
    $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}

Where does System.Diagnostics.Debug.Write output appear?

The Diagnostics messages are displayed in the Output Window.

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

The problem is that what you are trying to do shouldn't be done. You shouldn't be inflating fragments inside other fragments. From Android's documentation:

Note: You cannot inflate a layout into a fragment when that layout includes a <fragment>. Nested fragments are only supported when added to a fragment dynamically.

While you may be able to accomplish the task with the hacks presented here, I highly suggest you don't do it. Its impossible to be sure that these hacks will handle what each new Android OS does when you try to inflate a layout for a fragment containing another fragment.

The only Android-supported way to add a fragment to another fragment is via a transaction from the child fragment manager.

Simply change your XML layout into an empty container (add an ID if needed):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapFragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
</LinearLayout>

Then in the Fragment onViewCreated(View view, @Nullable Bundle savedInstanceState) method:

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    FragmentManager fm = getChildFragmentManager();
    SupportMapFragment mapFragment = (SupportMapFragment) fm.findFragmentByTag("mapFragment");
    if (mapFragment == null) {
        mapFragment = new SupportMapFragment();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.mapFragmentContainer, mapFragment, "mapFragment");
        ft.commit();
        fm.executePendingTransactions();
    }
    mapFragment.getMapAsync(callback);
}

How to convert An NSInteger to an int?

If you want to do this inline, just cast the NSUInteger or NSInteger to an int:

int i = -1;
NSUInteger row = 100;
i > row // true, since the signed int is implicitly converted to an unsigned int
i > (int)row // false

CSS performance relative to translateZ(0)

I can attest to the fact that -webkit-transform: translate3d(0, 0, 0); will mess with the new position: -webkit-sticky; property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.

Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased on the html element. I was testing this behavior in iOS7 and Android.

How do I use cascade delete with SQL Server?

ON DELETE CASCADE
It specifies that the child data is deleted when the parent data is deleted.

CREATE TABLE products
( product_id INT PRIMARY KEY,
  product_name VARCHAR(50) NOT NULL,
  category VARCHAR(25)
);

CREATE TABLE inventory
( inventory_id INT PRIMARY KEY,
  product_id INT NOT NULL,
  quantity INT,
  min_level INT,
  max_level INT,
  CONSTRAINT fk_inv_product_id
    FOREIGN KEY (product_id)
    REFERENCES products (product_id)
    ON DELETE CASCADE
);

For this foreign key, we have specified the ON DELETE CASCADE clause which tells SQL Server to delete the corresponding records in the child table when the data in the parent table is deleted. So in this example, if a product_id value is deleted from the products table, the corresponding records in the inventory table that use this product_id will also be deleted.

MySQL and PHP - insert NULL rather than empty string

For some reason, radhoo's solution wouldn't work for me. When I used the following expression:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')?"NULL":("'".$val1."'")) . ", ".
    (($val2=='')?"NULL":("'".$val2."'")) . 
    ")";

'null' (with quotes) was inserted instead of null without quotes, making it a string instead of an integer. So I finally tried:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')? :("'".$val1."'")) . ", ".
    (($val2=='')? :("'".$val2."'")) . 
    ")";

The blank resulted in the correct null (unquoted) being inserted into the query.

JavaScript error: "is not a function"

Your LMSInitialize function is declared inside Scorm_API_12 function. So it can be seen only in Scorm_API_12 function's scope.

If you want to use this function like API.LMSInitialize(""), declare Scorm_API_12 function like this:

function Scorm_API_12() {
var Initialized = false;

this.LMSInitialize = function(param) {
    errorCode = "0";
    if (param == "") {
        if (!Initialized) {
            Initialized = true;
            errorCode = "0";
            return "true";
        } else {
            errorCode = "101";
        }
    } else {
        errorCode = "201";
    }
    return "false";
}

// some more functions, omitted.
}

var API = new Scorm_API_12();

How do I solve this "Cannot read property 'appendChild' of null" error?

Just reorder or make sure, the (DOM or HTML) is loaded before the JavaScript.

SQL Server: IF EXISTS ; ELSE

Try this:

Update TableB Set
  Code = Coalesce(
    (Select Max(Value)
    From TableA 
    Where Id = b.Id), 123)
From TableB b

How do I find out what type each object is in a ArrayList<Object>?

In C#:
Fixed with recommendation from Mike

ArrayList list = ...;
// List<object> list = ...;
foreach (object o in list) {
    if (o is int) {
        HandleInt((int)o);
    }
    else if (o is string) {
        HandleString((string)o);
    }
    ...
}

In Java:

ArrayList<Object> list = ...;
for (Object o : list) {
    if (o instanceof Integer)) {
        handleInt((Integer o).intValue());
    }
    else if (o instanceof String)) {
        handleString((String)o);
    }
    ...
}

Ctrl+click doesn't work in Eclipse Juno

I had the exact same issue while working on a GIT based project. I was able to resolve by changing the way i was importing the project in the workspace.

Wrong way : Import project to workspace from GIT perspective , like right click on the GIT URL and selecting the option import which was not recognizing the project facets.

Right way (which resolved my issue): clone the project in GIT perspective , change to JEE Perspective , then import from file > import > Existing Maven Project .

mysql datatype for telephone number and address

Store them as two fields for phone numbers - a "number" and a "mask" as TinyText types which do not need more than 255 items.

Before we store the files we parse the phone number to get the formatting that has been used and that creates the mask, we then store the number a digits only e.g.

Input: (0123) 456 7890
Number: 01234567890
Mask: (nnnn)_nnn_nnnn

Theoretically this allows us to perform comparison searches on the Number field such as getting all phone numbers that begin with a specific area code, without having to worry how it was input by the users

How can I select random files from a directory in bash?

I use this: it uses temporary file but goes deeply in a directory until it find a regular file and return it.

# find for a quasi-random file in a directory tree:

# directory to start search from:
ROOT="/";  

tmp=/tmp/mytempfile    
TARGET="$ROOT"
FILE=""; 
n=
r=
while [ -e "$TARGET" ]; do 
    TARGET="$(readlink -f "${TARGET}/$FILE")" ; 
    if [ -d "$TARGET" ]; then
      ls -1 "$TARGET" 2> /dev/null > $tmp || break;
      n=$(cat $tmp | wc -l); 
      if [ $n != 0 ]; then
        FILE=$(shuf -n 1 $tmp)
# or if you dont have/want to use shuf:
#       r=$(($RANDOM % $n)) ; 
#       FILE=$(tail -n +$(( $r + 1 ))  $tmp | head -n 1); 
      fi ; 
    else
      if [ -f "$TARGET"  ] ; then
        rm -f $tmp
        echo $TARGET
        break;
      else 
        # is not a regular file, restart:
        TARGET="$ROOT"
        FILE=""
      fi
    fi
done;

Bootstrap 3 - How to load content in modal body via AJAX?

This is actually super simple with just a little bit of added javascript. The link's href is used as the ajax content source. Note that for Bootstrap 3.* we set data-remote="false" to disable the deprecated Bootstrap load function.

JavaScript:

// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});

Html (based on the official example):

<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
    Launch Modal
</a>

<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Try it yourself: https://jsfiddle.net/ednon5d1/

Include PHP file into HTML file

Create a .htaccess file in directory and add this code to .htaccess file

AddHandler x-httpd-php .html .htm

or

AddType application/x-httpd-php .html .htm

It will force Apache server to parse HTML or HTM files as PHP Script

Is it possible to install both 32bit and 64bit Java on Windows 7?

To install 32-bit Java on Windows 7 (64-bit OS + Machine). You can do:

1) Download JDK: http://javadl.sun.com/webapps/download/AutoDL?BundleId=58124
2) Download JRE: http://www.java.com/en/download/installed.jsp?jre_version=1.6.0_22&vendor=Sun+Microsystems+Inc.&os=Linux&os_version=2.6.41.4-1.fc15.i686

3) System variable create: C:\program files (x86)\java\jre6\bin\

4) Anywhere you type java -version

it use 32-bit on (64-bit). I have to use this because lots of third party libraries do not work with 64-bit. Java wake up from the hell, give us peach :P. Go-language is killer.

What's the main difference between int.Parse() and Convert.ToInt32

int.Parse(string s)

  • Integer in RANGE > returns integer value
  • Null value > ArguementNullException
  • Not in format > FormatException
  • Value not in RANGE > OverflowException

Convert.ToInt32(string s)

  • Integer in RANGE > returns integer value
  • Null value > returns "0"
  • Not in format > FormatException
  • Value not in RANGE > OverflowException

bool isParsed = int.TryParse(string s,out res)

  • Integer in RANGE > returns integer value, isParsed = true
  • Null value > returns "0", isParsed = false
  • Not in format > returns "0", isParsed = false
  • Value not in RANGE > returns "0", isParsed = false

Try this code below.....

class Program
{
    static void Main(string[] args)
    {
        string strInt = "24532";
        string strNull = null;
        string strWrongFrmt = "5.87";
        string strAboveRange = "98765432123456";
        int res;
        try
        {
            // int.Parse() - TEST
            res = int.Parse(strInt); // res = 24532
            res = int.Parse(strNull); // System.ArgumentNullException
            res = int.Parse(strWrongFrmt); // System.FormatException
            res = int.Parse(strAboveRange); // System.OverflowException

            // Convert.ToInt32(string s) - TEST
            res = Convert.ToInt32(strInt); // res = 24532
            res = Convert.ToInt32(strNull); // res = 0
            res = Convert.ToInt32(strWrongFrmt); // System.FormatException
            res = Convert.ToInt32(strAboveRange); //System.OverflowException

            // int.TryParse(string s, out res) - Test
            bool isParsed;
            isParsed = int.TryParse(strInt, out res); // isParsed = true, res = 24532
            isParsed = int.TryParse(strNull, out res); // isParsed = false, res = 0
            isParsed = int.TryParse(strWrongFrmt, out res); // isParsed = false, res = 0
            isParsed = int.TryParse(strAboveRange, out res); // isParsed = false, res = 0 
        }
        catch(Exception e)
        {
            Console.WriteLine("Check this.\n" + e.Message);
        }
    }

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Make the id parameter be a nullable int:

public ActionResult Edit(int? id, User collection)

And then add the validation:

if (Id == null) ...

Is there a way to check for both `null` and `undefined`?

The simplest way is to use:

import { isNullOrUndefined } from 'util';

and than:

if (!isNullOrUndefined(foo))

How to use orderby with 2 fields in linq?

MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

What is VanillaJS?

This is a joke for those who are excited about the JavaScript frameworks and do not know the pure Javascript.

So VanillaJS is the same as pure Javascript.

Vanilla in slang means:

unexciting, normal, conventional, boring

Here is a nice presentation on YouTube about VanillaJS: What is Vanilla JS?

WPF popup window

In WPF there is a control named Popup.

Popup myPopup = new Popup();
//(...)
myPopup.IsOpen = true;

JSON forEach get Key and Value

Use forEach in combo with Object.entries().

_x000D_
_x000D_
const WALLPAPERS = [{
  WALLPAPER_KEY: 'wallpaper.image',
  WALLPAPER_VALID_KEY: 'wallpaper.image.valid',
}, {
  WALLPAPER_KEY: 'lockscreen.image',
  WALLPAPER_VALID_KEY: 'lockscreen.image.valid',
}];

WALLPAPERS.forEach((obj) => {
  for (const [key, value] of Object.entries(obj)) {
    console.log(`${key} - ${value}`);
  }
});
_x000D_
_x000D_
_x000D_

How to convert vector to array

std::vector<double> vec;
double* arr = vec.data();

How to remove a build from itunes connect?

As I understand the new iTunesConnect philosophy :

  • you can upload some multiple "eligible" builds to iTunesConnect int the "pre release" tab
  • let some other testers test a specific build, via TestFlight (and declared as iTunesConnect users)
  • when you come to a stable version, select the correct build version, from the "Versions" tab to submit to the AppStore, the usual way.

To me, you can have like 150 build for a pre release, it doesn't matter.

Best way to remove duplicate entries from a data table

In order to distinct all datatable columns, you can easily retrieve the names of the columns in a string array

public static DataTable RemoveDuplicateRows(this DataTable dataTable)
{
    List<string> columnNames = new List<string>();
    foreach (DataColumn col in dataTable.Columns)
    {
        columnNames.Add(col.ColumnName);
    }
    return dataTable.DefaultView.ToTable(true, columnNames.Select(c => c.ToString()).ToArray());
}

As you can notice, I thought of using it as an extension to DataTable class

How to rename a table column in Oracle 10g

SQL> create table a(id number);

Table created.

SQL> alter table a rename column id to new_id;

Table altered.

SQL> desc a
 Name                                      Null?    Type
 ----------------------------------------- -------- -----------
 NEW_ID                                             NUMBER

How to increase the vertical split window size in Vim

CTRL-W >

and

CTRL-W <

to make the window wider or narrower.

MySQL Update Column +1?

update table_name set field1 = field1 + 1;

How to run a function when the page is loaded?

Try readystatechange

document.addEventListener('readystatechange', () => {    
  if (document.readyState == 'complete') codeAddress();
});

where states are:

  • loading - the document is loading (no fired in snippet)
  • interactive - the document is parsed, fired before DOMContentLoaded
  • complete - the document and resources are loaded, fired before window.onload

_x000D_
_x000D_
<script>_x000D_
  document.addEventListener("DOMContentLoaded", () => {_x000D_
    mydiv.innerHTML += `DOMContentLoaded (timestamp: ${Date.now()})</br>`;_x000D_
  });_x000D_
  _x000D_
  window.onload = () => {_x000D_
    mydiv.innerHTML += `window.onload (timestamp: ${Date.now()}) </br>` ;_x000D_
  } ;_x000D_
_x000D_
  document.addEventListener('readystatechange', () => {_x000D_
    mydiv.innerHTML += `ReadyState: ${document.readyState}  (timestamp: ${Date.now()})</br>`;_x000D_
    _x000D_
    if (document.readyState == 'complete') codeAddress();_x000D_
  });_x000D_
_x000D_
  function codeAddress() {_x000D_
    mydiv.style.color = 'red';_x000D_
  }_x000D_
</script>_x000D_
_x000D_
<div id='mydiv'></div>
_x000D_
_x000D_
_x000D_

Add a Progress Bar in WebView

Put a progress bar and the webview inside a relativelayout and set the properties for the progress bar as follows,

  1. Make its visibility as GONE.
  2. CENTRE it in the Relativelayout.

and then in onPageStarted() of the webclient make the progress bar visible so that it shows the progressbar when you have clicked on a link. In onPageFinished() make the progress bar visiblility as GONE so that it disappears when the page has finished loading... This will work fine for your scenario. Hope this helps...

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

before going for the step "compile -DIPLIB=NONE filename.cxx" take the path of VIsual Studio installation upto the vcvarsall batch file and change the configuration as shown below.

*C:\apps\MVS9\VC\vcvarsall.bat x86_amd64*

now next step should be

compile -64bit -DIPLIB=none filename.cxx

this solved the problem for me

Bootstrap: adding gaps between divs

An alternative way to accomplish what you are asking, without having problems on the mobile version of your website, (Remember that the margin attribute will brake your responsive layout on mobile version thus you have to add on your element a supplementary attribute like @media (min-width:768px){ 'your-class'{margin:0}} to override the previous margin)

is to nest your class in your preferred div and then add on your class the margin option you want

like the following example: HTML

<div class="container">
  <div class="col-md-3 col-xs-12">
   <div class="events">
     <img src="..."  class="img-responsive" alt="...."/>
     <div class="figcaption">
       <h2>Event Title</h2>
       <p>Event Description.</p>
     </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
</div>

And on your CSS you just add the margin option on your class which in this example is "events" like:

.events{
margin: 20px 10px;
}

By this method you will have all the wanted space between your divs making sure you do not brake anything on your website's mobile and tablet versions.

Why use pip over easy_install?

REQUIREMENTS files.

Seriously, I use this in conjunction with virtualenv every day.


QUICK DEPENDENCY MANAGEMENT TUTORIAL, FOLKS

Requirements files allow you to create a snapshot of all packages that have been installed through pip. By encapsulating those packages in a virtualenvironment, you can have your codebase work off a very specific set of packages and share that codebase with others.

From Heroku's documentation https://devcenter.heroku.com/articles/python

You create a virtual environment, and set your shell to use it. (bash/*nix instructions)

virtualenv env
source env/bin/activate

Now all python scripts run with this shell will use this environment's packages and configuration. Now you can install a package locally to this environment without needing to install it globally on your machine.

pip install flask

Now you can dump the info about which packages are installed with

pip freeze > requirements.txt

If you checked that file into version control, when someone else gets your code, they can setup their own virtual environment and install all the dependencies with:

pip install -r requirements.txt

Any time you can automate tedium like this is awesome.

Convert SVG to PNG in Python

I did not find any of the answers satisfactory. All the mentioned libraries have some problem or the other like Cairo dropping support for python 3.6 (they dropped Python 2 support some 3 years ago!). Also, installing the mentioned libraries on the Mac was a pain.

Finally, I found the best solution was svglib + reportlab. Both installed without a hitch using pip and first call to convert from svg to png worked beautifully! Very happy with the solution.

Just 2 commands do the trick:

from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
drawing = svg2rlg("my.svg")
renderPM.drawToFile(drawing, "my.png", fmt="PNG")

Are there any limitations with these I should be aware of?

If (Array.Length == 0)

You can absolutely check an empty array's length. However, if you try to do that on a null reference you'll get an exception. I suspect that's what you're running into. You can cope with both though:

if (array == null || array.Length == 0)

If that isn't the cause, please give a short but complete program demonstrating the problem. If that was the cause, it's worth taking a moment to make sure you understand null references vs "empty" collections/strings/whatever.

Link to download apache http server for 64bit windows.

From: http://wiki.apache.org/httpd/FAQ#Where_can_I_download_.28certified.29_64_bit_Apache_httpd_binaries_for_Windows.3F

Where can I download (certified) 64 bit Apache httpd binaries for Windows?

Right now, there are none. The Apache Software Foundation produces Open Source Software. The 32 bit binaries provided are a courtesy of the community members.

Though there are some unofficial e.g. http://www.apachelounge.com/download/win64/, but I have no idea if they can be trusted.

How to print from Flask @app.route to python console

It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:

from __future__ import print_function # In python 2.7
import sys

@app.route('/button/')
def button_clicked():
    print('Hello world!', file=sys.stderr)
    return redirect('/')

Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post

Editing in the Chrome debugger

You can use "Overrides" in Chrome to persist javascript changes between page loads, even where you aren't hosting the original source.

  1. Create a folder under Developer Tools > Sources > Overrides
  2. Chrome will ask for permission to the folder, click Allow
  3. Edit the file in Sources>Page then save (ctrl-s). A purple dot will indicate the file is saved locally.

The Overrides sub tab in Chrome Developer Tools

Sort array by firstname (alphabetically) in Javascript

for a two factors sort (name and lastname):

_x000D_
_x000D_
users.sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : a.name.toLowerCase() > b.name.toLowerCase() ? 1 : a.lastname.toLowerCase() < b.lastname.toLowerCase() ? -1 : a.lastname.toLowerCase() > b.lastname.toLowerCase() ? 1 : 0)
_x000D_
_x000D_
_x000D_

Why are my PHP files showing as plain text?

Yet another reason (not for this case, but maybe it'll save some nerves for someone) is that in PHP 5.5 short open tags <? phpinfo(); ?> are disabled by default.

So the PHP interpreter would process code within short tags as plain text. In previous versions PHP this feature was enable by default. So the new behaviour can be a little bit mysterious.

Which characters need to be escaped when using Bash?

Using the print '%q' technique, we can run a loop to find out which characters are special:

#!/bin/bash
special=$'`!@#$%^&*()-_+={}|[]\\;\':",.<>?/ '
for ((i=0; i < ${#special}; i++)); do
    char="${special:i:1}"
    printf -v q_char '%q' "$char"
    if [[ "$char" != "$q_char" ]]; then
        printf 'Yes - character %s needs to be escaped\n' "$char"
    else
        printf 'No - character %s does not need to be escaped\n' "$char"
    fi
done | sort

It gives this output:

No, character % does not need to be escaped
No, character + does not need to be escaped
No, character - does not need to be escaped
No, character . does not need to be escaped
No, character / does not need to be escaped
No, character : does not need to be escaped
No, character = does not need to be escaped
No, character @ does not need to be escaped
No, character _ does not need to be escaped
Yes, character   needs to be escaped
Yes, character ! needs to be escaped
Yes, character " needs to be escaped
Yes, character # needs to be escaped
Yes, character $ needs to be escaped
Yes, character & needs to be escaped
Yes, character ' needs to be escaped
Yes, character ( needs to be escaped
Yes, character ) needs to be escaped
Yes, character * needs to be escaped
Yes, character , needs to be escaped
Yes, character ; needs to be escaped
Yes, character < needs to be escaped
Yes, character > needs to be escaped
Yes, character ? needs to be escaped
Yes, character [ needs to be escaped
Yes, character \ needs to be escaped
Yes, character ] needs to be escaped
Yes, character ^ needs to be escaped
Yes, character ` needs to be escaped
Yes, character { needs to be escaped
Yes, character | needs to be escaped
Yes, character } needs to be escaped

Some of the results, like , look a little suspicious. Would be interesting to get @CharlesDuffy's inputs on this.

Create a custom callback in JavaScript

function LoadData(callback) 
{
    alert('the data have been loaded');
    callback(loadedData, currentObject);
}

What data type to use for hashed password field and what length?

You might find this Wikipedia article on salting worthwhile. The idea is to add a set bit of data to randomize your hash value; this will protect your passwords from dictionary attacks if someone gets unauthorized access to the password hashes.

What is an undefined reference/unresolved external symbol error and how do I fix it?

Compiling a C++ program takes place in several steps, as specified by 2.2 (credits to Keith Thompson for the reference):

The precedence among the syntax rules of translation is specified by the following phases [see footnote].

  1. Physical source file characters are mapped, in an implementation-defined manner, to the basic source character set (introducing new-line characters for end-of-line indicators) if necessary. [SNIP]
  2. Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. [SNIP]
  3. The source file is decomposed into preprocessing tokens (2.5) and sequences of white-space characters (including comments). [SNIP]
  4. Preprocessing directives are executed, macro invocations are expanded, and _Pragma unary operator expressions are executed. [SNIP]
  5. Each source character set member in a character literal or a string literal, as well as each escape sequence and universal-character-name in a character literal or a non-raw string literal, is converted to the corresponding member of the execution character set; [SNIP]
  6. Adjacent string literal tokens are concatenated.
  7. White-space characters separating tokens are no longer significant. Each preprocessing token is converted into a token. (2.7). The resulting tokens are syntactically and semantically analyzed and translated as a translation unit. [SNIP]
  8. Translated translation units and instantiation units are combined as follows: [SNIP]
  9. All external entity references are resolved. Library components are linked to satisfy external references to entities not defined in the current translation. All such translator output is collected into a program image which contains information needed for execution in its execution environment. (emphasis mine)

[footnote] Implementations must behave as if these separate phases occur, although in practice different phases might be folded together.

The specified errors occur during this last stage of compilation, most commonly referred to as linking. It basically means that you compiled a bunch of implementation files into object files or libraries and now you want to get them to work together.

Say you defined symbol a in a.cpp. Now, b.cpp declared that symbol and used it. Before linking, it simply assumes that that symbol was defined somewhere, but it doesn't yet care where. The linking phase is responsible for finding the symbol and correctly linking it to b.cpp (well, actually to the object or library that uses it).

If you're using Microsoft Visual Studio, you'll see that projects generate .lib files. These contain a table of exported symbols, and a table of imported symbols. The imported symbols are resolved against the libraries you link against, and the exported symbols are provided for the libraries that use that .lib (if any).

Similar mechanisms exist for other compilers/ platforms.

Common error messages are error LNK2001, error LNK1120, error LNK2019 for Microsoft Visual Studio and undefined reference to symbolName for GCC.

The code:

struct X
{
   virtual void foo();
};
struct Y : X
{
   void foo() {}
};
struct A
{
   virtual ~A() = 0;
};
struct B: A
{
   virtual ~B(){}
};
extern int x;
void foo();
int main()
{
   x = 0;
   foo();
   Y y;
   B b;
}

will generate the following errors with GCC:

/home/AbiSfw/ccvvuHoX.o: In function `main':
prog.cpp:(.text+0x10): undefined reference to `x'
prog.cpp:(.text+0x19): undefined reference to `foo()'
prog.cpp:(.text+0x2d): undefined reference to `A::~A()'
/home/AbiSfw/ccvvuHoX.o: In function `B::~B()':
prog.cpp:(.text._ZN1BD1Ev[B::~B()]+0xb): undefined reference to `A::~A()'
/home/AbiSfw/ccvvuHoX.o: In function `B::~B()':
prog.cpp:(.text._ZN1BD0Ev[B::~B()]+0x12): undefined reference to `A::~A()'
/home/AbiSfw/ccvvuHoX.o:(.rodata._ZTI1Y[typeinfo for Y]+0x8): undefined reference to `typeinfo for X'
/home/AbiSfw/ccvvuHoX.o:(.rodata._ZTI1B[typeinfo for B]+0x8): undefined reference to `typeinfo for A'
collect2: ld returned 1 exit status

and similar errors with Microsoft Visual Studio:

1>test2.obj : error LNK2001: unresolved external symbol "void __cdecl foo(void)" (?foo@@YAXXZ)
1>test2.obj : error LNK2001: unresolved external symbol "int x" (?x@@3HA)
1>test2.obj : error LNK2001: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1A@@UAE@XZ)
1>test2.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall X::foo(void)" (?foo@X@@UAEXXZ)
1>...\test2.exe : fatal error LNK1120: 4 unresolved externals

Common causes include:

IntelliJ: Error:java: error: release version 5 not supported

You should do one more change by either below approaches:


1 Through IntelliJ GUI

As mentioned by 'tataelm':

Project Structure > Project Settings > Modules > Language level: > then change to your preferred language level


2 Edit IntelliJ config file directly

Open the <ProjectName>.iml file (it is created automatically in your project folder if you're using IntelliJ) directly by editing the following line,

From: <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5">

To: <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_11">

As your approach is also meaning to edit this file. :)


Approach 1 is actually asking IntelliJ to help edit the .iml file instead of doing by you directly.

Eclipse error: 'Failed to create the Java Virtual Machine'

  1. Open the ecplise.ini file which is located in the eclipse installation folder.

  2. Find & Replace the line -vmargs with -vm D:\jdk1.6.0_23\bin\javaw.exe OR just remove the line -vmargs and save it . Now the problem is getting solved

Global keyboard capture in C# application

private void buttonHook_Click(object sender, EventArgs e)
{
    // Hooks only into specified Keys (here "A" and "B").
    // (***) Use this constructor

    _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

    // Hooks into all keys.
    // (***) Or this - not both

    _globalKeyboardHook = new GlobalKeyboardHook();
    _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}

And then is working fine.

How to bind list to dataGridView?

Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:

List<string> filenamesList = ...;
foreach(string filename in filenamesList)
      gvFilesOnServer.Rows.Add(new object[]{filename});

In any case, thanks user927524 for clearing this weird behavior!!

VBScript How can I Format Date?

0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm


d=CDate("2010-02-16 13:45")
document.write(FormatDateTime(d) & "<br />")
document.write(FormatDateTime(d,1) & "<br />")
document.write(FormatDateTime(d,2) & "<br />")
document.write(FormatDateTime(d,3) & "<br />")
document.write(FormatDateTime(d,4) & "<br />")

If you want to use another format you will have to create your own function and parse Month, Year, Day, etc and put them together in your preferred format.

Function myDateFormat(myDate)
    d = TwoDigits(Day(myDate))
    m = TwoDigits(Month(myDate))    
    y = Year(myDate)
    myDateFormat= m & "-" & d & "-" & y
End Function

Function TwoDigits(num)
    If(Len(num)=1) Then
        TwoDigits="0"&num
    Else
        TwoDigits=num
    End If
End Function

edit: added function to format day and month as 0n if value is less than 10.

Neatest way to remove linebreaks in Perl

After digging a bit through the perlre docs a bit, I'll present my best suggestion so far that seems to work pretty good. Perl 5.10 added the \R character class as a generalized linebreak:

$line =~ s/\R//g;

It's the same as:

(?>\x0D\x0A?|[\x0A-\x0C\x85\x{2028}\x{2029}])

I'll keep this question open a while yet, just to see if there's more nifty ways waiting to be suggested.

Datatables - Search Box outside datatable

If you are using JQuery dataTable so you need to just add "bFilter":true. This will display default search box outside table and its works dynamically..as per expected

$("#archivedAssignments").dataTable({
                "sPaginationType": "full_numbers",
                "bFilter":true,
                "sPageFirst": false,
                "sPageLast": false,
                "oLanguage": {
                "oPaginate": {
                    "sPrevious": "<< previous",
                    "sNext" : "Next >>",
                    "sFirst": "<<",
                    "sLast": ">>"
                    }
                },
            "bJQueryUI": false,
            "bLengthChange": false,
            "bInfo":false,
            "bSortable":true
        });    

Run function in script from command line (Node JS)

Try make-runnable.

In db.js, add require('make-runnable'); to the end.

Now you can do:

node db.js init

Any further args would get passed to the init method.

Automatic creation date for Django model form objects?

You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

Convert Swift string to array

There is also this useful function on String: components(separatedBy: String)

let string = "1;2;3"
let array = string.components(separatedBy: ";")
print(array) // returns ["1", "2", "3"]

Works well to deal with strings separated by a character like ";" or even "\n"

How do you Programmatically Download a Webpage in Java

Jetty has an HTTP client which can be use to download a web page.

package com.zetcode;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;

public class ReadWebPageEx5 {

    public static void main(String[] args) throws Exception {

        HttpClient client = null;

        try {

            client = new HttpClient();
            client.start();

            String url = "http://www.something.com";

            ContentResponse res = client.GET(url);

            System.out.println(res.getContentAsString());

        } finally {

            if (client != null) {

                client.stop();
            }
        }
    }
}

The example prints the contents of a simple web page.

In a Reading a web page in Java tutorial I have written six examples of dowloading a web page programmaticaly in Java using URL, JSoup, HtmlCleaner, Apache HttpClient, Jetty HttpClient, and HtmlUnit.

in_array() and multidimensional array

$userdb = Array
(
    (0) => Array
        (
            ('uid') => '100',
            ('name') => 'Sandra Shush',
            ('url') => 'urlof100'
        ),

    (1) => Array
        (
            ('uid') => '5465',
            ('name') => 'Stefanie Mcmohn',
            ('url') => 'urlof5465'
        ),

    (2) => Array
        (
            ('uid') => '40489',
            ('name') => 'Michael',
            ('url') => 'urlof40489'
        )
);

$url_in_array = in_array('urlof5465', array_column($userdb, 'url'));

if($url_in_array) {
    echo 'value is in multidim array';
}
else {
    echo 'value is not in multidim array';
}

Linq to Entities - SQL "IN" clause

Real example:

var trackList = Model.TrackingHistory.GroupBy(x => x.ShipmentStatusId).Select(x => x.Last()).Reverse();
List<int> done_step1 = new List<int>() {2,3,4,5,6,7,8,9,10,11,14,18,21,22,23,24,25,26 };
bool isExists = trackList.Where(x => done_step1.Contains(x.ShipmentStatusId.Value)).FirstOrDefault() != null;

What is the right way to debug in iPython notebook?

A native debugger is being made available as an extension to JupyterLab. Released a few weeks ago, this can be installed by getting the relevant extension, as well as xeus-python kernel (which notably comes without the magics well-known to ipykernel users):

jupyter labextension install @jupyterlab/debugger
conda install xeus-python -c conda-forge

This enables a visual debugging experience well-known from other IDEs.

enter image description here

Source: A visual debugger for Jupyter

ASP.NET Core - Swashbuckle not creating swagger.json file

Personally I had the same issue and when I tried again today after a while I found in the new version (2.5.0) that going in the json I could see an explanation of the error that was in here.

Also another thing that helped to fix it to me was removing the hosting information connected to the website that is hold inside "..vs\config\applicationhost.config" at the root of the solution folder

I removed the element that was configuring the website.

           <site name="**" id="9">
              <application path="/" applicationPool=""></application>
              <bindings></bindings>
           </site>

Detecting endianness programmatically in a C++ program

You can do it by setting an int and masking off bits, but probably the easiest way is just to use the built in network byte conversion ops (since network byte order is always big endian).

if ( htonl(47) == 47 ) {
  // Big endian
} else {
  // Little endian.
}

Bit fiddling could be faster, but this way is simple, straightforward and pretty impossible to mess up.

Running multiple commands with xargs

My current BKM for this is

... | xargs -n1 -I % perl -e 'system("echo 1 %"); system("echo 2 %");'

It is unfortunate that this uses perl, which is less likely to be installed than bash; but it handles more input that the accepted answer. (I welcome a ubiquitous version that does not rely on perl.)

@KeithThompson's suggestion of

 ... | xargs -I % sh -c 'command1; command2; ...'

is great - unless you have the shell comment character # in your input, in which case part of the first command and all of the second command will be truncated.

Hashes # can be quite common, if the input is derived from a filesystem listing, such as ls or find, and your editor creates temporary files with # in their name.

Example of the problem:

$ bash 1366 $>  /bin/ls | cat
#Makefile#
#README#
Makefile
README

Oops, here is the problem:

$ bash 1367 $>  ls | xargs -n1 -I % sh -i -c 'echo 1 %; echo 2 %'
1
1
1
1 Makefile
2 Makefile
1 README
2 README

Ahh, that's better:

$ bash 1368 $>  ls | xargs -n1 -I % perl -e 'system("echo 1 %"); system("echo 2 %");'
1 #Makefile#
2 #Makefile#
1 #README#
2 #README#
1 Makefile
2 Makefile
1 README
2 README
$ bash 1369 $>  

Calculating the position of points in a circle

PHP Solution:

class point{
    private $x = 0;
    private $y = 0;
    public function setX($xpos){
        $this->x = $xpos;
    }
    public function setY($ypos){
        $this->y = $ypos;
    }
    public function getX(){
        return $this->x;
    }
    public function getY(){
        return $this->y;
    }
    public function printX(){
        echo $this->x;
    }
    public function printY(){
        echo $this->y;
    }
}
function drawCirclePoints($points, $radius, &$center){
    $pointarray = array();
    $slice = (2*pi())/$points;
    for($i=0;$i<$points;$i++){
        $angle = $slice*$i;
        $newx = (int)($center->getX() + ($radius * cos($angle)));
        $newy = (int)($center->getY() + ($radius * sin($angle)));
        $point = new point();
        $point->setX($newx);
        $point->setY($newy);
        array_push($pointarray,$point);
    }
    return $pointarray;
}

Merge or combine by rownames

cbind.fill <- function(x, y){
  xrn <- rownames(x)
  yrn <- rownames(y)
  rn <- union(xrn, yrn)
  xcn <- colnames(x)
  ycn <- colnames(y)
  if(is.null(xrn) | is.null(yrn) | is.null(xcn) | is.null(ycn)) 
    stop("NULL rownames or colnames")
  z <- matrix(NA, nrow=length(rn), ncol=length(xcn)+length(ycn))
  rownames(z) <- rn
  colnames(z) <- c(xcn, ycn)
  idx <- match(rn, xrn)
  z[!is.na(idx), 1:length(xcn)] <- x[na.omit(idx),]
  idy <- match(rn, yrn)
  z[!is.na(idy), length(xcn)+(1:length(ycn))] <- y[na.omit(idy),]
  return(z)
}

How to write to an existing excel file without overwriting data (using pandas)?

def append_sheet_to_master(self, master_file_path, current_file_path, sheet_name):
    try:
        master_book = load_workbook(master_file_path)
        master_writer = pandas.ExcelWriter(master_file_path, engine='openpyxl')
        master_writer.book = master_book
        master_writer.sheets = dict((ws.title, ws) for ws in master_book.worksheets)
        current_frames = pandas.ExcelFile(current_file_path).parse(pandas.ExcelFile(current_file_path).sheet_names[0],
                                                               header=None,
                                                               index_col=None)
        current_frames.to_excel(master_writer, sheet_name, index=None, header=False)

        master_writer.save()
    except Exception as e:
        raise e

This works perfectly fine only thing is that formatting of the master file(file to which we add new sheet) is lost.

ArrayList filter

In , they introduced the method removeIf which takes a Predicate as parameter.

So it will be easy as:

List<String> list = new ArrayList<>(Arrays.asList("How are you",
                                                  "How you doing",
                                                  "Joe",
                                                  "Mike"));
list.removeIf(s -> !s.contains("How"));

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

try this too

pd.set_option("max_columns", None) # show all cols
pd.set_option('max_colwidth', None) # show full width of showing cols
pd.set_option("expand_frame_repr", False) # print cols side by side as it's supposed to be

How to send a message to a particular client with socket.io

Here is the full solution for Android Client + Socket IO Server (Lot of code but works). There seems to be lack of support for Android and IOS when it comes to socket io which is a tragedy of sorts.

Basically creating a room name by joining user unique id from mysql or mongo then sorting it (done in Android Client and sent to server). So each pair has a unique but common amongst the pair room name. Then just go about chatting in that room.

For quick refernce how room is created in Android

 // Build The Chat Room
        if (Integer.parseInt(mySqlUserId) < Integer.parseInt(toMySqlUserId)) {
            room = "ic" + mySqlUserId + toMySqlUserId;
        } else {
            room = "ic" + toMySqlUserId + mySqlUserId;
        }

The Full Works

Package Json

"dependencies": {
    "express": "^4.17.1",
    "socket.io": "^2.3.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.6"
  }

Socket IO Server

app = require('express')()
http = require('http').createServer(app)
io = require('socket.io')(http)

app.get('/', (req, res) => {

    res.send('Chat server is running on port 5000')
})

io.on('connection', (socket) => {

    // console.log('one user connected ' + socket.id);

    // Join Chat Room
    socket.on('join', function(data) {

        console.log('======Joined Room========== ');
        console.log(data);

        // Json Parse String To Access Child Elements
        var messageJson = JSON.parse(data);
        const room = messageJson.room;
        console.log(room);

        socket.join(room);

    });

    // On Receiving Individual Chat Message (ic_message)
    socket.on('ic_message', function(data) {
        console.log('======IC Message========== ');
        console.log(data);

        // Json Parse String To Access Child Elements
        var messageJson = JSON.parse(data);
        const room = messageJson.room;
        const message = messageJson.message;

        console.log(room);
        console.log(message);

        // Sending to all clients in room except sender
        socket.broadcast.to(room).emit('new_msg', {
            msg: message
        });

    });

    socket.on('disconnect', function() {
        console.log('one user disconnected ' + socket.id);
    });

});

http.listen(5000, () => {

    console.log('Node app is running on port 5000')
})

Android Socket IO Class

public class SocketIOClient {

    public Socket mSocket;

    {
        try {
            mSocket = IO.socket("http://192.168.1.5:5000");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public Socket getSocket() {
        return mSocket;
    }
}

Android Activity

public class IndividualChatSocketIOActivity extends AppCompatActivity {

    // Activity Number For Bottom Navigation Menu
    private final Context mContext = IndividualChatSocketIOActivity.this;

    // Strings
    private String mySqlUserId;
    private String toMySqlUserId;

    // Widgets
    private EditText etTextMessage;
    private ImageView ivSendMessage;

    // Socket IO
    SocketIOClient socketIOClient = new SocketIOClient();
    private String room;

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

        // Widgets
        etTextMessage = findViewById(R.id.a_chat_et_text_message);
        ivSendMessage = findViewById(R.id.a_chat_iv_send_message);

        // Get The MySql UserId from Shared Preference
        mySqlUserId = StartupMethods.getFromSharedPreferences("shared",
                                                              "id",
                                                              mContext);

        // Variables From Individual List Adapter
        Intent intent = getIntent();

        if (intent.hasExtra("to_id")) {

            toMySqlUserId = Objects.requireNonNull(Objects.requireNonNull(getIntent().getExtras())
                                                          .get("to_id"))
                                   .toString();
        }

        // Build The Chat Room
        if (Integer.parseInt(mySqlUserId) < Integer.parseInt(toMySqlUserId)) {
            room = "ic" + mySqlUserId + toMySqlUserId;
        } else {
            room = "ic" + toMySqlUserId + mySqlUserId;
        }

        connectToSocketIO();

        joinChat();

        leaveChat();

        getChatMessages();

        sendChatMessages();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    private void connectToSocketIO() {

        socketIOClient.mSocket = socketIOClient.getSocket();
        socketIOClient.mSocket.on(Socket.EVENT_CONNECT_ERROR,
                                  onConnectError);
        socketIOClient.mSocket.on(Socket.EVENT_CONNECT_TIMEOUT,
                                  onConnectError);
        socketIOClient.mSocket.on(Socket.EVENT_CONNECT,
                                  onConnect);
        socketIOClient.mSocket.on(Socket.EVENT_DISCONNECT,
                                  onDisconnect);
        socketIOClient.mSocket.connect();
    }

    private void joinChat() {

        // Prepare To Send Data Through WebSockets
        JSONObject jsonObject = new JSONObject();

        // Header Fields
        try {

            jsonObject.put("room",
                           room);

            socketIOClient.mSocket.emit("join",
                                        String.valueOf(jsonObject));

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void leaveChat() {
    }

    private void getChatMessages() {

        socketIOClient.mSocket.on("new_msg",
                                  new Emitter.Listener() {
                                      @Override
                                      public void call(Object... args) {
                                          try {
                                              JSONObject messageJson = new JSONObject(args[0].toString());
                                              String message = String.valueOf(messageJson);

                                              runOnUiThread(new Runnable() {
                                                  @Override
                                                  public void run() {
                                                      Toast.makeText(IndividualChatSocketIOActivity.this,
                                                                     message,
                                                                     Toast.LENGTH_SHORT)
                                                           .show();
                                                  }
                                              });
                                          } catch (JSONException e) {
                                              e.printStackTrace();
                                          }
                                      }
                                  });
    }

    private void sendChatMessages() {

        ivSendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String message = etTextMessage.getText()
                                              .toString()
                                              .trim();

                // Prepare To Send Data Thru WebSockets
                JSONObject jsonObject = new JSONObject();

                // Header Fields
                try {
                    jsonObject.put("room",
                                   room);

                    jsonObject.put("message",
                                   message);

                    socketIOClient.mSocket.emit("ic_message",
                                                String.valueOf(jsonObject));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(IndividualChatSocketIOActivity.this,
                                   "Connected To Socket Server",
                                   Toast.LENGTH_SHORT)
                         .show();

                }
            });

            Log.d("TAG",
                  "Socket Connected!");
        }
    };

    private Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                }
            });
        }
    };
    private Emitter.Listener onDisconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                }
            });
        }
    };

}

Android Gradle

// SocketIO
implementation ('io.socket:socket.io-client:1.0.0') {
    // excluding org.json which is provided by Android
    exclude group: 'org.json', module: 'json'
}

When to use static classes in C#

I do tend to use static classes for factories. For example, this is the logging class in one of my projects:

public static class Log
{
   private static readonly ILoggerFactory _loggerFactory =
      IoC.Resolve<ILoggerFactory>();

   public static ILogger For<T>(T instance)
   {
      return For(typeof(T));
   }

   public static ILogger For(Type type)
   {
      return _loggerFactory.GetLoggerFor(type);
   }
}

You might have even noticed that IoC is called with a static accessor. Most of the time for me, if you can call static methods on a class, that's all you can do so I mark the class as static for extra clarity.

intellij incorrectly saying no beans of type found for autowired repository

I had similar issue in Spring Boot application. The application utilizes Feign (HTTP client synthetizing requests from annotated interfaces). Having interface SomeClient annotated with @FeignClient, Feign generates runtime proxy class implementing this interface. When some Spring component tries to autowire bean of type SomeClient, Idea complains no bean of type SomeClient found since no real class actually exists in project and Idea is not taught to understand @FeignClient annotation in any way.

Solution: annotate interface SomeClient with @Component. (In our case, we don't use @FeignClient annotation on SomeClient directly, we rather use metaannotation @OurProjectFeignClient which is annotated @FeignClient and adding @Component annotation to it works as well.)

Angular2: How to load data before rendering the component?

update

original

When console.log(this.ev) is executed after this.fetchEvent();, this doesn't mean the fetchEvent() call is done, this only means that it is scheduled. When console.log(this.ev) is executed, the call to the server is not even made and of course has not yet returned a value.

Change fetchEvent() to return a Promise

     fetchEvent(){
        return  this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
     }

change ngOnInit() to wait for the Promise to complete

    ngOnInit() {
        this.fetchEvent().then(() =>
        console.log(this.ev)); // Now has value;
    }

This actually won't buy you much for your use case.

My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>

and in ngOnInit()

    isDataAvailable:boolean = false;

    ngOnInit() {
        this.fetchEvent().then(() =>
        this.isDataAvailable = true); // Now has value;
    }

Retrieve the commit log for a specific line in a file?

I don't believe there's anything built-in for this. It's made tricky by the fact that it's rare for a single line to change several times without the rest of the file changing substantially too, so you'll tend to end up with the line numbers changing a lot.

If you're lucky enough that the line always has some identifying characteristic, e.g. an assignment to a variable whose name never changed, you could use the regex choice for git blame -L. For example:

git blame -L '/variable_name *= */',+1

But this only finds the first match for that regex, so if you don't have a good way of matching the line, it's not too helpful.

You could hack something up, I suppose. I don't have time to write out code just now, but... something along these lines. Run git blame -n -L $n,$n $file. The first field is the previous commit touched, and the second field is the line number in that commit, since it could've changed. Grab those, and run git blame -n $n,$n $commit^ $file, i.e. the same thing starting from the commit before the last time the file was changed.

(Note that this will fail you if the last commit that changed the line was a merge commit. The primary way this could happen if the line was changed as part of a merge conflict resolution.)

Edit: I happened across this mailing list post from March 2011 today, which mentions that tig and git gui have a feature that will help you do this. It looks like the feature has been considered, but not finished, for git itself.

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

I had the same issue ... solution at the end !

here the eclipse log:

java.lang.NullPointerException
    at com.google.appengine.eclipse.wtp.maven.GaeRuntimeManager.getGaeRuntime(GaeRuntimeManager.java:85)
    at com.google.appengine.eclipse.wtp.maven.GaeRuntimeManager.ensureGaeRuntimeWithSdk(GaeRuntimeManager.java:55)
    at com.google.appengine.eclipse.wtp.maven.GaeFacetManager.addGaeFacet(GaeFacetManager.java:59)
    at com.google.appengine.eclipse.wtp.maven.GaeProjectConfigurator.configure(GaeProjectConfigurator.java:46)

... it comes from "appengine maven wtp plugin" that try to get the type of GAE runtime, but seems to be null here (... getRuntimeType() --> NPE):

see class com.google.appengine.eclipse.wtp.maven/GaeRuntimeManager.java

  private static IRuntime getGaeRuntime(String sdkVersion) {
    IRuntime[] runtimes = ServerCore.getRuntimes();
    for (IRuntime runtime : runtimes) {
      if (runtime != null &&  **runtime.getRuntimeType()**.equals(GAE_RUNTIME_TYPE)) {

So, if you check in eclipse, Google App Engine is visible , but when you select it you'll see that no SDK is associated ... preference/Server/Runtime environments

SOLUTION: in red on the screenshot ;-)

How to generate entire DDL of an Oracle schema (scriptable)?

You can spool the schema out to a file via SQL*Plus and dbms_metadata package. Then replace the schema name with another one via sed. This works for Oracle 10 and higher.

sqlplus<<EOF
set long 100000
set head off
set echo off
set pagesize 0
set verify off
set feedback off
spool schema.out

select dbms_metadata.get_ddl(object_type, object_name, owner)
from
(
    --Convert DBA_OBJECTS.OBJECT_TYPE to DBMS_METADATA object type:
    select
        owner,
        --Java object names may need to be converted with DBMS_JAVA.LONGNAME.
        --That code is not included since many database don't have Java installed.
        object_name,
        decode(object_type,
            'DATABASE LINK',      'DB_LINK',
            'JOB',                'PROCOBJ',
            'RULE SET',           'PROCOBJ',
            'RULE',               'PROCOBJ',
            'EVALUATION CONTEXT', 'PROCOBJ',
            'CREDENTIAL',         'PROCOBJ',
            'CHAIN',              'PROCOBJ',
            'PROGRAM',            'PROCOBJ',
            'PACKAGE',            'PACKAGE_SPEC',
            'PACKAGE BODY',       'PACKAGE_BODY',
            'TYPE',               'TYPE_SPEC',
            'TYPE BODY',          'TYPE_BODY',
            'MATERIALIZED VIEW',  'MATERIALIZED_VIEW',
            'QUEUE',              'AQ_QUEUE',
            'JAVA CLASS',         'JAVA_CLASS',
            'JAVA TYPE',          'JAVA_TYPE',
            'JAVA SOURCE',        'JAVA_SOURCE',
            'JAVA RESOURCE',      'JAVA_RESOURCE',
            'XML SCHEMA',         'XMLSCHEMA',
            object_type
        ) object_type
    from dba_objects 
    where owner in ('OWNER1')
        --These objects are included with other object types.
        and object_type not in ('INDEX PARTITION','INDEX SUBPARTITION',
           'LOB','LOB PARTITION','TABLE PARTITION','TABLE SUBPARTITION')
        --Ignore system-generated types that support collection processing.
        and not (object_type = 'TYPE' and object_name like 'SYS_PLSQL_%')
        --Exclude nested tables, their DDL is part of their parent table.
        and (owner, object_name) not in (select owner, table_name from dba_nested_tables)
        --Exclude overflow segments, their DDL is part of their parent table.
        and (owner, object_name) not in (select owner, table_name from dba_tables where iot_type = 'IOT_OVERFLOW')
)
order by owner, object_type, object_name;

spool off
quit
EOF

cat schema.out|sed 's/OWNER1/MYOWNER/g'>schema.out.change.sql

Put everything in a script and run it via cron (scheduler). Exporting objects can be tricky when advanced features are used. Don't be surprised if you need to add some more exceptions to the above code.

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

NuGet Package Restore Not Working

If anything else didn't work, try:

  1. Close Project.
  2. Delete packages folder in your solution folder.
  3. Open Project again and restore Nugget Packages again.

Worked for me and it's easy to try.

Dynamically create an array of strings with malloc

You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:

char **orderedIds;

orderedIds = malloc(variableNumberOfElements * sizeof(char*));
for (int i = 0; i < variableNumberOfElements; i++)
    orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear...

Seems like a good way to me. Although you perform many mallocs, you clearly assign memory for a specific string, and you can free one block of memory without freeing the whole "string array"

Is it possible to have empty RequestParam values use the defaultValue?

This was considered a bug in 2013: https://jira.spring.io/browse/SPR-10180

and was fixed with version 3.2.2. Problem shouldn't occur in any versions after that and your code should work just fine.

How to get date, month, year in jQuery UI datepicker?

$("#date").datepicker('getDate').getMonth() + 1; 

The month on the datepicker is 0 based (0-11), so add 1 to get the month as it appears in the date.

Bootstrap 4: Multilevel Dropdown Inside Navigation

This one works on Bootstrap 4.3.1.

Jsfiddle: https://jsfiddle.net/ko6L31w4/1/

The HTML code might be a little bit messy because I create a slightly complex dropdown menu for comprehensive test, otherwise everything is pretty straight forward.

Js includes fewer ways to collapse opened dropdowns and CSS only includes minimal styles for full functionalities.

_x000D_
_x000D_
$(function() {_x000D_
  $("ul.dropdown-menu [data-toggle='dropdown']").on("click", function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    _x000D_
    //method 1: remove show from sibilings and their children under your first parent_x000D_
    _x000D_
/*   if (!$(this).next().hasClass('show')) {_x000D_
        _x000D_
          $(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
       }  */     _x000D_
     _x000D_
     _x000D_
    //method 2: remove show from all siblings of all your parents_x000D_
    $(this).parents('.dropdown-submenu').siblings().find('.show').removeClass("show");_x000D_
    _x000D_
    $(this).siblings().toggleClass("show");_x000D_
    _x000D_
    _x000D_
    //collapse all after nav is closed_x000D_
    $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
      $('.dropdown-submenu .show').removeClass("show");_x000D_
    });_x000D_
_x000D_
  });_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu>.dropdown-menu {_x000D_
  top: 0;_x000D_
  left: 100%;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
_x000D_
<nav class="navbar navbar-expand-md navbar-light bg-white py-3 shadow-sm">_x000D_
  <div class="container-fluid">_x000D_
    <a href="#" class="navbar-brand font-weight-bold">Multilevel Dropdown</a>_x000D_
    _x000D_
  <button type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbars" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
_x000D_
_x000D_
  <div id="navbarContent" class="collapse navbar-collapse">_x000D_
      <ul class="navbar-nav mr-auto">_x000D_
      _x000D_
        <!-- nav dropdown -->_x000D_
        <li class="nav-item dropdown">_x000D_
        _x000D_
          <a href="#" data-toggle="dropdown" class="nav-link dropdown-toggle">Dropdown</a>_x000D_
          <ul class="dropdown-menu">_x000D_
            _x000D_
            <li><a href="#" class="dropdown-item">Some action</a></li>_x000D_
            _x000D_
            <!-- lvl 1 dropdown -->_x000D_
            <li class="dropdown-submenu">_x000D_
              <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
                _x000D_
                <!-- lvl 2 dropdown -->_x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    _x000D_
                    <!-- lvl 3 dropdown --> _x000D_
                    <li class="dropdown-submenu">_x000D_
                      <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 3</a>_x000D_
                      <ul class="dropdown-menu">_x000D_
                        <li><a href="#" class="dropdown-item">level 4</a></li>_x000D_
                      </ul>_x000D_
                    </li>_x000D_
                    _x000D_
                  </ul>_x000D_
                </li>_x000D_
_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
            _x000D_
            <li><a href="#" class="dropdown-item">Some other action</a></li>_x000D_
            _x000D_
            <li class="dropdown-submenu">_x000D_
              <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
              <ul class="dropdown-menu">_x000D_
                _x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
                _x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
                _x000D_
                                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
                _x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
              </ul>_x000D_
            </li>  _x000D_
          </ul>_x000D_
        </li>_x000D_
_x000D_
        <li class="nav-item"><a href="#" class="nav-link">About</a></li>_x000D_
        <li class="nav-item"><a href="#" class="nav-link">Services</a></li>_x000D_
        <li class="nav-item"><a href="#" class="nav-link">Contact</a></li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Auto-Submit Form using JavaScript

Try using document.getElementById("myForm") instead of document.myForm.

<script>
var auto_refresh = setInterval(function() { submitform(); }, 10000);

function submitform()
{
  alert('test');
  document.getElementById("myForm").submit();
}
</script>

Java: Check the date format of current string is according to required format or not

Regex can be used for this with some detailed info for validation, for example this code can be used to validate any date in (DD/MM/yyyy) format with proper date and month value and year between (1950-2050)

    public Boolean checkDateformat(String dateToCheck){   
        String rex="([0]{1}[1-9]{1}|[1-2]{1}[0-9]{1}|[3]{1}[0-1]{1})+
        \/([0]{1}[1-9]{1}|[1]{1}[0-2]{2})+
        \/([1]{1}[9]{1}[5-9]{1}[0-9]{1}|[2]{1}[0]{1}([0-4]{1}+
        [0-9]{1}|[5]{1}[0]{1}))";

        return(dateToCheck.matches(rex));
    }

Compute a confidence interval from sample data

import numpy as np
import scipy.stats


def mean_confidence_interval(data, confidence=0.95):
    a = 1.0 * np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
    return m, m-h, m+h

you can calculate like this way.

Illegal character in path at index 16

the install directory can't have space. reinstall the software will correct it

How do I write a Windows batch script to copy the newest file from a directory?

Windows shell, one liner:

FOR /F %%I IN ('DIR *.* /B /O:-D') DO COPY %%I <<NewDir>> & EXIT

What are some uses of template template parameters?

I use it for versioned types.

If you have a type versioned through a template such as MyType<version>, you can write a function in which you can capture the version number:

template<template<uint8_t> T, uint8_t Version>
Foo(const T<Version>& obj)
{
    assert(Version > 2 && "Versions older than 2 are no longer handled");
    ...
    switch (Version)
    {
    ...
    }
}

So you can do different things depending on the version of the type being passed in instead of having an overload for each type. You can also have conversion functions which take in MyType<Version> and return MyType<Version+1>, in a generic way, and even recurse them to have a ToNewest() function which returns the latest version of a type from any older version (very useful for logs that might have been stored a while back but need to be processed with today's newest tool).

Escape quotes in JavaScript

The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.

<a href="#" onclick='DoEdit("Preliminary Assessment \"Mini\""); return false;'>edit</a>

What's the common practice for enums in Python?

I've seen this pattern several times:

>>> class Enumeration(object):
        def __init__(self, names):  # or *names, with no .split()
            for number, name in enumerate(names.split()):
                setattr(self, name, number)

>>> foo = Enumeration("bar baz quux")
>>> foo.quux
2

You can also just use class members, though you'll have to supply your own numbering:

>>> class Foo(object):
        bar  = 0
        baz  = 1
        quux = 2

>>> Foo.quux
2

If you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe.

Difference between arguments and parameters in Java

The term parameter refers to any declaration within the parentheses following the method/function name in a method/function declaration or definition; the term argument refers to any expression within the parentheses of a method/function call. i.e.

  1. parameter used in function/method definition.
  2. arguments used in function/method call.

Please have a look at the below example for better understanding:

package com.stackoverflow.works;

public class ArithmeticOperations {

    public static int add(int x, int y) { //x, y are parameters here
        return x + y;
    }

    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        int sum = add(x, y); //x, y are arguments here
        System.out.println("SUM IS: " +sum);
    }

}

Thank you!

Space between two divs

Why not use margin? you can apply all kinds off margins to an element. Not just the whole margin around it.

You should use css classes since this is referencing more than one element and you can use id's for those that you want to be different specifically

i.e:

<style>
.box { height: 50px; background: #0F0; width: 100%; margin-top: 10px; }
#first { margin-top: 20px; }
#second { background: #00F; }
h1.box { background: #F00; margin-bottom: 50px;  }
</style>

<h1 class="box">Hello World</h1>
<div class="box" id="first"></div>
<div class="box" id="second"></div>?

Here is a jsfiddle example:

REFERENCE:

How can I extract substrings from a string in Perl?

You could do something like this:

my $data = <<END;
1) Scheme ID: abc-456-hu5t10 (High priority) *
2) Scheme ID: frt-78f-hj542w (Balanced)
3) Scheme ID: 23f-f974-nm54w (super formula run) *
END

foreach (split(/\n/,$data)) {
  $_ =~ /Scheme ID: ([a-z0-9-]+)\s+\(([^)]+)\)\s*(\*)?/ || next;
  my ($id,$word,$star) = ($1,$2,$3);
  print "$id $word $star\n";
}

The key thing is the Regular expression:

Scheme ID: ([a-z0-9-]+)\s+\(([^)]+)\)\s*(\*)?

Which breaks up as follows.

The fixed String "Scheme ID: ":

Scheme ID: 

Followed by one or more of the characters a-z, 0-9 or -. We use the brackets to capture it as $1:

([a-z0-9-]+)

Followed by one or more whitespace characters:

\s+

Followed by an opening bracket (which we escape) followed by any number of characters which aren't a close bracket, and then a closing bracket (escaped). We use unescaped brackets to capture the words as $2:

\(([^)]+)\)

Followed by some spaces any maybe a *, captured as $3:

\s*(\*)?

How to sync with a remote Git repository?

You have to add the original repo as an upstream.

It is all well described here: https://help.github.com/articles/fork-a-repo

git remote add upstream https://github.com/octocat/Spoon-Knife.git
git fetch upstream
git merge upstream/master
git push origin master

Colors in JavaScript console

Older versions of Chrome do not allow you to get console.log()s to show in a specific color programmatically, but calling console.error() will put a red X icon on error lines and make the text red, and console.warn() gets you a yellow ! icon.

You can then filter console entries with the All, Errors, Warnings, and Logs buttons beneath the console.


It turns out Firebug has supported custom CSS for console.logs since 2010 and Chrome support has been added as of Chrome 24.

console.log('%c Oh my heavens! ', 'background: #222; color: #bada55',
            'more text');

When %c appears anywhere in the first argument, the next argument is used as the CSS to style the console line. Further arguments are concatenated (as has always been the case).

Best Practice to Use HttpClient in Multithreaded Environment

Definitely Method A because its pooled and thread safe.

If you are using httpclient 4.x, the connection manager is called ThreadSafeClientConnManager. See this link for further details (scroll down to "Pooling connection manager"). For example:

    HttpParams params = new BasicHttpParams();
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, registry);
    HttpClient client = new DefaultHttpClient(cm, params);

Java Timer vs ExecutorService?

If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:

ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();

will give you a ScheduledExecutorService with similar functionality to Timer (i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer class). Using a ScheduledExecutorService also gives you advantages such as:

  • You can customize it if need be (see the newScheduledThreadPoolExecutor() or the ScheduledThreadPoolExecutor class)
  • The 'one off' executions can return results

About the only reasons for sticking to Timer I can think of are:

  • It is available pre Java 5
  • A similar class is provided in J2ME, which could make porting your application easier (but it wouldn't be terribly difficult to add a common layer of abstraction in this case)

How can I check if an argument is defined when starting/calling a batch file?

IF "%1"=="" GOTO :Continue
.....
.....
:Continue
IF "%1"=="" echo No Parameter given

Add item to Listview control

I have done it like this and it seems to work:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
        var listViewItem = new ListViewItem(row); 
        listView1.Items.Add(listViewItem);
    }
}

Getting the Facebook like/share count for a given URL

Use the open graph API. Here is a live example querying how many likes "Coca Cola" has.

https://developers.facebook.com/tools/explorer/?method=GET&path=cocacola%3Ffields%3Dlikes

Which boils down to:

https://graph.facebook.com/cocacola?fields=likes

Which you could do in an AJAX GET

The result is:

{
  "likes": 71717854, 
  "id": "40796308305"
}

How to get All input of POST in Laravel

For those who came here looking for "how to get All input of POST" only

class Illuminate\Http\Request extends from Symfony\Component\HttpFoundation\Request which has two class variables that store request parameters.

public $query - for GET parameters

public $request - for POST parameters

Usage: To get a post data only

$request = Request::instance();
$request->request->all(); //Get all post requests
$request->request->get('my_param'); //Get a post parameter

Source here

EDIT

For Laravel >= 5.5, you can simply call $request->post() or $request->post('my_param') which internally calls $request->request->all() or $request->request->get('my_param') respectively.

How to find server name of SQL Server Management Studio

1.you can run following command.

EXEC xp_cmdshell 'reg query "HKLM\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL"';
GO

you can read instance name using Registry. Ingore null values.

2.using inbuilt standard Report.

select instance--> right click->Reports-->Standard Reports-->server Dashbords enter image description here

How do I add my bot to a channel?

This is how I've added a bot to my channel and set up notifications:

  1. Make sure the channel is public (you can set it private later)
  2. Add administrators > Type the bot username and make it administrator
  3. Your bot will join your channel
  4. set a channel id by setting the channel url like

telegram.me/whateverIWantAndAvailable

the channel id will be @whateverIWantAndAvailable

Now set up your bot to send notifications by pusshing the messages here:

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Test

the message which bot will notify is: Test

I strongly suggest an urlencode of the message like

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Testing%20if%20this%20works

in php you can use urlencode("Test if this works"); in js you can encodeURIComponent("Test if this works");

I hope it helps

Why is my asynchronous function returning Promise { <pending> } instead of a value?

The promise will always log pending as long as its results are not resolved yet. You must call .then on the promise to capture the results regardless of the promise state (resolved or still pending):

let AuthUser = function(data) {
  return google.login(data.username, data.password).then(token => { return token } )
}

let userToken = AuthUser(data)
console.log(userToken) // Promise { <pending> }

userToken.then(function(result) {
   console.log(result) // "Some User token"
})

Why is that?

Promises are forward direction only; You can only resolve them once. The resolved value of a Promise is passed to its .then or .catch methods.

Details

According to the Promises/A+ spec:

The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.

This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.

This spec is a little hard to parse, so let's break it down. The rule is:

If the function in the .then handler returns a value, then the Promise resolves with that value. If the handler returns another Promise, then the original Promise resolves with the resolved value of the chained Promise. The next .then handler will always contain the resolved value of the chained promise returned in the preceding .then.

The way it actually works is described below in more detail:

1. The return of the .then function will be the resolved value of the promise.

function initPromise() {
  return new Promise(function(res, rej) {
    res("initResolve");
  })
}

initPromise()
  .then(function(result) {
    console.log(result); // "initResolve"
    return "normalReturn";
  })
  .then(function(result) {
    console.log(result); // "normalReturn"
  });

2. If the .then function returns a Promise, then the resolved value of that chained promise is passed to the following .then.

function initPromise() {
  return new Promise(function(res, rej) {
    res("initResolve");
  })
}

initPromise()
  .then(function(result) {
    console.log(result); // "initResolve"
    return new Promise(function(resolve, reject) {
       setTimeout(function() {
          resolve("secondPromise");
       }, 1000)
    })
  })
  .then(function(result) {
    console.log(result); // "secondPromise"
  });

Error handling in C code

The UNIX approach is most similar to your second suggestion. Return either the result or a single "it went wrong" value. For instance, open will return the file descriptor on success or -1 on failure. On failure it also sets errno, an external global integer to indicate which failure occurred.

For what it's worth, Cocoa has also been adopting a similar approach. A number of methods return BOOL, and take an NSError ** parameter, so that on failure they set the error and return NO. Then the error handling looks like:

NSError *error = nil;
if ([myThing doThingError: &error] == NO)
{
  // error handling
}

which is somewhere between your two options :-).

MySQL server has gone away - in exactly 60 seconds

In our case, the culprit was the global (not "local") MySQL variable "wait_timeout".

Compare the results of the following queries:

SHOW VARIABLES LIKE '%wait%';

to

SHOW GLOBAL VARIABLES WHERE Variable_name LIKE '%wait%';

In our case the first query showed a wait_timeout of 28800, but the 2nd query showed a value of 10 (seconds).

We verified that changing the global variable fixed the problem. Here is a simple PHP script that reproduced our condition:

<?php    
$db = mysqli_connect('host', 'user', 'password', 'database');

sleep(10); // number of seconds to sleep

// MySQL server has gone away?
$obj = mysqli_query($db, 'SELECT * FROM some_table');

$results = mysqli_fetch_object($obj);

print_r($results);

As soon as the sleep time exceeded the global wait_timeout value, we would get the error: "Warning: mysqli_query(): MySQL server has gone away".

To change the value, we had to edit the setting in our Amazon RDS dashboard.

How to move an entire div element up x pixels?

In css add this to the element:

margin-top: -15px; /*for exact positioning */
margin-top: -5%; /* for relative positioning */

you can use either one to position accordingly.

How to exit a function in bash

If you want to return from an outer function with an error without exiting you can use this trick:

do-something-complex() {
  # Using `return` here would only return from `fail`, not from `do-something-complex`.
  # Using `exit` would close the entire shell.
  # So we (ab)use a different feature. :)
  fail() { : "${__fail_fast:?$1}"; }

  nested-func() {
      try-this || fail "This didn't work"
      try-that || fail "That didn't work"
  }
  nested-func
}

Trying it out:

$ do-something-complex
try-this: command not found
bash: __fail_fast: This didn't work

This has the added benefit/drawback that you can optionally turn off this feature: __fail_fast=x do-something-complex.

Note that this causes the outermost function to return 1.

Using Custom Domains With IIS Express

This method has been tested and worked with ASP.NET Core 3.1 and Visual Studio 2019.

.vs\PROJECTNAME\config\applicationhost.config

Change "*:44320:localhost" to "*:44320:*".

<bindings>
    <binding protocol="http" bindingInformation="*:5737:localhost" />
    <binding protocol="https" bindingInformation="*:44320:*" />
</bindings>

Both links work:

Now if you want the app to work with the custom domain, just add the following line to the host file:

C:\Windows\System32\drivers\etc\hosts

127.0.0.1 customdomain

Now:

  • https://customdomain:44320

NOTE: If your app works without SSL, change the protocol="http" part.

UIButton title text color

I created a custom class MyButton extended from UIButton. Then added this inside the Identity Inspector:

enter image description here

After this, change the button type to Custom:

enter image description here

Then you can set attributes like textColor and UIFont for your UIButton for the different states:

enter image description here

Then I also created two methods inside MyButton class which I have to call inside my code when I want a UIButton to be displayed as highlighted:

- (void)changeColorAsUnselection{
    [self setTitleColor:[UIColor colorFromHexString:acColorGreyDark] 
               forState:UIControlStateNormal & 
                        UIControlStateSelected & 
                        UIControlStateHighlighted];
}

- (void)changeColorAsSelection{
    [self setTitleColor:[UIColor colorFromHexString:acColorYellow] 
               forState:UIControlStateNormal & 
                        UIControlStateHighlighted & 
                        UIControlStateSelected];
}

You have to set the titleColor for normal, highlight and selected UIControlState because there can be more than one state at a time according to the documentation of UIControlState. If you don't create these methods, the UIButton will display selection or highlighting but they won't stay in the UIColor you setup inside the UIInterface Builder because they are just available for a short display of a selection, not for displaying selection itself.

How do I vertically align text in a paragraph?

Alternative solution which scales for multi-line text:

Set vertical and horizontal padding to be (height - line-height) / 2

p.event_desc {
    font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
    line-height: 14px;
    padding: 10.5px 0;
    margin: 0px;
}

Binding List<T> to DataGridView in WinForm

This isn't exactly the issue I had, but if anyone is looking to convert a BindingList of any type to List of the same type, then this is how it is done:

var list = bindingList.ToDynamicList();

Also, if you're assigning BindingLists of dynamic types to a DataGridView.DataSource, then make sure you declare it first as IBindingList so the above works.

How can I add C++11 support to Code::Blocks compiler?

A simple way is to write:

-std=c++11

in the Other Options section of the compiler flags. You could do this on a per-project basis (Project -> Build Options), and/or set it as a default option in the Settings -> Compilers part.

Some projects may require -std=gnu++11 which is like C++11 but has some GNU extensions enabled.

If using g++ 4.9, you can use -std=c++14 or -std=gnu++14.

How to solve javax.net.ssl.SSLHandshakeException Error?

I believe that you are trying to connect to a something using SSL but that something is providing a certificate which is not verified by root certification authorities such as verisign.. In essence by default secure connections can only be established if the person trying to connect knows the counterparties keys or some other verndor such as verisign can step in and say that the public key being provided is indeed right..

ALL OS's trust a handful of certification authorities and smaller certificate issuers need to be certified by one of the large certifiers making a chain of certifiers if you get what I mean...

Anyways coming back to the point.. I had a similiar problem when programming a java applet and a java server ( Hopefully some day I will write a complete blogpost about how I got all the security to work :) )

In essence what I had to do was to extract the public keys from the server and store it in a keystore inside my applet and when I connected to the server I used this key store to create a trust factory and that trust factory to create the ssl connection. There are alterante procedures as well such as adding the key to the JVM's trusted host and modifying the default trust store on start up..

I did this around two months back and dont have source code on me right now.. use google and you should be able to solve this problem. If you cant message me back and I can provide you the relevent source code for the project .. Dont know if this solves your problem since you havent provided the code which causes these exceptions. Furthermore I was working wiht applets thought I cant see why it wont work on Serverlets...

P.S I cant get source code before the weekend since external SSH is disabled in my office :(

Error: Could not find or load main class in intelliJ IDE

I ran into this problem when my Java class was under src/main/kotlin. After I moved it to src/main/java, the problem was gone.

wamp server does not start: Windows 7, 64Bit

You just need Visual C++ runtime 2015 installed, if you change your php version to the newest version you will get the error for it. this is why apache has php dependency error.

How do I install boto?

Best way to install boto in my opinion is to use:

pip install boto-1.6 

This ensures you'll have the boto glacier code.

How to redirect the output of an application in background to /dev/null

These will also redirect both:

yourcommand  &> /dev/null

yourcommand  >& /dev/null

though the bash manual says the first is preferred.

SQL Server: Error converting data type nvarchar to numeric

You might need to revise the data in the column, but anyway you can do one of the following:-

1- check if it is numeric then convert it else put another value like 0

Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA) 
ELSE 0 END AS COLUMNA

2- select only numeric values from the column

SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1

Drawing in Java using Canvas

Suggestions:

  • Don't use Canvas as you shouldn't mix AWT with Swing components unnecessarily.
  • Instead use a JPanel or JComponent.
  • Don't get your Graphics object by calling getGraphics() on a component as the Graphics object obtained will be transient.
  • Draw in the JPanel's paintComponent() method.
  • All this is well explained in several tutorials that are easily found. Why not read them first before trying to guess at this stuff?

Key tutorial links:

No shadow by default on Toolbar?

All you need is a android:margin_bottom equal to the android:elevation value. No AppBarLayout, clipToPadding, etc. required.

Example:

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:layout_marginBottom="4dp"
    android:background="@android:color/white"
    android:elevation="4dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!--Inner layout goes here-->

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>

Strip / trim all strings of a dataframe

If you really want to use regex, then

>>> df.replace('(^\s+|\s+$)', '', regex=True, inplace=True)
>>> df
   0   1
0  a  10
1  c   5

But it should be faster to do it like this:

>>> df[0] = df[0].str.strip()

Call to undefined function mysql_query() with Login

I would recommend that start using mysqli_() and stop using mysql_()

Check the following page: LINK

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include: mysqli_affected_rows() PDOStatement::rowCount()

Try and use mysqli_() Or PDO

make html text input field grow as I type?

I just wrote this for you, I hope you like it :) No guarantees that it's cross-browser, but I think it is :)

(function(){
    var min = 100, max = 300, pad_right = 5, input = document.getElementById('adjinput');

    input.style.width = min+'px';
    input.onkeypress = input.onkeydown = input.onkeyup = function(){
        var input = this;
        setTimeout(function(){
            var tmp = document.createElement('div');
            tmp.style.padding = '0';
            if(getComputedStyle)
                tmp.style.cssText = getComputedStyle(input, null).cssText;
            if(input.currentStyle)
                tmp.style.cssText = input.currentStyle.cssText;
            tmp.style.width = '';
            tmp.style.position = 'absolute';
            tmp.innerHTML = input.value.replace(/&/g, "&amp;")
                                       .replace(/</g, "&lt;")
                                       .replace(/>/g, "&gt;")
                                       .replace(/"/g, "&quot;")
                                       .replace(/'/g, "&#039;")
                                       .replace(/ /g, '&nbsp;');
            input.parentNode.appendChild(tmp);
            var width = tmp.clientWidth+pad_right+1;
            tmp.parentNode.removeChild(tmp);
            if(min <= width && width <= max)
                input.style.width = width+'px';
        }, 1);
    }
})();

JSFiddle

How can I convert a hex string to a byte array?

Here's a nice fun LINQ example.

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

C# "No suitable method found to override." -- but there is one

You cannot override a function with different parameters, only you are allowed to change the functionality of the overridden method.

//Compiler Microsoft (R) .NET Framework 4.5

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

//Overriding & overloading

namespace polymorpism
{
    public class Program
    {
        public static void Main(string[] args)
        {

            drowButn calobj = new drowButn();

            BtnOverride calobjOvrid = new BtnOverride();

            Console.WriteLine(calobj.btn(5.2, 6.6).ToString());

            //btn has compleately overrided inside this calobjOvrid object
            Console.WriteLine(calobjOvrid.btn(5.2, 6.6).ToString());
            //the overloaded function
            Console.WriteLine(calobjOvrid.btn(new double[] { 5.2, 6.6 }).ToString());

            Console.ReadKey();
        }
    }

    public class drowButn
    {

        //same add function overloading to add double type field inputs
        public virtual double btn(double num1, double num2)
        {

            return (num1 + num2);

        }


    }

    public class BtnOverride : drowButn
    {

        //same add function overrided and change its functionality 
        //(this will compleately replace the base class function
        public override double btn(double num1, double num2)
        {
            //do compleatly diffarant function then the base class
            return (num1 * num2);

        }

        //same function overloaded (no override keyword used) 
        // this will not effect the base class function

        public double btn(double[] num)
        {
            double cal = 0;

            foreach (double elmnt in num)
            {

                cal += elmnt;
            }
            return cal;

        }
    }
}

Show spinner GIF during an $http request in AngularJS?

You can use angular interceptor to manage http request calls

  <div class="loader">
    <div id="loader"></div>
  </div>

<script>
    var app = angular.module("myApp", []);

    app.factory('httpRequestInterceptor', ['$rootScope', '$location', function ($rootScope, $location) {
        return {
            request: function ($config) {
                $('.loader').show();
                return $config;
            },
            response: function ($config) {
                $('.loader').hide();
                return $config;
            },
            responseError: function (response) {
                return response;
            }
        };
    }]);

    app.config(['$stateProvider', '$urlRouterProvider', '$httpProvider',
        function ($stateProvider, $urlRouterProvider, $httpProvider) {
            $httpProvider.interceptors.push('httpRequestInterceptor');
        }]);

</script>

https://stackoverflow.com/a/49632155/4976786

Generate a unique id

We can do something like this

string TransactionID = "BTRF"+DateTime.Now.Ticks.ToString().Substring(0, 10);

vertical-align: middle doesn't work

The answer given by Matt K works perfectly fine.

However it is important to note one thing - If the div you are applying it to has absolute positioning, it wont work. For it to work, do this -

<div style="position:absolute; hei...">
   <div style="position:relative; display: table-cell; vertical-align:middle; hei..."> 
      <!-- here position MUST be relative, this div acts as a wrapper-->
      ...
   </div>
</div>

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

For Intellij Idea sometime localhost.log file generated at different location. For e.g. you can find it at homedirectory\ .IntelliJIdea14\system\tomcat.

IF you are using spring then start ur server in debug mode and put debug point in catch block of org.springframework.context.support.AbstractApplicationContext's refresh() method. If bean creation fails you would be able to see the exception.

Disable eslint rules for folder

To ignore some folder from eslint rules we could create the file .eslintignore in root directory and add there the path to the folder we want omit (the same way as for .gitignore).

Here is the example from the ESLint docs on Ignoring Files and Directories:

# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default

# Ignore built files except build/index.js
build/*
!build/index.js

Angular 5 Button Submit On Enter Key Press

Try to use keyup.enter but make sure to use it inside your input tag

<input
  matInput
  placeholder="enter key word"
  [(ngModel)]="keyword"
  (keyup.enter)="addToKeywords()"
/>

Servlet for serving static content

I did this by extending the tomcat DefaultServlet (src) and overriding the getRelativePath() method.

package com.example;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.servlets.DefaultServlet;

public class StaticServlet extends DefaultServlet
{
   protected String pathPrefix = "/static";

   public void init(ServletConfig config) throws ServletException
   {
      super.init(config);

      if (config.getInitParameter("pathPrefix") != null)
      {
         pathPrefix = config.getInitParameter("pathPrefix");
      }
   }

   protected String getRelativePath(HttpServletRequest req)
   {
      return pathPrefix + super.getRelativePath(req);
   }
}

... And here are my servlet mappings

<servlet>
    <servlet-name>StaticServlet</servlet-name>
    <servlet-class>com.example.StaticServlet</servlet-class>
    <init-param>
        <param-name>pathPrefix</param-name>
        <param-value>/static</param-value>
    </init-param>       
</servlet>

<servlet-mapping>
    <servlet-name>StaticServlet</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>  

iptables block access to port 8000 except from IP address

Another alternative is;

sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP

I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

Edit**

According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP

How to temporarily exit Vim and go back

You can also do that by :sus to fall into shell and back by fg.

What is the difference between UNION and UNION ALL?

It is good to understand with a Venn diagramm.

here is the link to the source. There is a good description.

enter image description here

How do you get the selected value of a Spinner?

To get just the string value within the spinner use the following:

spinner.getSelectedItem().toString();

How can I get a resource content from a static context?

I am using API level 27 and found a best solution after struggling for around two days. If you want to read a xml file from a class which doesn't derive from Activity or Application then do the following.

  1. Put the testdata.xml file inside the assets directory.

  2. Write the following code to get the testdata document parsed.

        InputStream inputStream = this.getClass().getResourceAsStream("/assets/testdata.xml");
    
        // create a new DocumentBuilderFactory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // use the factory to create a documentbuilder
        DocumentBuilder builder = factory.newDocumentBuilder();
        // create a new document from input stream
        Document doc = builder.parse(inputStream);
    

Define preprocessor macro through CMake?

To do this for a specific target, you can do the following:

target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)

You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.

How to find whether a ResultSet is empty or not in Java?

if (rs == null || !rs.first()) {
    //empty
} else {
    //not empty
}

Note that after this method call, if the resultset is not empty, it is at the beginning.

How to disable margin-collapsing?

overflow:hidden prevents collapsing margins but it's not free of side effects - namely it... hides overflow.

Apart form this and what you've mentioned you just have to learn live with it and learn for this day when they are actually useful (comes every 3 to 5 years).

sql primary key and index

primary keys are automatically indexed

you can create additional indices using the pk depending on your usage

  • index zip_code, id may be helpful if you often select by zip_code and id

How to send custom headers with requests in Swagger UI?

For those who use NSwag and need a custom header:

app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, settings =>
      {
          settings.GeneratorSettings.IsAspNetCore = true;
          settings.GeneratorSettings.OperationProcessors.Add(new OperationSecurityScopeProcessor("custom-auth"));

          settings.GeneratorSettings.DocumentProcessors.Add(
              new SecurityDefinitionAppender("custom-auth", new SwaggerSecurityScheme
                {
                    Type = SwaggerSecuritySchemeType.ApiKey,
                    Name = "header-name",
                    Description = "header description",
                    In = SwaggerSecurityApiKeyLocation.Header
                }));
        });            
    }

Swagger UI will then include an Authorize button.

Adding one day to a date

<?php
$stop_date = '2009-09-30 20:24:00';
echo 'date before day adding: ' . $stop_date; 
$stop_date = date('Y-m-d H:i:s', strtotime($stop_date . ' +1 day'));
echo 'date after adding 1 day: ' . $stop_date;
?>

For PHP 5.2.0+, you may also do as follows:

$stop_date = new DateTime('2009-09-30 20:24:00');
echo 'date before day adding: ' . $stop_date->format('Y-m-d H:i:s'); 
$stop_date->modify('+1 day');
echo 'date after adding 1 day: ' . $stop_date->format('Y-m-d H:i:s');

Python - abs vs fabs

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In [2]: from math import fabs

In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop

In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop

So it seems abs() only has slight speed advantage over fabs() for integers. For floats, abs() and fabs() demonstrate similar speed.


In addition to what @aix has said, one more thing to consider is the speed difference:

In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop

In [2]: import math

In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop

So abs() is faster than math.fabs().

Regex: Use start of line/end of line signs (^ or $) in different context

you just need to use word boundary (\b) instead of ^ and $:

\bgarp\b

top nav bar blocking top content of the page

EDIT: This solution is not viable for newer versions of Bootstrap, where the navbar-inverse and navbar-static-top classes are not available.

Using MVC 5, the way I fixed mine, was to simply add my own Site.css, loaded after the others, with the following line: body{padding: 0}

and I changed the code in the beginning of _Layout.cshtml, to be:

<body>
    <div class="navbar navbar-inverse navbar-static-top">
        <div class="container">
            @if (User.Identity.IsAuthenticated) {
                <div class="top-navbar">

MySQL: Cloning a MySQL database on the same MySql instance

As the manual says in Copying Databases you can pipe the dump directly into the mysql client:

mysqldump db_name | mysql new_db_name

If you're using MyISAM you could copy the files, but I wouldn't recommend it. It's a bit dodgy.

Integrated from various good other answers

Both mysqldump and mysql commands accept options for setting connection details (and much more), like:

mysqldump -u <user name> --password=<pwd> <original db> | mysql -u <user name> -p <new db>

Also, if the new database is not existing yet, you have to create it beforehand (e.g. with echo "create database new_db_name" | mysql -u <dbuser> -p).

How to echo xml file in php

Here's what worked for me:

<pre class="prettyprint linenums">
    <code class="language-xml"><?php echo htmlspecialchars(file_get_contents("example.xml"), ENT_QUOTES); ?></code>
</pre>

Using htmlspecialchars will prevent tags from being displayed as html and won't break anything. Note that I'm using Prettyprint to highlight the code ;)

Trigger an event on `click` and `enter`

$('#form').keydown(function(e){
    if (e.keyCode === 13) { // If Enter key pressed
        $(this).trigger('submit');
    }
});

CLEAR SCREEN - Oracle SQL Developer shortcut?

In the Oracle SQL-plus:

shift+del

Textarea Auto height

var minRows = 5;
var maxRows = 26;
function ResizeTextarea(id) {
    var t = document.getElementById(id);
    if (t.scrollTop == 0)   t.scrollTop=1;
    while (t.scrollTop == 0) {
        if (t.rows > minRows)
                t.rows--; else
            break;
        t.scrollTop = 1;
        if (t.rows < maxRows)
                t.style.overflowY = "hidden";
        if (t.scrollTop > 0) {
            t.rows++;
            break;
        }
    }
    while(t.scrollTop > 0) {
        if (t.rows < maxRows) {
            t.rows++;
            if (t.scrollTop == 0) t.scrollTop=1;
        } else {
            t.style.overflowY = "auto";
            break;
        }
    }
}

What are the differences among grep, awk & sed?

I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....

they are very handy but you have to learn their options etc.

A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)

AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.

a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.

Java: random long number in 0 <= x < n range

import java.util*;

    Random rnd = new Random ();
    long name = Math.abs(rnd.nextLong());

This should work

How to set column widths to a jQuery datatable?

Answer from official website

https://datatables.net/reference/option/columns.width

$('#example').dataTable({
    "columnDefs": [
        {
            "width": "20%",
            "targets": 0
        }
    ]
});

Multiple select statements in Single query

I know this is an old stack but i will post this Multi-SQL select case

    SELECT bp.bizid, bp.usrid, bp.website, 
ROUND((SELECT SUM(rating) FROM ratings WHERE bizid=bp.bizid)/(SELECT COUNT(*) FROM ratings WHERE bizid=bp.bizid), 1) AS 'ratings', 
(SELECT COUNT(*) FROM bzreviews WHERE bizid=bp.bizid) AS 'ttlreviews', 
bp.phoneno, als.bizname, 
(SELECT COUNT(*) FROM endorsment WHERE bizid=bp.bizid) AS 'endorses'
, als.imgname, bp.`location`, bp.`ownership`, 
(SELECT COUNT(*) FROM follows WHERE bizid=bp.bizid) AS 'followers', 
bp.categories, bp.openhours, bp.bizdecri FROM bizprofile AS bp 
INNER JOIN alluser AS als ON bp.usrid=als.userid 
WHERE als.usertype='Business'

Difference between variable declaration syntaxes in Javascript (including global variables)?

Keeping it simple :

a = 0

The code above gives a global scope variable

var a = 0;

This code will give a variable to be used in the current scope, and under it

window.a = 0;

This generally is same as the global variable.

How to hide/show div tags using JavaScript?

just use a jquery event listner , click event. let the class of the link is lb... i am considering body as a div as you said...

$('.lb').click(function() {
    $('#body1').show();
    $('#body').hide();
 });

How do I get a list of locked users in an Oracle database?

select username,
       account_status 
  from dba_users 
 where lock_date is not null;

This will actually give you the list of locked users.

How to capture a backspace on the onkeydown event

not sure if it works outside of firefox:

callback (event){
  if (event.keyCode === event.DOM_VK_BACK_SPACE || event.keyCode === event.DOM_VK_DELETE)
    // do something
  }
}

if not, replace event.DOM_VK_BACK_SPACE with 8 and event.DOM_VK_DELETE with 46 or define them as constant (for better readability)