Programs & Examples On #Content query rollup

How to parse JSON string in Typescript

Type-safe JSON.parse

You can continue to use JSON.parse, as TS is a JS superset. There is still a problem left: JSON.parse returns any, which undermines type safety. Here are two options for stronger types:

1. User-defined type guards (playground)

Custom type guards are the simplest solution and often sufficient for external data validation:

// For example, you expect to parse a given value with `MyType` shape
type MyType = { name: string; description: string; }

// Validate this value with a custom type guard
function isMyType(o: any): o is MyType {
  return "name" in o && "description" in o
}

A JSON.parse wrapper can then take a type guard as input and return the parsed, typed value:

const safeJsonParse = <T>(guard: (o: any) => o is T) => (text: string): ParseResult<T> => {
  const parsed = JSON.parse(text)
  return guard(parsed) ? { parsed, hasError: false } : { hasError: true }
}

type ParseResult<T> =
  | { parsed: T; hasError: false; error?: undefined }
  | { parsed?: undefined; hasError: true; error?: unknown }
Usage example:
const json = '{ "name": "Foo", "description": "Bar" }';
const result = safeJsonParse(isMyType)(json) // result: ParseResult<MyType>
if (result.hasError) {
  console.log("error :/")  // further error handling here
} else {
  console.log(result.parsed.description) // result.parsed now has type `MyType`
}

safeJsonParse might be extended to fail fast or try/catch JSON.parse errors.

2. External libraries

Writing type guard functions manually becomes cumbersome, if you need to validate many different values. There are libraries to assist with this task - examples (no comprehensive list):

More infos

Creating a JSON Array in node js

This one helped me,

res.format({
        json:function(){
                            var responseData    = {};
                            responseData['status'] = 200;
                            responseData['outputPath']  = outputDirectoryPath;
                            responseData['sourcePath']  = url;
                            responseData['message'] = 'Scraping of requested resource initiated.';
                            responseData['logfile'] = logFileName;
                            res.json(JSON.stringify(responseData));
                        }
    });

Call Python function from MATLAB

Like Daniel said you can run python commands directly from Matlab using the py. command. To run any of the libraries you just have to make sure Malab is running the python environment where you installed the libraries:

On a Mac:

  • Open a new terminal window;

  • type: which python (to find out where the default version of python is installed);

  • Restart Matlab;

  • type: pyversion('/anaconda2/bin/python'), in the command line (obviously replace with your path).
  • You can now run all the libraries in your default python installation.

For example:

py.sys.version;

py.sklearn.cluster.dbscan

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

The dts data Conversion task is time taking if there are 50 plus columns!Found a fix for this at the below link

http://rdc.codeplex.com/releases/view/48420

However, it does not seem to work for versions above 2008. So this is how i had to work around the problem

*Open the .DTSX file on Notepad++. Choose language as XML
*Goto the <DTS:FlatFileColumns> tag. Select all items within this tag
*Find the string **DTS:DataType="129"**  replace with **DTS:DataType="130"**
*Save the .DTSX file. 
*Open the project again on Visual Studio BIDS
*Double Click on the Source Task . You would get the message

the metadata of the following output columns does not match the metadata of the external columns with which the output columns are associated:
...
Do you want to replace the metadata of the output columns with the metadata of the external columns?

 *Now Click Yes. We are done !

How do I switch between command and insert mode in Vim?

Coming from emacs I've found that I like ctrl + keys to do stuff, and in vim I've found that both [ctrl + C] and [alt + backspace] will enter Normal mode from insert mode. You might try and see if any of those works out for you.

How to print spaces in Python?

First and foremost, for newlines, the simplest thing to do is have separate print statements, like this:

print("Hello")
print("World.")
#the parentheses allow it to work in Python 2, or 3.

To have a line break, and still only one print statement, simply use the "\n" within, as follows:

print("Hello\nWorld.")

Below, I explain spaces, instead of line breaks...

I see allot of people here using the + notation, which personally, I find ugly. Example of what I find ugly:

x=' ';
print("Hello"+10*x+"world"); 

The example above is currently, as I type this the top up-voted answer. The programmer is obviously coming into Python from PHP as the ";" syntax at the end of every line, well simple isn't needed. The only reason it doesn't through an error in Python is because semicolons CAN be used in Python, really should only be used when you are trying to place two lines on one, for aesthetic reasons. You shouldn't place these at the end of every line in Python, as it only increases file-size.

Personally, I prefer to use %s notation. In Python 2.7, which I prefer, you don't need the parentheses, "(" and ")". However, you should include them anyways, so your script won't through errors, in Python 3.x, and will run in either.

Let's say you wanted your space to be 8 spaces, So what I would do would be the following in Python > 3.x

print("Hello", "World.",  sep=' '*8, end="\n")
# you don't need to specify end, if you don't want to, but I wanted you to know it was also an option
#if you wanted to have an 8 space prefix, and did not wish to use tabs for some reason, you could do the following.
print("%sHello World." % (' '*8))

The above method will work in Python 2.x as well, but you cannot add the "sep" and "end" arguments, those have to be done manually in Python < 3.

Therefore, to have an 8 space prefix, with a 4 space separator, the syntax which would work in Python 2, or 3 would be:

print("%sHello%sWorld." % (' '*8, ' '*4))

I hope this helps.

P.S. You also could do the following.

>>> prefix=' '*8
>>> sep=' '*2
>>> print("%sHello%sWorld." % (prefix, sep))
    Hello  World.

How to count the number of columns in a table using SQL?

Old question - but I recently needed this along with the row count... here is a query for both - sorted by row count desc:

SELECT t.owner, 
       t.table_name, 
       t.num_rows, 
       Count(*) 
FROM   all_tables t 
       LEFT JOIN all_tab_columns c 
              ON t.table_name = c.table_name 
WHERE  num_rows IS NOT NULL 
GROUP  BY t.owner, 
          t.table_name, 
          t.num_rows 
ORDER  BY t.num_rows DESC; 

Python: Get the first character of the first string in a list?

Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case - this will return you a rest(except first char) of string.

If you have the following structure:

mylist = ['base', 'sample', 'test']

And want to get fist char for the first one string(item):

myList[0][0]
>>> b

If all first chars:

[x[0] for x in myList]
>>> ['b', 's', 't']    

If you have a text:

text = 'base sample test'
text.split()[0][0]
>>> b

How to scroll to the bottom of a UITableView on the iPhone before the view appears

No need for any scrolling you can just do it by using this code:

[YOURTABLEVIEWNAME setContentOffset:CGPointMake(0, CGFLOAT_MAX)];

Trigger change event of dropdown

Try this:

$('#id').change();

Works for me.

On one line together with setting the value: $('#id').val(16).change();

Current time in microseconds in java

You can use System.nanoTime():

long start = System.nanoTime();
// do stuff
long end = System.nanoTime();
long microseconds = (end - start) / 1000;

to get time in nanoseconds but it is a strictly relative measure. It has no absolute meaning. It is only useful for comparing to other nano times to measure how long something took to do.

Can I serve multiple clients using just Flask app.run() as standalone?

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

React-router: How to manually invoke Link?

again this is JS :) this still works ....

var linkToClick = document.getElementById('something');
linkToClick.click();

<Link id="something" to={/somewhaere}> the link </Link>

Is bool a native C type?

No such thing, probably just a macro for int

Getting URL parameter in java and extract a specific text from that URL

I solved the problem like this

public static String getUrlParameterValue(String url, String paramName) {
String value = "";
List<NameValuePair> result = null;

try {
    result = URLEncodedUtils.parse(new URI(url), UTF_8);
    value = result.stream().filter(pair -> pair.getName().equals(paramName)).findFirst().get().getValue();
    System.out.println("-------------->  \n" + paramName + " : " + value + "\n");
} catch (URISyntaxException e) {
    e.printStackTrace();
} 
return value;

}

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Do I need to pass the full path of a file in another directory to open()?

Here's a snippet that will walk the file tree for you:

indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        print(f)
        log = open(indir + f, 'r')

Dynamically set value of a file input

I had similar problem, then I tried writing this from JavaScript and it works! : referenceToYourInputFile.value = "" ;

How do I implement __getattribute__ without an infinite recursion error?

Actually, I believe you want to use the __getattr__ special method instead.

Quote from the Python docs:

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

Note: for this to work, the instance should not have a test attribute, so the line self.test=20 should be removed.

Return value from nested function in Javascript

Just FYI, Geocoder is asynchronous so the accepted answer while logical doesn't really work in this instance. I would prefer to have an outside object that acts as your updater.

var updater = {};

function geoCodeCity(goocoord) { 
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'latLng': goocoord
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            updater.currentLocation = results[1].formatted_address;
        } else {
            if (status == "ERROR") { 
                    console.log(status);
                }
        }
    });
};

How To Change DataType of a DataColumn in a DataTable?

I combined the efficiency of Mark's solution - so I do not have to .Clone the entire DataTable - with generics and extensibility, so I can define my own conversion function. This is what I ended up with:

/// <summary>
///     Converts a column in a DataTable to another type using a user-defined converter function.
/// </summary>
/// <param name="dt">The source table.</param>
/// <param name="columnName">The name of the column to convert.</param>
/// <param name="valueConverter">Converter function that converts existing values to the new type.</param>
/// <typeparam name="TTargetType">The target column type.</typeparam>
public static void ConvertColumnTypeTo<TTargetType>(this DataTable dt, string columnName, Func<object, TTargetType> valueConverter)
{
    var newType = typeof(TTargetType);

    DataColumn dc = new DataColumn(columnName + "_new", newType);

    // Add the new column which has the new type, and move it to the ordinal of the old column
    int ordinal = dt.Columns[columnName].Ordinal;
    dt.Columns.Add(dc);
    dc.SetOrdinal(ordinal);

    // Get and convert the values of the old column, and insert them into the new
    foreach (DataRow dr in dt.Rows)
    {
        dr[dc.ColumnName] = valueConverter(dr[columnName]);
    }

    // Remove the old column
    dt.Columns.Remove(columnName);

    // Give the new column the old column's name
    dc.ColumnName = columnName;
}

This way, usage is a lot more straightforward, while also customizable:

DataTable someDt = CreateSomeDataTable();
// Assume ColumnName is an int column which we want to convert to a string one.
someDt.ConvertColumnTypeTo<string>('ColumnName', raw => raw.ToString());

OpenCV & Python - Image too big to display

The other answers perform a fixed (width, height) resize. If you wanted to resize to a specific size while maintaining aspect ratio, use this

def ResizeWithAspectRatio(image, width=None, height=None, inter=cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]

    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))

    return cv2.resize(image, dim, interpolation=inter)

Example

image = cv2.imread('img.png')
resize = ResizeWithAspectRatio(image, width=1280) # Resize by width OR
# resize = ResizeWithAspectRatio(image, height=1280) # Resize by height 

cv2.imshow('resize', resize)
cv2.waitKey()

Java 8 optional: ifPresent return object orElseThrow exception

Two options here:

Replace ifPresent with map and use Function instead of Consumer

private String getStringIfObjectIsPresent(Optional<Object> object) {
    return object
            .map(obj -> {
                String result = "result";
                //some logic with result and return it
                return result;
            })
            .orElseThrow(MyCustomException::new);
}

Use isPresent:

private String getStringIfObjectIsPresent(Optional<Object> object) {
    if (object.isPresent()) {
        String result = "result";
        //some logic with result and return it
        return result;
    } else {
        throw new MyCustomException();
    }
}

How do you connect to a MySQL database using Oracle SQL Developer?

Although @BrianHart 's answer is correct, if you are connecting from a remote host, you'll also need to allow remote hosts to connect to the MySQL/MariaDB database.

My article describes the full instructions to connect to a MySQL/MariaDB database in Oracle SQL Developer:

https://alvinbunk.wordpress.com/2017/06/29/using-oracle-sql-developer-to-connect-to-mysqlmariadb-databases/

What are the most common font-sizes for H1-H6 tags

Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.

How to prevent scientific notation in R?

To set the use of scientific notation in your entire R session, you can use the scipen option. From the documentation (?options):

‘scipen’: integer.  A penalty to be applied when deciding to print
          numeric values in fixed or exponential notation.  Positive
          values bias towards fixed and negative towards scientific
          notation: fixed notation will be preferred unless it is more
          than ‘scipen’ digits wider.

So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999:

options(scipen=999)

git error: failed to push some refs to remote

Rename your branch and then push, e.g.:

git branch -m new-name
git push -u new-name

This worked for me.

Rename computer and join to domain in one step with PowerShell

This will prompt for computer name and join to domain then restart.

$computerName = Get-WmiObject Win32_ComputerSystem 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$name = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Desired Computer Name ")
$computername.rename("$name")
Add-Computer -DomainName [domainname] -Credential [user\domain]  -Verbose
Restart-Computer

Submit button doesn't work

Hello from the future.

For clarity, I just wanted to add (as this was pretty high up in google) - we can now use

<button type="submit">Upload Stuff</button>

And to reset a form

<button type="reset" value="Reset">Reset</button>

Check out button types

We can also attach buttons to submit forms like this:

<button type="submit" form="myform" value="Submit">Submit</button>

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

git init
git remote add origin [email protected]:<user>/<repo>.git
git remote -v
git pull origin master

Call a Class From another class

Class2 class2 = new Class2();

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

Appending to an object

Now with ES6 we have a very powerful spread operator (...Object) which can make this job very easy. It can be done as follows:

let alerts = { 
   1: { app: 'helloworld', message: 'message' },
   2: { app: 'helloagain', message: 'another message' }
} 

//now suppose you want to add another key called alertNo. with value 2 in the alerts object. 

alerts = {
   ...alerts,
   alertNo: 2
 }

Thats it. It will add the key you want. Hope this helps!!

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

The system function requires const char *, and your expression is of the type std::string. You should write

string name = "john";
string system_str = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'";
system(system_str.c_str ());

How to get a user's client IP address in ASP.NET?

use this

Dns.GetHostEntry(Dns.GetHostName())

How do I create a new user in a SQL Azure database?

You can simply create a contained user in SQL DB V12.

Create user containeduser with password = 'Password'

Contained user login is more efficient than login to the database using the login created by master. You can find more details @ http://www.sqlindepth.com/contained-users-in-sql-azure-db-v12/

Send array with Ajax to PHP script

Encode your data string into JSON.

dataString = ??? ; // array?
var jsonString = JSON.stringify(dataString);
   $.ajax({
        type: "POST",
        url: "script.php",
        data: {data : jsonString}, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

In your PHP

$data = json_decode(stripslashes($_POST['data']));

  // here i would like use foreach:

  foreach($data as $d){
     echo $d;
  }

Note

When you send data via POST, it needs to be as a keyvalue pair.

Thus

data: dataString

is wrong. Instead do:

data: {data:dataString}

Reading an Excel file in PHP

Try this...

I have used following code to read "xls and xlsx"

    <?php
    include 'excel_reader.php';       // include the class
    $excel = new PhpExcelReader;      // creates object instance of the class
    $excel->read('excel_file.xls');   // reads and stores the excel file data

    // Test to see the excel data stored in $sheets property
    echo '<pre>';
    var_export($excel->sheets);

    echo '</pre>';

    or 

 echo '<pre>';
    print_r($excel->sheets);

    echo '</pre>';

Reference:http://coursesweb.net/php-mysql/read-excel-file-data-php_pc

Update statement with inner join on Oracle

UPDATE table1 t1
SET t1.value = 
    (select t2.CODE from table2 t2 
     where t1.value = t2.DESC) 
WHERE t1.UPDATETYPE='blah';

Java: How to stop thread?

One possible way is to do something like this:

public class MyThread extends Thread {
    @Override
    public void run() {
        while (!this.isInterrupted()) {
            //
        }
    }
}

And when you want to stop your thread, just call a method interrupt():

myThread.interrupt();

Of course, this won't stop thread immediately, but in the following iteration of the loop above. In the case of downloading, you need to write a non-blocking code. It means, that you will attempt to read new data from the socket only for a limited amount of time. If there are no data available, it will just continue. It may be done using this method from the class Socket:

mySocket.setSoTimeout(50);

In this case, timeout is set up to 50 ms. After this time has gone and no data was read, it throws an SocketTimeoutException. This way, you may write iterative and non-blocking thread, which may be killed using the construction above.

It's not possible to kill thread in any other way and you've to implement such a behavior yourself. In past, Thread had some method (not sure if kill() or stop()) for this, but it's deprecated now. My experience is, that some implementations of JVM doesn't even contain that method currently.

Python CSV error: line contains NULL byte

Why are you doing this?

 reader = csv.reader(open(filepath, "rU"))

The docs are pretty clear that you must do this:

with open(filepath, "rb") as src:
    reader= csv.reader( src )

The mode must be "rb" to read.

http://docs.python.org/library/csv.html#csv.reader

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java

How to add a class with React.js?

you can also use pure js to accomplish this like the old ways with jquery

try this if you want a simple way

 document.getElementById("myID").classList.add("show-example");

Spring Boot Multiple Datasource

I faced same issue few days back, I followed the link mentioned below and I could able to overcome the problem

http://www.baeldung.com/spring-data-jpa-multiple-databases

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

Well, I think the error says that it can't find a nib file named "RootViewController" in your project.

You are writing these lines of code,

self.viewController = [[RootViewController alloc]      initWithNibName:@"RootViewController_iPhone.xib" bundle:nil];

self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController_iPad.xib" bundle:nil];

At the same time you are asking it to load a nib file named "RootviewController"..!! Where is it..? Do you have a xib file named "Rootviewcontroller"..?

Horizontal ListView in Android?

There is a great library for that, called TwoWayView, it's very easy to implement, just include the project library into your work space and add it as a library project to your original project, and then follow the following steps which are originally mentioned here:

First, let's add a style indicating the orientation of the ListView (horizontal or vertical) in (res/values/styles.xml):

<style name="TwoWayView">
    <item name="android:orientation">horizontal</item>
</style>

Then,

In your Layout XML, use the following code to add the TwoWayView:

<org.lucasr.twowayview.TwoWayView 
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:id="@+id/lvItems"
     style="@style/TwoWayView"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:drawSelectorOnTop="false"
     tools:context=".MainActivity" />

and finally, just declare it and deal with it like any regular ListView:

TwoWayView lvTest = (TwoWayView) findViewById(R.id.lvItems);

All the methods of ListView will work here as usual, but there is only one difference I noticed, which is when setting the choice mode, the method setChoiceMode not takes an int value but a value from enum called ChoiceMode, so list_view.setChoiceMode(ListView.CHOICE_MODE_SINGLE); will be lvTest.setChoiceMode(ChoiceMode.SINGLE); // or MULTIPLE or NONE.

Response Content type as CSV

Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )

  • text/comma-separated-values
  • text/csv
  • application/csv
  • application/excel
  • application/vnd.ms-excel
  • application/vnd.msexcel

Also, the mime-type might be case sensitive...

Hibernate Delete query

instead of using

session.delete(object)

use

getHibernateTemplate().delete(object)

In both place for select query and also for delete use getHibernateTemplate()

In select query you have to use DetachedCriteria or Criteria

Example for select query

List<foo> fooList = new ArrayList<foo>();
DetachedCriteria queryCriteria = DetachedCriteria.forClass(foo.class);
queryCriteria.add(Restrictions.eq("Column_name",restriction));
fooList = getHibernateTemplate().findByCriteria(queryCriteria);

In hibernate avoid use of session,here I am not sure but problem occurs just because of session use

Java escape JSON String?

org.json.simple.JSONObject.escape() escapes quotes,, /, \r, \n, \b, \f, \t and other control characters.

import org.json.simple.JSONValue;
JSONValue.escape("test string");

Add pom.xml when using maven

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <scope>test</scope>
</dependency>

How to find out which JavaScript events fired?

Just thought I'd add that you can do this in Chrome as well:

Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).

You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).

For example:

  • Right click on the upvote button to the left
  • Select inspect element
  • Collapse the styles section (section on the far right - double chevron)
  • Expand the event listeners option
  • Now you can see the events bound to the upvote
  • Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.

    Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2

    It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.

    AnonymousAndrew has also pointed out monitorEvents(window); here

    SQL Server Insert if not exists

    Try below code

    ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
      (@_DE nvarchar(50),
       @_ASSUNTO nvarchar(50),
       @_DATA nvarchar(30) )
    AS
    BEGIN
       INSERT INTO EmailsRecebidos (De, Assunto, Data)
       select @_DE, @_ASSUNTO, @_DATA
       EXCEPT
       SELECT De, Assunto, Data from EmailsRecebidos
    END
    

    Random integer in VB.NET

    Public Function RandomNumber(ByVal n As Integer) As Integer
        'initialize random number generator
        Dim r As New Random(System.DateTime.Now.Millisecond)
        Return r.Next(1, n)
    End Function
    

    How to get only numeric column values?

    Use This [Tested]

    To get numeric

    SELECT column1
    FROM table
    WHERE Isnumeric(column1) = 1; // will return Numeric values
    

    To get non-numeric

    SELECT column1
    FROM table
    WHERE Isnumeric(column1) = 0; // will return non-numeric values
    

    Is it a good practice to place C++ definitions in header files?

    I think your co-worker is right as long as he does not enter in the process to write executable code in the header. The right balance, I think, is to follow the path indicated by GNAT Ada where the .ads file gives a perfectly adequate interface definition of the package for its users and for its childs.

    By the way Ted, have you had a look on this forum to the recent question on the Ada binding to the CLIPS library you wrote several years ago and which is no more available (relevant Web pages are now closed). Even if made to an old Clips version, this binding could be a good start example for somebody willing to use the CLIPS inference engine within an Ada 2012 program.

    Random strings in Python

    This function generates random string consisting of upper,lowercase letters, digits, pass the length seperator, no_of_blocks to specify your string format

    eg: len_sep = 4, no_of_blocks = 4 will generate the following pattern,

    F4nQ-Vh5z-JKEC-WhuS

    Where, length seperator will add "-" after 4 characters

    XXXX-

    no of blocks will generate the following patten of characters as string

    XXXX - XXXX - XXXX - XXXX

    if a single random string is needed, just keep the no_of_blocks variable to be equal to 1 and len_sep to specify the length of the random string.

    eg: len_sep = 10, no_of_blocks = 1, will generate the following pattern ie. random string of length 10,

    F01xgCdoDU

    import random as r
    
    def generate_random_string(len_sep, no_of_blocks):
        random_string = ''
        random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for i in range(0,len_sep*no_of_blocks):
            if i % len_sep == 0 and i != 0:
                random_string += '-'
            random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
        return random_string
    

    Matlab: Running an m-file from command-line

    I think that one important point that was not mentioned in the previous answers is that, if not explicitly indicated, the matlab interpreter will remain open. Therefore, to the answer of @hkBattousai I will add the exit command:

    "C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m');exit;"

    Tool to monitor HTTP, TCP, etc. Web Service traffic

    Wireshark (or Tshark) is probably the defacto standard traffic inspection tool. It is unobtrusive and works without fiddling with port redirecting and proxying. It is very generic, though, as does not (AFAIK) provide any tooling specifically to monitor web service traffic - it's all tcp/ip and http.

    You have probably already looked at tcpmon but I don't know of any other tool that does the sit-in-between thing.

    C#: easiest way to populate a ListBox from a List

    Is this what you are looking for:

    myListBox.DataSource = MyList;
    

    Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

    combined Extension + DateComponentsFormatter from the answer of @leo-dabus

    Xcode 8.3 • Swift 3.1

    extension DateComponentsFormatter {
        func difference(from fromDate: Date, to toDate: Date) -> String? {
            self.allowedUnits = [.year,.month,.weekOfMonth,.day]
            self.maximumUnitCount = 1
            self.unitsStyle = .full
            return self.string(from: fromDate, to: toDate)
        }
    }
    
    let dateComponentsFormatter = DateComponentsFormatter()
    dateComponentsFormatter.difference(from: Date(), to: Date(timeIntervalSinceNow: 4000000)) // "1 month"
    

    Find size of an array in Perl

    There are various ways to print size of an array. Here are the meanings of all:

    Let’s say our array is my @arr = (3,4);

    Method 1: scalar

    This is the right way to get the size of arrays.

    print scalar @arr;  # Prints size, here 2
    

    Method 2: Index number

    $#arr gives the last index of an array. So if array is of size 10 then its last index would be 9.

    print $#arr;     # Prints 1, as last index is 1
    print $#arr + 1; # Adds 1 to the last index to get the array size
    

    We are adding 1 here, considering the array as 0-indexed. But, if it's not zero-based then, this logic will fail.

    perl -le 'local $[ = 4; my @arr = (3, 4); print $#arr + 1;'   # prints 6
    

    The above example prints 6, because we have set its initial index to 4. Now the index would be 5 and 6, with elements 3 and 4 respectively.

    Method 3:

    When an array is used in a scalar context, then it returns the size of the array

    my $size = @arr;
    print $size;   # Prints size, here 2
    

    Actually, method 3 and method 1 are same.

    How to pass in password to pg_dump?

    You can pass a password into pg_dump directly by using the following:

    pg_dump "host=localhost port=5432 dbname=mydb user=myuser password=mypass" > mydb_export.sql
    

    Generate random numbers using C++11 random library

    I red all the stuff above, about 40 other pages with c++ in it like this and watched the video from Stephan T. Lavavej "STL" and still wasn't sure how random numbers works in praxis so I took a full Sunday to figure out what its all about and how it works and can be used.

    In my opinion STL is right about "not using srand anymore" and he explained it well in the video 2. He also recommend to use:

    a) void random_device_uniform() -- for encrypted generation but slower (from my example)

    b) the examples with mt19937 -- faster, ability to create seeds, not encrypted


    I pulled out all claimed c++11 books I have access to and found f.e. that german Authors like Breymann (2015) still use a clone of

    srand( time( 0 ) );
    srand( static_cast<unsigned int>(time(nullptr))); or
    srand( static_cast<unsigned int>(time(NULL))); or
    

    just with <random> instead of <time> and <cstdlib> #includings - so be careful to learn just from one book :).

    Meaning - that shouldn't be used since c++11 because:

    Programs often need a source of random numbers. Prior to the new standard, both C and C++ relied on a simple C library function named rand. That function produces pseudorandom integers that are uniformly distributed in the range from 0 to a system- dependent maximum value that is at least 32767. The rand function has several problems: Many, if not most, programs need random numbers in a different range from the one produced by rand. Some applications require random floating-point numbers. Some programs need numbers that reflect a nonuniform distribution. Programmers often introduce nonrandomness when they try to transform the range, type, or distribution of the numbers generated by rand. (quote from Lippmans C++ primer fifth edition 2012)


    I finally found a the best explaination out of 20 books in Bjarne Stroustrups newer ones - and he should know his stuff - in "A tour of C++ 2019", "Programming Principles and Practice Using C++ 2016" and "The C++ Programming Language 4th edition 2014" and also some examples in "Lippmans C++ primer fifth edition 2012":

    And it is really simple because a random number generator consists of two parts: (1) an engine that produces a sequence of random or pseudo-random values. (2) a distribution that maps those values into a mathematical distribution in a range.


    Despite the opinion of Microsofts STL guy, Bjarne Stroustrups writes:

    In , the standard library provides random number engines and distributions (§24.7). By default use the default_random_engine , which is chosen for wide applicability and low cost.

    The void die_roll() Example is from Bjarne Stroustrups - good idea generating engine and distribution with using (more bout that here).


    To be able to make practical use of the random number generators provided by the standard library in <random> here some executable code with different examples reduced to the least necessary that hopefully safe time and money for you guys:

        #include <random>     //random engine, random distribution
        #include <iostream>   //cout
        #include <functional> //to use bind
    
        using namespace std;
    
    
        void space() //for visibility reasons if you execute the stuff
        {
           cout << "\n" << endl;
           for (int i = 0; i < 20; ++i)
           cout << "###";
           cout << "\n" << endl;
        }
    
        void uniform_default()
        {
        // uniformly distributed from 0 to 6 inclusive
            uniform_int_distribution<size_t> u (0, 6);
            default_random_engine e;  // generates unsigned random integers
    
        for (size_t i = 0; i < 10; ++i)
            // u uses e as a source of numbers
            // each call returns a uniformly distributed value in the specified range
            cout << u(e) << " ";
        }
    
        void random_device_uniform()
        {
             space();
             cout << "random device & uniform_int_distribution" << endl;
    
             random_device engn;
             uniform_int_distribution<size_t> dist(1, 6);
    
             for (int i=0; i<10; ++i)
             cout << dist(engn) << ' ';
        }
    
        void die_roll()
        {
            space();
            cout << "default_random_engine and Uniform_int_distribution" << endl;
    
        using my_engine = default_random_engine;
        using my_distribution = uniform_int_distribution<size_t>;
    
            my_engine rd {};
            my_distribution one_to_six {1, 6};
    
            auto die = bind(one_to_six,rd); // the default engine    for (int i = 0; i<10; ++i)
    
            for (int i = 0; i <10; ++i)
            cout << die() << ' ';
    
        }
    
    
        void uniform_default_int()
        {
           space();
           cout << "uniform default int" << endl;
    
           default_random_engine engn;
           uniform_int_distribution<size_t> dist(1, 6);
    
            for (int i = 0; i<10; ++i)
            cout << dist(engn) << ' ';
        }
    
        void mersenne_twister_engine_seed()
        {
            space();
            cout << "mersenne twister engine with seed 1234" << endl;
    
            //mt19937 dist (1234);  //for 32 bit systems
            mt19937_64 dist (1234); //for 64 bit systems
    
            for (int i = 0; i<10; ++i)
            cout << dist() << ' ';
        }
    
    
        void random_seed_mt19937_2()
        {
            space();
            cout << "mersenne twister split up in two with seed 1234" << endl;
    
            mt19937 dist(1234);
            mt19937 engn(dist);
    
            for (int i = 0; i < 10; ++i)
            cout << dist() << ' ';
    
            cout << endl;
    
            for (int j = 0; j < 10; ++j)
            cout << engn() << ' ';
        }
    
    
    
        int main()
        {
                uniform_default(); 
                random_device_uniform();
                die_roll();
                random_device_uniform();
                mersenne_twister_engine_seed();
                random_seed_mt19937_2();
            return 0;
        }
    

    I think that adds it all up and like I said, it took me a bunch of reading and time to destill it to that examples - if you have further stuff about number generation I am happy to hear about that via pm or in the comment section and will add it if necessary or edit this post. Bool

    CSS3 gradient background set on body doesn't stretch but instead repeats?

    I had trouble getting the answers in here to work.
    I found it worked better to fix a full-size div in the body, give it a negative z-index, and attach the gradient to it.

    <style>
    
      .fixed-background {
        position:fixed;
        margin-left: auto;
        margin-right: auto;
        top: 0;
        width: 100%;
        height: 100%;
        z-index: -1000;
        background-position: top center;
        background-size: cover;
        background-repeat: no-repeat;
      }
    
      .blue-gradient-bg {
        background: #134659; /* For browsers that do not support gradients */
        background: -webkit-linear-gradient(top, #134659 , #2b7692); /* For Safari 5.1 to 6.0 */
        background: -o-linear-gradient(bottom, #134659, #2b7692); /* For Opera 11.1 to 12.0 */
        background: -moz-linear-gradient(top, #134659, #2b7692); /* For Firefox 3.6 to 15 */
        background: linear-gradient(to bottom, #134659 , #2b7692); /* Standard syntax */
      }
    
      body{
        margin: 0;
      }
    
    </style>
    
    <body >
     <div class="fixed-background blue-gradient-bg"></div>
    </body>
    

    Here's a full sample https://gist.github.com/morefromalan/8a4f6db5ce43b5240a6ddab611afdc55

    What is this Javascript "require"?

    It's used to load modules. Let's use a simple example.

    In file circle_object.js:

    var Circle = function (radius) {
        this.radius = radius
    }
    Circle.PI = 3.14
    
    Circle.prototype = {
        area: function () {
            return Circle.PI * this.radius * this.radius;
        }
    }
    

    We can use this via require, like:

    node> require('circle_object')
    {}
    node> Circle
    { [Function] PI: 3.14 }
    node> var c = new Circle(3)
    { radius: 3 }
    node> c.area()
    

    The require() method is used to load and cache JavaScript modules. So, if you want to load a local, relative JavaScript module into a Node.js application, you can simply use the require() method.

    Example:

    var yourModule = require( "your_module_name" ); //.js file extension is optional
    

    How do I grep recursively?

    If you know the extension or pattern of the file you would like, another method is to use --include option:

    grep -r --include "*.txt" texthere .
    

    You can also mention files to exclude with --exclude.

    Ag

    If you frequently search through code, Ag (The Silver Searcher) is a much faster alternative to grep, that's customized for searching code. For instance, it's recursive by default and automatically ignores files and directories listed in .gitignore, so you don't have to keep passing the same cumbersome exclude options to grep or find.

    Is there a way to link someone to a YouTube Video in HD 1080p quality?

    Yes there is:

    https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1440
    https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1080
    etc...
    

    Options are:

    Code for 1440: vq=hd1440
    Code for 1080: vq=hd1080
    Code for 720: vq=hd720
    Code for 480p: vq=large
    Code for 360p: vq=medium
    Code for 240p: vq=small

    UPDATE
    As of 10 of April 2018, this code still works.
    Some users reported "not working", if it doesn't work for you, please read below:

    From what I've learned, the problem is related with network speed and or screen size.
    When YT player starts, it collects the network speed, screen and player sizes, among other information, if the connection is slow or the screen/player size smaller than the quality requested(vq=), a lower quality video is displayed despite the option selected on vq=.

    Also make sure you read the comments below.

    ES6 Map in Typescript

    Not sure if this is official but this worked for me in typescript 2.7.1:

    class Item {
       configs: Map<string, string>;
       constructor () {
         this.configs = new Map();
       }
    }
    

    In simple Map<keyType, valueType>

    Apache HttpClient Android (Gradle)

    I resolved problem by adding following to my build.gradle file

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

    However this only works if you are using gradle 1.3.0-beta2 or greater, so you will have to add this to buildscript dependencies if you are on a lower version:

    classpath 'com.android.tools.build:gradle:1.3.0-beta2'
    

    Installing tensorflow with anaconda in windows

    The above steps

    conda install -c conda-forge tensorflow
    

    will work for Windows 10 as well but the Python version should be 3.5 or above. I have used it with Anaconda Python version 3.6 as the protocol buffer format it refers to available on 3.5 or above. Thanks, Sandip

    Access restriction on class due to restriction on required library rt.jar?

    • Go to the Build Path settings in the project properties. Windows -> Preferences -> Java Compiler
    • Remove the JRE System Library
    • Add another JRE with a "perfect match"
    • clean and build your project again. It worked for me.

    How to increase heap size for jBoss server

    In my case, for jboss 6.3 I had to change JAVA_OPTS in file jboss-eap-6.3\bin\standalone.conf.bat and set following values -Xmx8g -Xms8g -Xmn3080m for jvm to take 8gb space.

    How to check if Location Services are enabled?

    i use first code begin create method isLocationEnabled

     private LocationManager locationManager ;
    
    protected boolean isLocationEnabled(){
            String le = Context.LOCATION_SERVICE;
            locationManager = (LocationManager) getSystemService(le);
            if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
                return false;
            } else {
                return true;
            }
        }
    

    and i check Condition if ture Open the map and false give intent ACTION_LOCATION_SOURCE_SETTINGS

        if (isLocationEnabled()) {
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
    
            locationClient = getFusedLocationProviderClient(this);
            locationClient.getLastLocation()
                    .addOnSuccessListener(new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // GPS location can be null if GPS is switched off
                            if (location != null) {
                                onLocationChanged(location);
    
                                Log.e("location", String.valueOf(location.getLongitude()));
                            }
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.e("MapDemoActivity", e.toString());
                            e.printStackTrace();
                        }
                    });
    
    
            startLocationUpdates();
    
        }
        else {
            new AlertDialog.Builder(this)
                    .setTitle("Please activate location")
                    .setMessage("Click ok to goto settings else exit.")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }
                    })
                    .show();
        }
    

    enter image description here

    How to define several include path in Makefile

    Make's substitutions feature is nice and helped me to write

    %.i: src/%.c $(INCLUDE)
            gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@
    

    You might find this useful, because it asks make to check for changes in include folders too

    PHP: How to check if image file exists?

    You can use the file_get_contents function to access remote files. See http://php.net/manual/en/function.file-get-contents.php for details.

    Div Height in Percentage

    There is the semicolon missing (;) after the "50%"

    but you should also notice that the percentage of your div is connected to the div that contains it.

    for instance:

    <div id="wrapper">
      <div class="container">
       adsf
      </div>
    </div>
    
    #wrapper {
      height:100px;
    }
    .container
    {
      width:80%;
      height:50%;
      background-color:#eee;
    }
    

    here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.

    if you have:

    adsf

    #wrapper {
      height:400px;
    }
    .container
    {
      width:80%;
      height:50%;
      background-color:#eee;
    }
    

    then you .container will be 200px. 50% of the wrapper.

    So you may want to look at the divs "wrapping" your ".container"...

    Determine what user created objects in SQL Server

    If the object was recently created, you can check the Schema Changes History report, within the SQL Server Management Studio, which "provides a history of all committed DDL statement executions within the Database recorded by the default trace":

    enter image description here

    You then can search for the create statements of the objects. Among all the information displayed, there is the login name of whom executed the DDL statement.

    Gson library in Android Studio

    If you are going to use it with Retrofit library, I suggest you to use Square's gson library as:

    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    

    How do you render primitives as wireframes in OpenGL?

    You can use glut libraries like this:

    1. for a sphere:

      glutWireSphere(radius,20,20);
      
    2. for a Cylinder:

      GLUquadric *quadratic = gluNewQuadric();
      gluQuadricDrawStyle(quadratic,GLU_LINE);
      gluCylinder(quadratic,1,1,1,12,1);
      
    3. for a Cube:

      glutWireCube(1.5);
      

    How to avoid soft keyboard pushing up my layout?

    I had the same problem, but setting windowSoftInputMode did not help, and I did not want to change the upper view to have isScrollContainer="false" because I wanted it to scroll.

    My solution was to define the top location of the navigation tools instead of the bottom. I'm using Titanium, so I'm not sure exactly how this would translate to android. Defining the top location of the navigation tools view prevented the soft keyboard from pushing it up, and instead covered the nav controls like I wanted.

    How do I append a node to an existing XML file in java

    The following complete example will read an existing server.xml file from the current directory, append a new Server and re-write the file to server.xml. It does not work without an existing .xml file, so you will need to modify the code to handle that case.

    import java.util.*;
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    import javax.xml.transform.dom.*;
    import org.w3c.dom.*;
    import javax.xml.parsers.*;
    
    public class AddXmlNode {
        public static void main(String[] args) throws Exception {
    
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse("server.xml");
            Element root = document.getDocumentElement();
    
            Collection<Server> servers = new ArrayList<Server>();
            servers.add(new Server());
    
            for (Server server : servers) {
                // server elements
                Element newServer = document.createElement("server");
    
                Element name = document.createElement("name");
                name.appendChild(document.createTextNode(server.getName()));
                newServer.appendChild(name);
    
                Element port = document.createElement("port");
                port.appendChild(document.createTextNode(Integer.toString(server.getPort())));
                newServer.appendChild(port);
    
                root.appendChild(newServer);
            }
    
            DOMSource source = new DOMSource(document);
    
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            StreamResult result = new StreamResult("server.xml");
            transformer.transform(source, result);
        }
    
        public static class Server {
            public String getName() { return "foo"; }
            public Integer getPort() { return 12345; }
        }
    }
    

    Example server.xml file:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Servers>
      <server>
        <name>something</name>
        <port>port</port>
      </server>
    </Servers>
    

    The main change to your code is not creating a new "root" element. The above example just uses the current root node from the existing server.xml and then just appends a new Server element and re-writes the file.

    Unique device identification

    You can use the fingerprintJS2 library, it helps a lot with calculating a browser fingerprint.

    By the way, on Panopticlick you can see how unique this usually is.

    Extreme wait-time when taking a SQL Server database offline

    To get around this I stopped the website that was connected to the db in IIS and immediately the 'frozen' 'take db offline' panel became unfrozen.

    How do I remove a comma off the end of a string?

    I had a pesky "invisible" space at the end of my string and had to do this

     $update_sql=rtrim(trim($update_sql),',');
    

    But a solution above is better

     $update_sql=rtrim($update_sql,', ');
    

    rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

    I was having the exact same error in my development environment. In the end all I needed to do in order to fix it was to add:

    config.assets.manifest = Rails.root.join("public/assets")
    

    to my config/environments/development.rb file and it fixed it. My final config in development related to assets looks like:

    config.assets.compress = false  
    config.assets.precompile += %w[bootstrap-alerts.js] #Lots of other space separated files
    config.assets.compile = false
    config.assets.digest = true
    config.assets.manifest = Rails.root.join("public/assets")
    config.assets.debug = true
    

    execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

    when i generate rails g controller i got the same error. After that when do the following changes on Gemfile(in rails 4) everything went smooth.The changes i made was

    gem 'execjs'
    gem 'therubyracer', "0.11.4"
    After that i can able to run the server and able to do all basic operations on the application.

    Visual Studio 64 bit?

    Is there any 64 bit Visual Studio at all?

    Yes literally there is one called "Visual Studio" and is 64bit, but well,, on Mac not on Windows

    Why not?

    Decision making is electro-chemical reaction made in our brain and that have an activation point (Nerdest answer I can come up with, but follow). Same situation happened in history: Windows 64!...

    So in order to answer this fully I want you to remember old days. Imagine reasons for "why not we see 64bit Windows" are there at the time. I think at the time for Windows64 they had exact same reasons others have enlisted here about "reasons why not 64bit VS on windows" were on "reasons why not 64bit Windows" too. Then why they did start development for Windows 64bit? Simple! If they didn't succeed in making 64bit Windows I bet M$ would have been a history nowadays. If same reasons forcing M$ making 64bit Windows starts to appear on need for 64Bit VS then I bet we will see 64bit VS, even though very same reasons everyone else here enlisted will stay same! In time the limitations of 32bit may hit VS as well, so most likely something like below start to happen:

    • Visual Studio will drop 32bit support and become 64bit,
    • Visual Studio Code will take it's place instead,
    • Visual Studio will have similar functionality like WOW64 for old extensions which is I believe unlikely to happen.

    I put my bets on Visual Studio Code taking the place in time; I guess bifurcation point for it will be some CPU manufacturer X starts to compete x86_64 architecture taking its place on mainstream market for laptop and/or workstation,

    How to customize the background color of a UITableViewCell?

    This will work in the latest Xcode.

    -(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {
        cell.backgroundColor = [UIColor grayColor];
    }
    

    wampserver doesn't go green - stays orange

    My problem was not related to skype as i didn't had it installed. The solution I found was that 2 .dll files(msvcp110.dll, msvcr110.dll) were missing from the directory :

    C:\wamp\bin\apache\apache2.4.9\bin
    

    So I copied these 2 files to all these locations just in case and restarted wamp it worked

    C:\wamp
    C:\wamp\bin\apache\apache2.4.9\bin
    C:\wamp\bin\apache\apache2.4.9
    C:\wamp\bin\mysql\mysql5.6.17
    C:\wamp\bin\php\php5.5.12
    

    I hope this helps someone out.

    How to get database structure in MySQL via query

    using this:

    SHOW CREATE TABLE `users`;
    

    will give you the DDL for that table

    DESCRIBE `users`
    

    will list the columns in that table

    Check whether number is even or odd

    This following program can handle large numbers ( number of digits greater than 20 )

    package com.isEven.java;
    import java.util.Scanner;
    
    public class isEvenValuate{
    
    public static void main(String[] args) {            
    
            Scanner in = new Scanner(System.in);
            String digit = in.next();
    
            int y = Character.getNumericValue(digit.charAt(digit.length()-1));
    
            boolean isEven = (y&1)==0;
    
            if(isEven)
                System.out.println("Even");
            else
                System.out.println("Odd");
    
        }
    }
    

    Here is the output ::

      122873215981652362153862153872138721637272
      Even
    

    .htaccess not working on localhost with XAMPP

    For windows user, make sure to closely look at this section.

    RewriteRule ^properties$ /property_available.php/$1 [NC,QSA]
    

    As said in Apache documentation :

    The mod_rewrite module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite requested URLs on the fly.

    So ^properties$ means Apache will only look for URL that has exact match with properties. You might want to try this code.

    RewriteRule properties /property_available.php/$1 [NC,QSA]
    

    So Apache will see the URL that has properties and rewrite it to /property_available.php/

    Installing MySQL-python

    Reread the error message. It says:

    sh: mysql_config: not found

    If you are on Ubuntu Natty, mysql_config belongs to package libmysqlclient-dev

    Android Get Current timestamp?

    Solution in Kotlin:

    val nowInEpoch = Instant.now().epochSecond
    

    Make sure your minimum SDK version is 26.

    Converting XDocument to XmlDocument and vice versa

    There is a discussion on http://blogs.msdn.com/marcelolr/archive/2009/03/13/fast-way-to-convert-xmldocument-into-xdocument.aspx

    It seems that reading an XDocument via an XmlNodeReader is the fastest method. See the blog for more details.

    CSS Always On Top

    Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

    element {
        position: fixed;
        z-index: 999;
    }
    
    div {
        position: relative;
        z-index: 99;
    }
    

    It will probably require some more work than that but it's a start since you didn't post any code.

    Angular window resize event

    On Angular2 (2.1.0) I use ngZone to capture the screen change event.

    Take a look on the example:

    import { Component, NgZone } from '@angular/core';//import ngZone library
    ...
    //capture screen changed inside constructor
    constructor(private ngZone: NgZone) {
        window.onresize = (e) =>
        {
            ngZone.run(() => {
                console.log(window.innerWidth);
                console.log(window.innerHeight);
            });
        };
    }
    

    I hope this help!

    How to horizontally center a floating element of a variable width?

    This works better when the id = container (which is the outer div) and id = contained (which is the inner div). The problem with the highly recommended solution is that it results in some cases into an horizontal scrolling bar when the browser is trying to cater for the left: -50% attribute. There is a good reference for this solution

            #container {
                text-align: center;
            }
            #contained {
                text-align: left;
                display: inline-block;
            }
    

    SQL join format - nested inner joins

    Since you've already received help on the query, I'll take a poke at your syntax question:

    The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

    Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

    select
     count(*)
    from Table1 as t1
    join Table2 as t2
        join Table3 as t3
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2 
    on t1.DifferentKey = t3.DifferentKey     -- join #2  
    

    This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

    select
     count(*)
    from Table1 as t1
        join Table3 as t3
            join Table2 as t2
            on t2.Key = t3.Key                   -- join #1
            and t2.Key2 = t3.Key2   
        on t1.DifferentKey = t3.DifferentKey     -- join #2
    

    Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

    Image.open() cannot identify image file - Python?

    In my case the image file had just been written to and needed to be flushed before opening, like so:

    img_file.flush() 
    img = Image.open(img_file.name))
    

    How to get the title of HTML page with JavaScript?

    Put in the URL bar and then click enter:

    javascript:alert(document.title);
    

    You can select and copy the text from the alert depending on the website and the web browser you are using.

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

    Check this list or just keep trying upload!

    • Got to member center
    • Check if there are any invalid provisioning profiles (for some reason, my app store distribution profile has become invalid)
    • Delete invalid profiles
    • Create new ones
    • Download and drag on XCode
    • Reboot Mac
    • Archive => Upload to App Store
    • Everything should be fine again

    Removing elements from array Ruby

    [1,3].inject([1,1,1,2,2,3]) do |memo,element|
      memo.tap do |memo|
        i = memo.find_index(e)
        memo.delete_at(i) if i
      end
    end
    

    How to run a JAR file

    You have to add a manifest to the jar, which tells the java runtime what the main class is. Create a file 'Manifest.mf' with the following content:

    Manifest-Version: 1.0
    Main-Class: your.programs.MainClass
    

    Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.

    What is a deadlock?

    To define deadlock, first I would define process.

    Process : As we know process is nothing but a program in execution.

    Resource : To execute a program process needs some resources. Resource categories may include memory, printers, CPUs, open files, tape drives, CD-ROMS, etc.

    Deadlock : Deadlock is a situation or condition when two or more processes are holding some resources and trying to acquire some more resources, and they can not release the resources until they finish there execution.

    Deadlock condition or situation

    enter image description here

    In the above diagram there are two process P1 and p2 and there are two resources R1 and R2.

    Resource R1 is allocated to process P1 and resource R2 is allocated to process p2. To complete execution of process P1 needs resource R2, so P1 request for R2, but R2 is already allocated to P2.

    In the same way Process P2 to complete its execution needs R1, but R1 is already allocated to P1.

    both the processes can not release their resource until and unless they complete their execution. So both are waiting for another resources and they will wait forever. So this is a DEADLOCK Condition.

    In order for deadlock to occur, four conditions must be true.

    1. Mutual exclusion - Each resource is either currently allocated to exactly one process or it is available. (Two processes cannot simultaneously control the same resource or be in their critical section).
    2. Hold and Wait - processes currently holding resources can request new resources.
    3. No preemption - Once a process holds a resource, it cannot be taken away by another process or the kernel.
    4. Circular wait - Each process is waiting to obtain a resource which is held by another process.

    and all these condition are satisfied in above diagram.

    How to call a mysql stored procedure, with arguments, from command line?

    With quotes around the date:

    mysql> CALL insertEvent('2012.01.01 12:12:12');
    

    How to pause for specific amount of time? (Excel/VBA)

    Try this :

    Threading.thread.sleep(1000)
    

    JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

    Your for loop looks good.

    A possible while loop to accomplish the same thing:

    int sum = 0;
    int i = 1;
    while (i <= 100) {
        sum += i;
        i++;
    }
    System.out.println("The sum is " + sum);
    

    A possible do while loop to accomplish the same thing:

    int sum = 0;
    int i = 1;
    do {
        sum += i;
        i++;
    } while (i <= 100);
    System.out.println("The sum is " + sum);
    

    The difference between the while and the do while is that, with the do while, at least one iteration is sure to occur.

    HTML5 placeholder css padding

    I got the same issue.

    I fixed it by removing line-height from my input. Check if there is some lineheight which is causing the problem

    How to dynamically allocate memory space for a string and get that string from user?

    Read one character at a time (using getc(stdin)) and grow the string (realloc) as you go.

    Here's a function I wrote some time ago. Note it's intended only for text input.

    char *getln()
    {
        char *line = NULL, *tmp = NULL;
        size_t size = 0, index = 0;
        int ch = EOF;
    
        while (ch) {
            ch = getc(stdin);
    
            /* Check if we need to stop. */
            if (ch == EOF || ch == '\n')
                ch = 0;
    
            /* Check if we need to expand. */
            if (size <= index) {
                size += CHUNK;
                tmp = realloc(line, size);
                if (!tmp) {
                    free(line);
                    line = NULL;
                    break;
                }
                line = tmp;
            }
    
            /* Actually store the thing. */
            line[index++] = ch;
        }
    
        return line;
    }
    

    Bootstrap 3 modal vertical position center

    i have downloaded bootstrap3-dialog from bellow link and modified the open function in bootstrap-dialog.js

    https://github.com/nakupanda/bootstrap3-dialog

    Code

    open: function () {
                !this.isRealized() && this.realize();
                this.updateClosable();
                //Custom To Vertically centering Bootstrap 
                var $mymodal = this.getModal();
                $mymodal = $mymodal.append('<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td align="center" valign="middle" class="centerModal"></td></tr></table>');
                $mymodal = $mymodal.find(".modal-dialog").appendTo($mymodal.find(".centerModal"));
                //END
                this.getModal().modal('show');
                return this;
            }
    

    Css

    .centerModal .modal-header{
        text-align:left;
    }
    .centerModal .modal-body{
        text-align:left;
    } 
    

    How to pass in a react component into another react component to transclude the first component's content?

    const ParentComponent = (props) => {
      return(
        {props.childComponent}
        //...additional JSX...
      )
    }
    
    //import component
    import MyComponent from //...where ever
    
    //place in var
    const myComponent = <MyComponent />
    
    //pass as prop
    <ParentComponent childComponent={myComponent} />
    

    How do you connect localhost in the Android emulator?

    Thanks to author of this blog: https://bigdata-etl.com/solved-how-to-connect-from-android-emulator-to-application-on-localhost/

    Defining network security config in xml

    <network-security-config>
        <domain-config cleartextTrafficPermitted="true">
           <domain includeSubdomains="true">10.0.2.2</domain>
        </domain-config>
    </network-security-config>
    

    And setting it on AndroidManifest.xml

     <application
        android:networkSecurityConfig="@xml/network_security_config"
    </application>
    

    Solved issue for me!

    Please refer: https://developer.android.com/training/articles/security-config

    How add spaces between Slick carousel item

    Add

    centerPadding: '0'
    

    Slider settings will look like:

    $('.phase-slider-one').slick({
         centerMode: true,
         centerPadding: '0',
         responsive: [{breakpoint: 1024,},{breakpoint: 600,},{breakpoint: 480,}]
    });
    

    Thank you

    Difference between angle bracket < > and double quotes " " while including header files in C++?

    When you use angle brackets, the compiler searches for the file in the include path list. When you use double quotes, it first searches the current directory (i.e. the directory where the module being compiled is) and only then it'll search the include path list.

    So, by convention, you use the angle brackets for standard includes and the double quotes for everything else. This ensures that in the (not recommended) case in which you have a local header with the same name as a standard header, the right one will be chosen in each case.

    iPhone App Minus App Store?

    If you patch /Developer/Platforms/iPhoneOS.platform/Info.plist and then try to debug a application running on the device using a real development provisionen profile from Apple it will probably not work. Symptoms are weird error messages from com.apple.debugserver and that you can use any bundle identifier without getting a error when building in Xcode. The solution is to restore Info.plist.

    Dropping connected users in Oracle database

    If you use RAC then you need to use GV$* views instead V$*. Try to find your session by

    select * from gv$session where username = 'test';
    

    and then you can kill the session by

    alter system kill session 'sid, serial#, @inst_id' immediate;
    

    Start ssh-agent on login

    Please go through this article. You may find this very useful:

    http://mah.everybody.org/docs/ssh

    Just in case the above link vanishes some day, I am capturing the main piece of the solution below:

    This solution from Joseph M. Reagle by way of Daniel Starin:

    Add this following to your .bash_profile

    SSH_ENV="$HOME/.ssh/agent-environment"
    
    function start_agent {
        echo "Initialising new SSH agent..."
        /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
        echo succeeded
        chmod 600 "${SSH_ENV}"
        . "${SSH_ENV}" > /dev/null
        /usr/bin/ssh-add;
    }
    
    # Source SSH settings, if applicable
    
    if [ -f "${SSH_ENV}" ]; then
        . "${SSH_ENV}" > /dev/null
        #ps ${SSH_AGENT_PID} doesn't work under cywgin
        ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
            start_agent;
        }
    else
        start_agent;
    fi
    

    This version is especially nice since it will see if you've already started ssh-agent and, if it can't find it, will start it up and store the settings so that they'll be usable the next time you start up a shell.

    how to assign a block of html code to a javascript variable

    you can make a javascript object with key being name of the html snippet, and value being an array of html strings, that are joined together.

    var html = {
      top_crimes_template:
        [
          '<div class="top_crimes"><h3>Top Crimes</h3></div>',
          '<table class="crimes-table table table-responsive table-bordered">',
            '<tr>',
              '<th>',
                '<span class="list-heading">Crime:</span>',
              '</th>',
              '<th>',
                '<span id="last_crime_span"># Arrests</span>',
              '</th>',
            '</tr>',
          '</table>'
        ].join(""),
      top_teams_template:
        [
          '<div class="top_teams"><h3>Top Teams</h3></div>',
          '<table class="teams-table table table-responsive table-bordered">',
            '<tr>',
              '<th>',
                '<span class="list-heading">Team:</span>',
              '</th>',
              '<th>',
                '<span id="last_team_span"># Arrests</span>',
              '</th>',
            '</tr>',
          '</table>'
        ].join(""),
      top_players_template:
        [
          '<div class="top_players"><h3>Top Players</h3></div>',
          '<table class="players-table table table-responsive table-bordered">',
            '<tr>',
              '<th>',
                '<span class="list-heading">Players:</span>',
              '</th>',
              '<th>',
                '<span id="last_player_span"># Arrests</span>',
              '</th>',
            '</tr>',
          '</table>'
        ].join("")
    };
    

    How do you remove an invalid remote branch reference from Git?

    I had a similar problem. None of the answers helped. In my case, I had two removed remote repositories showing up permanently.

    My last idea was to remove all references to it by hand.

    Let's say the repository is called “Repo”. I did:

    find .git -name Repo 
    

    So, I deleted the corresponding files and directories from the .git folder (this folder could be found in your Rails app or on your computer https://stackoverflow.com/a/19538763/6638513).

    Then I did:

    grep Repo -r .git
    

    This found some text files in which I removed the corresponding lines. Now, everything seems to be fine.

    Usually, you should leave this job to git.

    OSError: [Errno 8] Exec format error

    Have you tried this?

    Out = subprocess.Popen('/usr/local/bin/script hostname = actual_server_name -p LONGLIST'.split(), shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 
    

    Edited per the apt comment from @J.F.Sebastian

    Python: Continuing to next iteration in outer loop

    I just did something like this. My solution for this was to replace the interior for loop with a list comprehension.

    for ii in range(200):
        done = any([op(ii, jj) for jj in range(200, 400)])
        ...block0...
        if done:
            continue
        ...block1...
    

    where op is some boolean operator acting on a combination of ii and jj. In my case, if any of the operations returned true, I was done.

    This is really not that different from breaking the code out into a function, but I thought that using the "any" operator to do a logical OR on a list of booleans and doing the logic all in one line was interesting. It also avoids the function call.

    Calling one Bash script from another Script passing it arguments with quotes and spaces

    I found following program works for me

    test1.sh 
    a=xxx
    test2.sh $a
    

    in test2.sh you use $1 to refer variable a in test1.sh

    echo $1

    The output would be xxx

    Check if any type of files exist in a directory using BATCH script

    For files in a directory, you can use things like:

    if exist *.csv echo "csv file found"
    

    or

    if not exist *.csv goto nofile
    

    Codeigniter : calling a method of one controller from other

    test.php Controller File :

    Class Test {
     function demo() {
      echo "Hello";
     }
    }
    

    test1.php Controller File :

    Class Test1 {
     function demo2() {
      require('test.php');
      $test = new Test();
      $test->demo();
     }
    }
    

    How do I remove an item from a stl vector with a certain value?

    std::remove does not actually erase the element from the container, but it does return the new end iterator which can be passed to container_type::erase to do the REAL removal of the extra elements that are now at the end of the container:

    std::vector<int> vec;
    // .. put in some values ..
    int int_to_remove = n;
    vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());
    

    How to fit a smooth curve to my data in R?

    the qplot() function in the ggplot2 package is very simple to use and provides an elegant solution that includes confidence bands. For instance,

    qplot(x,y, geom='smooth', span =0.5)
    

    produces enter image description here

    Skip download if files exist in wget?

    The -nc, --no-clobber option isn't the best solution as newer files will not be downloaded. One should use -N instead which will download and overwrite the file only if the server has a newer version, so the correct answer is:

    wget -N http://www.example.com/images/misc/pic.png
    

    Then running Wget with -N, with or without -r or -p, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file. -nc may not be specified at the same time as -N.

    -N, --timestamping: Turn on time-stamping.

    How do I determine whether my calculation of pi is accurate?

    Since I'm the current world record holder for the most digits of pi, I'll add my two cents:

    Unless you're actually setting a new world record, the common practice is just to verify the computed digits against the known values. So that's simple enough.

    In fact, I have a webpage that lists snippets of digits for the purpose of verifying computations against them: http://www.numberworld.org/digits/Pi/


    But when you get into world-record territory, there's nothing to compare against.

    Historically, the standard approach for verifying that computed digits are correct is to recompute the digits using a second algorithm. So if either computation goes bad, the digits at the end won't match.

    This does typically more than double the amount of time needed (since the second algorithm is usually slower). But it's the only way to verify the computed digits once you've wandered into the uncharted territory of never-before-computed digits and a new world record.


    Back in the days where supercomputers were setting the records, two different AGM algorithms were commonly used:

    These are both O(N log(N)^2) algorithms that were fairly easy to implement.

    However, nowadays, things are a bit different. In the last three world records, instead of performing two computations, we performed only one computation using the fastest known formula (Chudnovsky Formula):

    Enter image description here

    This algorithm is much harder to implement, but it is a lot faster than the AGM algorithms.

    Then we verify the binary digits using the BBP formulas for digit extraction.

    Enter image description here

    This formula allows you to compute arbitrary binary digits without computing all the digits before it. So it is used to verify the last few computed binary digits. Therefore it is much faster than a full computation.

    The advantage of this is:

    1. Only one expensive computation is needed.

    The disadvantage is:

    1. An implementation of the Bailey–Borwein–Plouffe (BBP) formula is needed.
    2. An additional step is needed to verify the radix conversion from binary to decimal.

    I've glossed over some details of why verifying the last few digits implies that all the digits are correct. But it is easy to see this since any computation error will propagate to the last digits.


    Now this last step (verifying the conversion) is actually fairly important. One of the previous world record holders actually called us out on this because, initially, I didn't give a sufficient description of how it worked.

    So I've pulled this snippet from my blog:

    N = # of decimal digits desired
    p = 64-bit prime number
    

    Enter image description here

    Compute A using base 10 arithmetic and B using binary arithmetic.

    Enter image description here

    If A = B, then with "extremely high probability", the conversion is correct.


    For further reading, see my blog post Pi - 5 Trillion Digits.

    Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

    Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014

    Just be sure to be using correct instance and connect each other

    Just pay attention in Stored procs must be recompiled

    Return the most recent record from ElasticSearch index

    Get the Last ID using by date (with out time stamp)

    Sample URL : http://localhost:9200/deal/dealsdetails/
    Method : POST

    Query :

    {
      "fields": ["_id"],
      "sort": [{
          "created_date": {
            "order": "desc"
          }
        },
        {
          "_score": {
            "order": "desc"
          }
        }
      ],
      "size": 1
    }
    

    result:

    {
      "took": 4,
      "timed_out": false,
      "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
      },
      "hits": {
        "total": 9,
        "max_score": null,
        "hits": [{
          "_index": "deal",
          "_type": "dealsdetails",
          "_id": "10",
          "_score": 1,
          "sort": [
            1478266145174,
            1
          ]
        }]
      }
    }
    

    Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

    This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:

    ' Get customer workbook...
    Dim customerBook As Workbook
    Dim filter As String
    Dim caption As String
    Dim customerFilename As String
    Dim customerWorkbook As Workbook
    Dim targetWorkbook As Workbook
    
    ' make weak assumption that active workbook is the target
    Set targetWorkbook = Application.ActiveWorkbook
    
    ' get the customer workbook
    filter = "Text files (*.xlsx),*.xlsx"
    caption = "Please Select an input file "
    customerFilename = Application.GetOpenFilename(filter, , caption)
    
    Set customerWorkbook = Application.Workbooks.Open(customerFilename)
    
    ' assume range is A1 - C10 in sheet1
    ' copy data from customer to target workbook
    Dim targetSheet As Worksheet
    Set targetSheet = targetWorkbook.Worksheets(1)
    Dim sourceSheet As Worksheet
    Set sourceSheet = customerWorkbook.Worksheets(1)
    
    targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value
    
    ' Close customer workbook
    customerWorkbook.Close
    

    What is a "method" in Python?

    To understand methods you must first think in terms of object oriented programming: Let's take a car as a a class. All cars have things in common and things that make them unique, for example all cars have 4 wheels, doors, a steering wheel.... but Your individual car (Lets call it, my_toyota) is red, goes from 0-60 in 5.6s Further the car is currently located at my house, the doors are locked, the trunk is empty... All those are properties of the instance of my_toyota. your_honda might be on the road, trunk full of groceries ...

    However there are things you can do with the car. You can drive it, you can open the door, you can load it. Those things you can do with a car are methods of the car, and they change a properties of the specific instance.

    as pseudo code you would do:

    my_toyota.drive(shop)
    

    to change the location from my home to the shop or

    my_toyota.load([milk, butter, bread]
    

    by this the trunk is now loaded with [milk, butter, bread].

    As such a method is practically a function that acts as part of the object:

    class Car(vehicle)
        n_wheels = 4
    
        load(self, stuff):
        '''this is a method, to load stuff into the trunk of the car'''
            self.open_trunk
            self.trunk.append(stuff)
            self.close_trunk
    

    the code then would be:

    my_toyota = Car(red)
    my_shopping = [milk, butter, bread]
    my_toyota.load(my_shopping)
    

    Make element fixed on scroll

    Plain Javascript Solution (DEMO) :

    <br/><br/><br/><br/><br/><br/><br/>
    <div>
      <div id="myyy_bar" style="background:red;"> Here is window </div>
    </div>
    <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
    
    
    <script type="text/javascript">
    var myyElement = document.getElementById("myyy_bar"); 
    var EnableConsoleLOGS = true;           //to check the results in Browser's Inspector(Console), whenever you are scrolling
    // ==============================================
    
    
    
    window.addEventListener('scroll', function (evt) {
        var Positionsss =  GetTopLeft ();  
        if (EnableConsoleLOGS) { console.log(Positionsss); }
        if (Positionsss.toppp  > 70)    { myyElement.style.position="relative"; myyElement.style.top = "0px";  myyElement.style.right = "auto"; }
        else                            { myyElement.style.position="fixed";    myyElement.style.top = "100px";         myyElement.style.right = "0px"; }
    });
    
    
    
    function GetOffset (object, offset) {
        if (!object) return;
        offset.x += object.offsetLeft;       offset.y += object.offsetTop;
        GetOffset (object.offsetParent, offset);
    }
    function GetScrolled (object, scrolled) {
        if (!object) return;
        scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
        if (object.tagName.toLowerCase () != "html") {          GetScrolled (object.parentNode, scrolled);        }
    }
    
    function GetTopLeft () {
        var offset = {x : 0, y : 0};        GetOffset (myyElement.parentNode, offset);
        var scrolled = {x : 0, y : 0};      GetScrolled (myyElement.parentNode.parentNode, scrolled);
        var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
        return {lefttt: posX , toppp: posY };
    }
    // ==============================================
    </script>
    

    How to find where gem files are installed

    You can trick gem open into displaying the gem path:

    VISUAL=echo gem open gem-name
    

    Example:

    VISUAL=echo gem open rails
    => /usr/local/opt/asdf/installs/ruby/2.4.3/lib/ruby/gems/2.4.0/gems/rails-5.1.4
    

    It just works, and no third party gem is necessary.

    Get JSONArray without array name?

    Here is a solution under 19API lvl:

    • First of all. Make a Gson obj. --> Gson gson = new Gson();

    • Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)

    • The last step to get JsonArray...

    YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);

    For vs. while in C programming?

    They are pretty much same except for do-while loop. The for loop is good when you have a counter kind of variable. It makes it obvious. while loop makes sense in cases where a flag is being checked as show below :

    while (!done) {
       if (some condtion) 
          done = true;
    }
    

    File size exceeds configured limit (2560000), code insight features not available

    Instructions for changing this settings in latest Jetbrains products

    Editing product64.vmoptions didnt worked for me, but editing idea.properties worked ok. Also in order to be able to work with large files you may need to change values for in product64.vmoptions / product.vmoptions for -Xms and -Xmx

    Use success() or complete() in AJAX call

    "complete" executes when the ajax call is finished. "success" executes when the ajax call finishes with a successful response code.

    SCRIPT5: Access is denied in IE9 on xmlhttprequest

    Probably you are requesting for an external resource, this case IE needs the XDomain object. See the sample code below for how to make ajax request for all browsers with cross domains:

    Tork.post = function (url,data,callBack,callBackParameter){
        if (url.indexOf("?")>0){
            data = url.substring(url.indexOf("?")+1)+"&"+ data;
            url = url.substring(0,url.indexOf("?"));
        }
        data += "&randomNumberG=" + Math.random() + (Tork.debug?"&debug=1":"");
        var xmlhttp;
        if (window.XDomainRequest)
        {
            xmlhttp=new XDomainRequest();
            xmlhttp.onload = function(){callBack(xmlhttp.responseText)};
        }
        else if (window.XMLHttpRequest)
            xmlhttp=new XMLHttpRequest();
        else
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                Tork.msg("Response:"+xmlhttp.responseText);
                callBack(xmlhttp.responseText,callBackParameter);
                Tork.showLoadingScreen(false);
            }
        }
        xmlhttp.open("POST",Tork.baseURL+url,true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(data);
    }
    

    Richtextbox wpf binding

    Most of my needs were satisfied by this answer https://stackoverflow.com/a/2989277/3001007 by krzysztof. But one issue with that code (i faced was), the binding won't work with multiple controls. So I changed _recursionProtection with a Guid based implementation. So it's working for Multiple controls in same window as well.

     public class RichTextBoxHelper : DependencyObject
        {
            private static List<Guid> _recursionProtection = new List<Guid>();
    
            public static string GetDocumentXaml(DependencyObject obj)
            {
                return (string)obj.GetValue(DocumentXamlProperty);
            }
    
            public static void SetDocumentXaml(DependencyObject obj, string value)
            {
                var fw1 = (FrameworkElement)obj;
                if (fw1.Tag == null || (Guid)fw1.Tag == Guid.Empty)
                    fw1.Tag = Guid.NewGuid();
                _recursionProtection.Add((Guid)fw1.Tag);
                obj.SetValue(DocumentXamlProperty, value);
                _recursionProtection.Remove((Guid)fw1.Tag);
            }
    
            public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(
                "DocumentXaml",
                typeof(string),
                typeof(RichTextBoxHelper),
                new FrameworkPropertyMetadata(
                    "",
                    FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                    (obj, e) =>
                    {
                        var richTextBox = (RichTextBox)obj;
                        if (richTextBox.Tag != null && _recursionProtection.Contains((Guid)richTextBox.Tag))
                            return;
    
    
                        // Parse the XAML to a document (or use XamlReader.Parse())
    
                        try
                        {
                            string docXaml = GetDocumentXaml(richTextBox);
                            var stream = new MemoryStream(Encoding.UTF8.GetBytes(docXaml));
                            FlowDocument doc;
                            if (!string.IsNullOrEmpty(docXaml))
                            {
                                doc = (FlowDocument)XamlReader.Load(stream);
                            }
                            else
                            {
                                doc = new FlowDocument();
                            }
    
                            // Set the document
                            richTextBox.Document = doc;
                        }
                        catch (Exception)
                        {
                            richTextBox.Document = new FlowDocument();
                        }
    
                        // When the document changes update the source
                        richTextBox.TextChanged += (obj2, e2) =>
                            {
                                RichTextBox richTextBox2 = obj2 as RichTextBox;
                                if (richTextBox2 != null)
                                {
                                    SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));
                                }
                            };
                    }
                )
            );
        }
    

    For completeness sake, let me add few more lines from original answer https://stackoverflow.com/a/2641774/3001007 by ray-burns. This is how to use the helper.

    <RichTextBox local:RichTextBoxHelper.DocumentXaml="{Binding Autobiography}" />
    

    Make the image go behind the text and keep it in center using CSS

    Try this code:

    body {z-index:0}
    img.center {z-index:-1; margin-left:auto; margin-right:auto}
    

    Setting the left & right margins to auto should center your image.

    removeEventListener on anonymous functions in JavaScript

    A not so anonymous option

    element.funky = function() {
        console.log("Click!");
    };
    element.funky.type = "click";
    element.funky.capt = false;
    element.addEventListener(element.funky.type, element.funky, element.funky.capt);
    // blah blah blah
    element.removeEventListener(element.funky.type, element.funky, element.funky.capt);
    

    Since receiving feedback from Andy (quite right, but as with many examples, I wished to show a contextual expansion of the idea), here's a less complicated exposition:

    <script id="konami" type="text/javascript" async>
        var konami = {
            ptrn: "38,38,40,40,37,39,37,39,66,65",
            kl: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
        };
        document.body.addEventListener( "keyup", function knm ( evt ) {
            konami.kl = konami.kl.slice( -9 );
            konami.kl.push( evt.keyCode );
            if ( konami.ptrn === konami.kl.join() ) {
                evt.target.removeEventListener( "keyup", knm, false );
    
                /* Although at this point we wish to remove a listener
                   we could easily have had multiple "keyup" listeners
                   each triggering different functions, so we MUST
                   say which function we no longer wish to trigger
                   rather than which listener we wish to remove.
    
                   Normal scoping will apply to where we can mention this function
                   and thus, where we can remove the listener set to trigger it. */
    
                document.body.classList.add( "konami" );
            }
        }, false );
        document.body.removeChild( document.getElementById( "konami" ) );
    </script>
    

    This allows an effectively anonymous function structure, avoids the use of the practically deprecated callee, and allows easy removal.

    Incidentally: The removal of the script element immediately after setting the listener is a cute trick for hiding code one would prefer wasn't starkly obvious to prying eyes (would spoil the surprise ;-)

    So the method (more simply) is:

    element.addEventListener( action, function name () {
        doSomething();
        element.removeEventListener( action, name, capture );
    }, capture );
    

    How to set connection timeout with OkHttp

    Like so:

    //New Request
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
    final OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(logging)
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .build();
    

    How to generate a random string in Ruby

    My 2 cents:

      def token(length=16)
        chars = [*('A'..'Z'), *('a'..'z'), *(0..9)]
        (0..length).map {chars.sample}.join
      end
    

    SQL Server 2008: How to query all databases sizes?

    sometimes SECURITY issues prevent from asking for all the db's and you need to query one by one with the db prefix, for those cases i created this dynamic query

    go
    declare @Results table ([Name] nvarchar(max), [DataFileSizeMB] int, [LogFileSizeMB] int);
    
    declare @QaQuery nvarchar(max)
    declare @name nvarchar(max)
    
    declare MY_CURSOR cursor 
      local static read_only forward_only
    for 
    select name from master.dbo.sysdatabases where name not in ('master', 'tempdb', 'model', 'msdb', 'rdsadmin');
    
    open MY_CURSOR
    fetch next from MY_CURSOR into @name
    while @@FETCH_STATUS = 0
    begin 
        if(len(@name)>0)
        begin
            print @name + ' Column Exist'
            set @QaQuery = N'select 
                                '''+@name+''' as Name
                                ,sum(case when type = 0 then size else 0 end) as DataFileSizeMB
                                ,sum(case when type = 1 then size else 0 end) as LogFileSizeMB
                            from ['+@name+'].sys.database_files
                            group by replace(name, ''_log'', '''')';
    
            insert @Results exec sp_executesql @QaQuery;
        end
      fetch next from MY_CURSOR into @name
    end
    close MY_CURSOR
    deallocate MY_CURSOR
    
    select * from @Results order by DataFileSizeMB desc
    go
    

    Entity Framework Query for inner join

    In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:

    db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);
    

    If you don't, unless there's some Join() override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):

    db.Services.Join(db.ServiceAssignments, 
         s => s.Id,
         sa => sa.ServiceId, 
         (s, sa) => new {service = s, asgnmt = sa})
    .Where(ssa => ssa.asgnmt.LocationId == 1)
    .Select(ssa => ssa.service);
    

    Command to close an application of console?

    return; will exit a method in C#.

    See code snippet below

    using System;
    
    namespace Exercise_strings
    {
        class Program
        {
            static void Main(string[] args)
            {
               Console.WriteLine("Input string separated by -");
    
                var stringInput = Console.ReadLine();
    
                if (string.IsNullOrWhiteSpace(stringInput))
                {
                    Console.WriteLine("Nothing entered");
                    return;
                }
    }
    

    So in this case if a user enters a null string or whitespace, the use of the return method terminates the Main method elegantly.

    Check if current directory is a Git repository

    You can use:

    git rev-parse --is-inside-work-tree
    

    Which will print 'true' if you are in a git repos working tree.

    Note that it still returns output to STDERR if you are outside of a git repo (and does not print 'false').

    Taken from this answer: https://stackoverflow.com/a/2044714/12983

    scale fit mobile web content using viewport meta tag

    For Android there is the addition of target-density tag.

    target-densitydpi=device-dpi
    

    So, the code would look like

    <meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />
    

    Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.

    Correct way to push into state array

    This Code work for me :

    fetch('http://localhost:8080')
      .then(response => response.json())
      .then(json => {
      this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
    })
    

    Asus Zenfone 5 not detected by computer

    This should solve your problem.

    1. Download the Asus USB Driver for Zenfone 5 here
    2. Extract the rar file
    3. Go to your Device Manager if you're on Windows (Make sure you've connected your phone to your computer)
    4. Choose update driver then browse the path to where the extracted rar file is. It should prompt something on your phone, just accept it
    5. Try it on your IDE, just select run configurations

    How to monitor Java memory usage?

    As has been suggested, try VisualVM to get a basic view.

    You can also use Eclipse MAT, to do a more detailed memory analysis.

    It's ok to do a System.gc() as long as you dont depend on it, for the correctness of your program.

    how to add json library

    AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.

    Vue.js unknown custom element

    You forgot about the components section in your Vue initialization. So Vue actually doesn't know about your component.

    Change it to:

    var myTask = Vue.component('my-task', {
     template: '#task-template',
     data: function() {
      return this.tasks; //Notice: in components data should return an object. For example "return { someProp: 1 }"
     },
     props: ['task']
    });
    
    new Vue({
     el: '#app',
     data: {
      tasks: [{
        name: "task 1",
        completed: false
       },
       {
        name: "task 2",
        completed: false
       },
       {
        name: "task 3",
        completed: true
       }
      ]
     },
     components: {
      myTask: myTask
     },
     methods: {
    
     },
     computed: {
    
     },
     ready: function() {
    
     }
    
    });
    

    And here is jsBin, where all seems to works correctly: http://jsbin.com/lahawepube/edit?html,js,output

    UPDATE

    Sometimes you want your components to be globally visible to other components.

    In this case you need to register your components in this way, before your Vue initialization or export (in case if you want to register component from the other component)

    Vue.component('exampleComponent', require('./components/ExampleComponent.vue')); //component name should be in camel-case
    

    After you can add your component inside your vue el:

    <example-component></example-component>
    

    Resizing an iframe based on content

    Here's a jQuery approach that adds the info in json via the src attribute of the iframe. Here's a demo, resize and scroll this window.. the resulting url with json looks like this... http://fiddle.jshell.net/zippyskippy/RJN3G/show/#{docHeight:5124,windowHeight:1019,scrollHeight:571}#

    Here's the source code fiddle http://jsfiddle.net/zippyskippy/RJN3G/

    function updateLocation(){
    
        var loc = window.location.href;
        window.location.href = loc.replace(/#{.*}#/,"") 
            + "#{docHeight:"+$(document).height() 
            + ",windowHeight:"+$(window).height()
            + ",scrollHeight:"+$(window).scrollTop()
            +"}#";
    
    };
    
    //setInterval(updateLocation,500);
    
    $(window).resize(updateLocation);
    $(window).scroll(updateLocation);
    

    Use css gradient over background image

    Ok, I solved it by adding the url for the background image at the end of the line.

    Here's my working code:

    _x000D_
    _x000D_
    .css {_x000D_
      background: -moz-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
      background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0)), color-stop(59%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0.65))), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
      background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
      background: -o-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
      background: -ms-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
      background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
      height: 200px;_x000D_
    _x000D_
    }
    _x000D_
    <div class="css"></div>
    _x000D_
    _x000D_
    _x000D_

    Find methods calls in Eclipse project

    You can also search for specific methods. For e.g. If you want to search for isEmpty() method of the string class you have to got to - Search -> Java -> type java.lang.String.isEmpty() and in the 'Search For' option use Method.

    You can then select the scope that you require.

    How do you import a large MS SQL .sql file?

    I have encountered the same problem and invested a whole day to find the way out but this is resolved by making the copy of .sql file and change the extension to .txt file and open the .txt file into chrome browser. I have seen the magic and file is opened in a browser.

    Thanks and Best Regards,

    How to get URI from an asset File?

    Try this out, it works:

    InputStream in_s = 
        getClass().getClassLoader().getResourceAsStream("TopBrands.xml");
    

    If you get a Null Value Exception, try this (with class TopBrandData):

    InputStream in_s1 =
        TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");
    

    Traversing text in Insert mode

    You could use imap to map any key in insert mode to one of the cursor keys. Like so:

    imap h <Left>
    

    Now h works like in normal mode, moving the cursor. (Mapping h in this way is obviously a bad choice)

    Having said that I do not think the standard way of moving around in text using VIM is "not productive". There are lots of very powerful ways of traversing the text in normal mode (like using w and b, or / and ?, or f and F, etc.)

    node.js + mysql connection pooling

    You should avoid using pool.getConnection() if you can. If you call pool.getConnection(), you must call connection.release() when you are done using the connection. Otherwise, your application will get stuck waiting forever for connections to be returned to the pool once you hit the connection limit.

    For simple queries, you can use pool.query(). This shorthand will automatically call connection.release() for you—even in error conditions.

    function doSomething(cb) {
      pool.query('SELECT 2*2 "value"', (ex, rows) => {
        if (ex) {
          cb(ex);
        } else {
          cb(null, rows[0].value);
        }
      });
    }
    

    However, in some cases you must use pool.getConnection(). These cases include:

    • Making multiple queries within a transaction.
    • Sharing data objects such as temporary tables between subsequent queries.

    If you must use pool.getConnection(), ensure you call connection.release() using a pattern similar to below:

    function doSomething(cb) {
      pool.getConnection((ex, connection) => {
        if (ex) {
          cb(ex);
        } else {
          // Ensure that any call to cb releases the connection
          // by wrapping it.
          cb = (cb => {
            return function () {
              connection.release();
              cb.apply(this, arguments);
            };
          })(cb);
          connection.beginTransaction(ex => {
            if (ex) {
              cb(ex);
            } else {
              connection.query('INSERT INTO table1 ("value") VALUES (\'my value\');', ex => {
                if (ex) {
                  cb(ex);
                } else {
                  connection.query('INSERT INTO table2 ("value") VALUES (\'my other value\')', ex => {
                    if (ex) {
                      cb(ex);
                    } else {
                      connection.commit(ex => {
                        cb(ex);
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    }
    

    I personally prefer to use Promises and the useAsync() pattern. This pattern combined with async/await makes it a lot harder to accidentally forget to release() the connection because it turns your lexical scoping into an automatic call to .release():

    async function usePooledConnectionAsync(actionAsync) {
      const connection = await new Promise((resolve, reject) => {
        pool.getConnection((ex, connection) => {
          if (ex) {
            reject(ex);
          } else {
            resolve(connection);
          }
        });
      });
      try {
        return await actionAsync(connection);
      } finally {
        connection.release();
      }
    }
    
    async function doSomethingElse() {
      // Usage example:
      const result = await usePooledConnectionAsync(async connection => {
        const rows = await new Promise((resolve, reject) => {
          connection.query('SELECT 2*4 "value"', (ex, rows) => {
            if (ex) {
              reject(ex);
            } else {
              resolve(rows);
            }
          });
        });
        return rows[0].value;
      });
      console.log(`result=${result}`);
    }
    

    How to make a HTML Page in A4 paper size page(s)?

    It would be fairly easy to force the web browser to display the page with the same pixel dimensions as A4. However, there may be a few quirks when things are rendered.

    Assuming your monitors display 72 dpi, you could add something like this:

    <!DOCTYPE html>
    <html>
      <head>
        <style>
        body {
            height: 842px;
            width: 595px;
            /* to centre page on screen*/
            margin-left: auto;
            margin-right: auto;
        }
        </style>
      </head>
      <body>
      </body>
    </html>
    

    See line breaks and carriage returns in editor

    Just to clarify why :set list won't show CR's as ^M without e ++ff=unix and why :set list has nothing to do with ^M's.

    Internally when Vim reads a file into its buffer, it replaces all line-ending characters with its own representation (let's call it $'s). To determine what characters should be removed, it firstly detects in what format line endings are stored in a file. If there are only CRLF '\r\n' or only CR '\r' or only LF '\n' line-ending characters, then the 'fileformat' is set to dos, mac and unix respectively.

    When list option is set, Vim displays $ character when the line break occurred no matter what fileformat option has been detected. It uses its own internal representation of line-breaks and that's what it displays.

    Now when you write buffer to the disc, Vim inserts line-ending characters according to what fileformat options has been detected, essentially converting all those internal $'s with appropriate characters. If the fileformat happened to be unix then it will simply write \n in place of its internal line-break.

    The trick is to force Vim to read a dos encoded file as unix one. The net effect is that it will remove all \n's leaving \r's untouched and display them as ^M's in your buffer. Setting :set list will additionally show internal line-endings as $. After all, you see ^M$ in place of dos encoded line-breaks.

    Also notice that :set list has nothing to do with showing ^M's. You can check it by yourself (make sure you have disabled list option first) by inserting single CR using CTRL-V followed by Enter in insert mode. After writing buffer to disc and opening it again you will see ^M despite list option being set to 0.

    You can find more about file formats on http://vim.wikia.com/wiki/File_format or by typing:help 'fileformat' in Vim.

    How to check if a function exists on a SQL database

    I've found you can use a very non verbose and straightforward approach to checking for the existence various SQL Server objects this way:

    IF OBJECTPROPERTY (object_id('schemaname.scalarfuncname'), 'IsScalarFunction') = 1
    IF OBJECTPROPERTY (object_id('schemaname.tablefuncname'), 'IsTableFunction') = 1
    IF OBJECTPROPERTY (object_id('schemaname.procname'), 'IsProcedure') = 1
    

    This is based on the OBJECTPROPERTY function which is available in SQL 2005+. The MSDN article can be found here.

    The OBJECTPROPERTY function uses the following signature:

    OBJECTPROPERTY ( id , property ) 
    

    You pass a literal value into the property parameter, designating the type of object you are looking for. There's a massive list of values you can supply.

    Pandas Split Dataframe into two Dataframes at a specific row

    iloc

    df1 = datasX.iloc[:, :72]
    df2 = datasX.iloc[:, 72:]
    

    (iloc docs)

    Getting the name of a variable as a string

    Many of the answers return just one variable name. But that won't work well if more than one variable have the same value. Here's a variation of Amr Sharaki's answer which returns multiple results if more variables have the same value.

    def getVariableNames(variable):
        results = []
        globalVariables=globals().copy()
        for globalVariable in globalVariables:
            if id(variable) == id(globalVariables[globalVariable]):
                results.append(globalVariable)
        return results
    
    a = 1
    b = 1
    getVariableNames(a)
    # ['a', 'b']
    

    How to use ng-if to test if a variable is defined

    I edited your plunker to include ABOS's solution.

    <body ng-controller="MainCtrl">
        <ul ng-repeat='item in items'>
          <li ng-if='item.color'>The color is {{item.color}}</li>
          <li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
        </ul>
      </body>
    

    plunkerFork

    embedding image in html email

    For those who couldnt get one of these solutions working: Send inline image in email Following the steps laid out in the solution offered by @T30 i was able to get my inline image to display without being blocked by outlook (previous methods it was blocked). If you are using exchange like we are then also when doing:

    service = new ExchangeService(ExchangeVersion);
    service.AutodiscoverUrl("[email protected]");
    SmtpClient smtp = new SmtpClient(service.Url.Host);
    

    you will need to pass it your exchange service url host. Other than that following this solution should allow you to easily send embedded imgages.

    How do you get the current page number of a ViewPager for Android?

    If you only want the position, vp.getCurrentItem() will give it to you, no need to apply the onPageChangeListener() for that purpose alone.

    How to Logout of an Application Where I Used OAuth2 To Login With Google?

    this code will work to sign out

        <script>
          function signOut() 
          {
            var auth2 = gapi.auth2.getAuthInstance();
            auth2.signOut().then(function () {   
            console.log('User signed out.');   
            auth2.disconnect();   
          }); 
            auth2.disconnect();
          } 
        </script>
    

    In Tkinter is there any way to make a widget not visible?

    import tkinter as tk
    ...
    x = tk.Label(text='Hello', visible=True)
    def visiblelabel(lb, visible):
        lb.config(visible=visible)
    visiblelabel(x, False)  # Hide
    visiblelabel(x, True)  # Show
    

    P.S. config can change any attribute:

    x.config(text='Hello')  # Text: Hello
    x.config(text='Bye', font=('Arial', 20, 'bold'))  # Text: Bye, Font: Arial Bold 20
    x.config(bg='red', fg='white')  # Background: red, Foreground: white
    

    It's a bypass of StringVar, IntVar etc.

    How to search a string in a single column (A) in excel using VBA

    Below are two methods that are superior to looping. Both handle a "no-find" case.

    1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
    2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

      Sub Method1()
      Dim strSearch As String
      Dim strOut As String
      Dim bFailed As Boolean
      
      strSearch = "trees"
      
      On Error Resume Next
      strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
      If Err.Number <> 0 Then bFailed = True
      On Error GoTo 0
      
      If Not bFailed Then
      MsgBox "corresponding value is " & vbNewLine & strOut
      Else
      MsgBox strSearch & " not found"
      End If
      End Sub
      
      Sub Method2()
          Dim rng1 As Range
          Dim strSearch As String
          strSearch = "trees"
          Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
          If Not rng1 Is Nothing Then
              MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
          Else
              MsgBox strSearch & " not found"
          End If
      End Sub
      

    How to add an Access-Control-Allow-Origin header

    According to the official docs, browsers do not like it when you use the

    Access-Control-Allow-Origin: "*"
    

    header if you're also using the

    Access-Control-Allow-Credentials: "true"
    

    header. Instead, they want you to allow their origin specifically. If you still want to allow all origins, you can do some simple Apache magic to get it to work (make sure you have mod_headers enabled):

    Header set Access-Control-Allow-Origin "%{HTTP_ORIGIN}e" env=HTTP_ORIGIN
    

    Browsers are required to send the Origin header on all cross-domain requests. The docs specifically state that you need to echo this header back in the Access-Control-Allow-Origin header if you are accepting/planning on accepting the request. That's what this Header directive is doing.

    Reactjs - setting inline styles correctly

    You could also try setting style inline without using a variable, like so:

    style={{"height" : "100%"}} or,

    for multiple attributes: style={{"height" : "100%", "width" : "50%"}}

    How to get your Netbeans project into Eclipse

    In Eclipse:

    File>Import>General>Existing projects in Workspace

    Browse until get the netbeans project folder > Finish

    Proper use of 'yield return'

    I know this is an old question, but I'd like to offer one example of how the yield keyword can be creatively used. I have really benefited from this technique. Hopefully this will be of assistance to anyone else who stumbles upon this question.

    Note: Don't think about the yield keyword as merely being another way to build a collection. A big part of the power of yield comes in the fact that execution is paused in your method or property until the calling code iterates over the next value. Here's my example:

    Using the yield keyword (alongside Rob Eisenburg's Caliburn.Micro coroutines implementation) allows me to express an asynchronous call to a web service like this:

    public IEnumerable<IResult> HandleButtonClick() {
        yield return Show.Busy();
    
        var loginCall = new LoginResult(wsClient, Username, Password);
        yield return loginCall;
        this.IsLoggedIn = loginCall.Success;
    
        yield return Show.NotBusy();
    }
    

    What this will do is turn my BusyIndicator on, call the Login method on my web service, set my IsLoggedIn flag to the return value, and then turn the BusyIndicator back off.

    Here's how this works: IResult has an Execute method and a Completed event. Caliburn.Micro grabs the IEnumerator from the call to HandleButtonClick() and passes it into a Coroutine.BeginExecute method. The BeginExecute method starts iterating through the IResults. When the first IResult is returned, execution is paused inside HandleButtonClick(), and BeginExecute() attaches an event handler to the Completed event and calls Execute(). IResult.Execute() can perform either a synchronous or an asynchronous task and fires the Completed event when it's done.

    LoginResult looks something like this:

    public LoginResult : IResult {
        // Constructor to set private members...
    
        public void Execute(ActionExecutionContext context) {
            wsClient.LoginCompleted += (sender, e) => {
                this.Success = e.Result;
                Completed(this, new ResultCompletionEventArgs());
            };
            wsClient.Login(username, password);
        }
    
        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
        public bool Success { get; private set; }
    }
    

    It may help to set up something like this and step through the execution to watch what's going on.

    Hope this helps someone out! I've really enjoyed exploring the different ways yield can be used.

    Seeding the random number generator in Javascript

    For a number between 0 and 100.

    Number.parseInt(Math.floor(Math.random() * 100))
    

    When to use %r instead of %s in Python?

    Use the %r for debugging, since it displays the "raw" data of the variable, but the others are used for displaying to users.

    That's how %r formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging. Here \n used to display to users doesn't work. %r shows the representation if the raw data of the variable.

    months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
    print "Here are the months: %r" % months
    

    Output:

    Here are the months: '\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'
    

    Check this example from Learn Python the Hard Way.

    PHP new line break in emails

    When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is
    . so easy way to do this job is replacing all the "\n" with "
    ". so the code should be

    str_replace("\n","<br/>",$str);
    

    after adding this code you wont have to use pre tag for all the output oparation.

    copyed this ans from this website :

    Convert an ISO date to the date format yyyy-mm-dd in JavaScript

    This will output the date in YYYY-MM-DD format:

    let date = new Date();
    date = date.toISOString().slice(0,10);
    

    matplotlib set yaxis label size

    If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

    If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

    Get skin path in Magento?

    To get that file use the below code.

    include(Mage::getBaseDir('skin').'myfunc.php');
    

    But it is not a correct way. To add your custom functions you can use the below file.

    app/code/core/Mage/core/functions.php
    

    Kindly avoid to use the PHP function under skin dir.

    How to allow remote access to my WAMP server for Mobile(Android)

    I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

    If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

    If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

    See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

    Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

    If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

    To eliminate possible causes of the issue for now set your config file to

    <Directory />
        Options FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
        <RequireAll>
            Require all granted
        </RequireAll>
    </Directory>
    

    As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

    Config file that fixed the problem:

    https://gist.github.com/samvaughton/6790739

    Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

    Laravel 4 Eloquent Query Using WHERE with OR AND OR?

    Make use of Parameter Grouping (Laravel 4.2). For your example, it'd be something like this:

    Model::where(function ($query) {
        $query->where('a', '=', 1)
              ->orWhere('b', '=', 1);
    })->where(function ($query) {
        $query->where('c', '=', 1)
              ->orWhere('d', '=', 1);
    });
    

    Shorten string without cutting words in JavaScript

    Lodash has a function specifically written for this: _.truncate

    const truncate = _.truncate
    const str = 'The quick brown fox jumps over the lazy dog'
    
    truncate(str, {
      length: 30, // maximum 30 characters
      separator: /,?\.* +/ // separate by spaces, including preceding commas and periods
    })
    
    // 'The quick brown fox jumps...'
    

    Create nice column output in python

    Transposing the columns like that is a job for zip:

    >>> a = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
    >>> list(zip(*a))
    [('a', 'aaaaaaaaaa', 'a'), ('b', 'b', 'bbbbbbbbbb'), ('c', 'c', 'c')]
    

    To find the required length of each column, you can use max:

    >>> trans_a = zip(*a)
    >>> [max(len(c) for c in b) for b in trans_a]
    [10, 10, 1]
    

    Which you can use, with suitable padding, to construct strings to pass to print:

    >>> col_lenghts = [max(len(c) for c in b) for b in trans_a]
    >>> padding = ' ' # You might want more
    >>> padding.join(s.ljust(l) for s,l in zip(a[0], col_lenghts))
    'a          b          c'
    

    Different names of JSON property during serialization and deserialization

    You can use @jsonAlias which got introduced in jackson 2.9.0

    Example:

    public class Info {
      @JsonAlias({ "red" })
      public String r;
    }
    

    This uses r during serialization, but allows red as an alias during deserialization. This still allows r to be deserialized as well, though.

    Convert from MySQL datetime to another format with PHP

    To correctly format a DateTime object in PHP for storing in MySQL use the standardised format that MySQL uses, which is ISO 8601.

    PHP has had this format stored as a constant since version 5.1.1, and I highly recommend using it rather than manually typing the string each time.

    $dtNow = new DateTime();
    $mysqlDateTime = $dtNow->format(DateTime::ISO8601);
    

    This, and a list of other PHP DateTime constants are available at http://php.net/manual/en/class.datetime.php#datetime.constants.types

    How do I compare two strings in python?

    You can use simple loops to check two strings are equal. .But ideally you can use something like return s1==s2

    s1 = 'hello'
    s2 = 'hello'
    
    a = []
    for ele in s1:
        a.append(ele)
    for i in range(len(s2)):
        if a[i]==s2[i]:
            a.pop()
    if len(a)>0:
        return False
    else:
        return True
    

    Manually adding a Userscript to Google Chrome

    The best thing to do is to install the Tampermonkey extension.

    This will allow you to easily install Greasemonkey scripts, and to easily manage them. Also it makes it easier to install userscripts directly from sites like OpenUserJS, MonkeyGuts, etc.

    Finally, it unlocks most all of the GM functionality that you don't get by installing a GM script directly with Chrome. That is, more of what GM on Firefox can do, is available with Tampermonkey.


    But, if you really want to install a GM script directly, it's easy a right pain on Chrome these days...

    Chrome After about August, 2014:

    You can still drag a file to the extensions page and it will work... Until you restart Chrome. Then it will be permanently disabled. See Continuing to "protect" Chrome users from malicious extensions for more information. Again, Tampermonkey is the smart way to go. (Or switch browsers altogether to Opera or Firefox.)

    Chrome 21+ :

    Chrome is changing the way extensions are installed. Userscripts are pared-down extensions on Chrome but. Starting in Chrome 21, link-click behavior is disabled for userscripts. To install a user script, drag the **.user.js* file into the Extensions page (chrome://extensions in the address input).

    Older Chrome versions:

    Merely drag your **.user.js* files into any Chrome window. Or click on any Greasemonkey script-link.

    You'll get an installation warning:
    Initial warning

    Click Continue.


    You'll get a confirmation dialog:
    confirmation dialog

    Click Add.


    Notes:

    1. Scripts installed this way have limitations compared to a Greasemonkey (Firefox) script or a Tampermonkey script. See Cross-browser user-scripting, Chrome section.

    Controlling the Script and name:

    By default, Chrome installs scripts in the Extensions folder1, full of cryptic names and version numbers. And, if you try to manually add a script under this folder tree, it will be wiped the next time Chrome restarts.

    To control the directories and filenames to something more meaningful, you can:

    1. Create a directory that's convenient to you, and not where Chrome normally looks for extensions. For example, Create: C:\MyChromeScripts\.

    2. For each script create its own subdirectory. For example, HelloWorld.

    3. In that subdirectory, create or copy the script file. For example, Save this question's code as: HelloWorld.user.js.

    4. You must also create a manifest file in that subdirectory, it must be named: manifest.json.

      For our example, it should contain:

      {
          "manifest_version": 2,
          "content_scripts": [ {
              "exclude_globs":    [  ],
              "include_globs":    [ "*" ],
              "js":               [ "HelloWorld.user.js" ],
              "matches":          [   "https://stackoverflow.com/*",
                                      "https://stackoverflow.com/*"
                                  ],
              "run_at": "document_end"
          } ],
          "converted_from_user_script": true,
          "description":  "My first sensibly named script!",
          "name":         "Hello World",
          "version":      "1"
      }
      

      The manifest.json file is automatically generated from the meta-block by Chrome, when an user script is installed. The values of @include and @exclude meta-rules are stored in include_globs and exclude_globs, @match (recommended) is stored in the matches list. "converted_from_user_script": true is required if you want to use any of the supported GM_* methods.

    5. Now, in Chrome's Extension manager (URL = chrome://extensions/), Expand "Developer mode".

    6. Click the Load unpacked extension... button.

    7. For the folder, paste in the folder for your script, In this example it is: C:\MyChromeScripts\HelloWorld.

    8. Your script is now installed, and operational!

    9. If you make any changes to the script source, hit the Reload link for them to take effect:

      Reload link




    1 The folder defaults to:

    Windows XP:
      Chrome  : %AppData%\..\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\
      Chromium: %AppData%\..\Local Settings\Application Data\Chromium\User Data\Default\Extensions\
    
    Windows Vista/7/8:
      Chrome  : %LocalAppData%\Google\Chrome\User Data\Default\Extensions\
      Chromium: %LocalAppData%\Chromium\User Data\Default\Extensions\
    
    Linux:
      Chrome  : ~/.config/google-chrome/Default/Extensions/
      Chromium: ~/.config/chromium/Default/Extensions/
    
    Mac OS X:
      Chrome  : ~/Library/Application Support/Google/Chrome/Default/Extensions/
      Chromium: ~/Library/Application Support/Chromium/Default/Extensions/
    

    Although you can change it by running Chrome with the --user-data-dir= option.

    Gradle proxy configuration

    Refinement over Daniel's response:

    HTTP Only Proxy configuration

    gradlew -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=3128 "-Dhttp.nonProxyHosts=*.nonproxyrepos.com|localhost"

    HTTPS Only Proxy configuration

    gradlew -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3129 "-Dhttp.nonProxyHosts=*.nonproxyrepos.com|localhost"

    Both HTTP and HTTPS Proxy configuration

    gradlew -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=3128 -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3129 "-Dhttp.nonProxyHosts=*.nonproxyrepos.com|localhost"

    Proxy configuration with user and password

    gradlew -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=3128 - Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3129 -Dhttps.proxyUser=user -Dhttps.proxyPassword=pass -Dhttp.proxyUser=user -Dhttp.proxyPassword=pass -Dhttp.nonProxyHosts=host1.com|host2.com

    worked for me (with gradle.properties in either homedir or project dir, build was still failing). Thanks for pointing the issue at gradle that gave this workaround. See reference doc at https://docs.gradle.org/current/userguide/build_environment.html#sec:accessing_the_web_via_a_proxy

    Update You can also put these properties into gradle-wrapper.properties (see: https://stackoverflow.com/a/50492027/474034).

    How do I replace all line breaks in a string with <br /> elements?

    If the accepted answer isn't working right for you then you might try.

    str.replace(new RegExp('\n','g'), '<br />')
    

    It worked for me.

    How to convert any Object to String?

    I've written a few methods for convert by Gson library and java 1.8 .
    thay are daynamic model for convert.

    string to object

    object to string

    List to string

    string to List

    HashMap to String

    String to JsonObj

    //saeedmpt 
    public static String convertMapToString(Map<String, String> data) {
        //convert Map  to String
        return new GsonBuilder().setPrettyPrinting().create().toJson(data);
    }
    public static <T> List<T> convertStringToList(String strListObj) {
        //convert string json to object List
        return new Gson().fromJson(strListObj, new TypeToken<List<Object>>() {
        }.getType());
    }
    public static <T> T convertStringToObj(String strObj, Class<T> classOfT) {
        //convert string json to object
        return new Gson().fromJson(strObj, (Type) classOfT);
    }
    
    public static JsonObject convertStringToJsonObj(String strObj) {
        //convert string json to object
        return new Gson().fromJson(strObj, JsonObject.class);
    }
    
    public static <T> String convertListObjToString(List<T> listObj) {
        //convert object list to string json for
        return new Gson().toJson(listObj, new TypeToken<List<T>>() {
        }.getType());
    }
    
    public static String convertObjToString(Object clsObj) {
        //convert object  to string json
        String jsonSender = new Gson().toJson(clsObj, new TypeToken<Object>() {
        }.getType());
        return jsonSender;
    }
    

    Calculate correlation with cor(), only for numerical columns

    I found an easier way by looking at the R script generated by Rattle. It looks like below:

    correlations <- cor(mydata[,c(1,3,5:87,89:90,94:98)], use="pairwise", method="spearman")
    

    Converting a String to Object

    String extends Object, which means an Object. Object o = a; If you really want to get as Object, you may do like below.

    String s = "Hi";
    
    Object a =s;
    

    Regular expressions inside SQL Server

    Try this

    select * from mytable
    where p1 not like '%[^0-9]%' and substring(p1,1,1)='5'
    

    Of course, you'll need to adjust the substring value, but the rest should work...

    Can you split a stream into two streams?

    not exactly, but you may be able to accomplish what you need by invoking Collectors.groupingBy(). you create a new Collection, and can then instantiate streams on that new collection.

    MySQL - Rows to Columns

    I edit Agung Sagita's answer from subquery to join. I'm not sure about how much difference between this 2 way, but just for another reference.

    SELECT  hostid, T2.VALUE AS A, T3.VALUE AS B, T4.VALUE AS C
    FROM TableTest AS T1
    LEFT JOIN TableTest T2 ON T2.hostid=T1.hostid AND T2.ITEMNAME='A'
    LEFT JOIN TableTest T3 ON T3.hostid=T1.hostid AND T3.ITEMNAME='B'
    LEFT JOIN TableTest T4 ON T4.hostid=T1.hostid AND T4.ITEMNAME='C'
    

    Uninitialized Constant MessagesController

    Your model is @Messages, change it to @message.

    To change it like you should use migration:

    def change   rename_table :old_table_name, :new_table_name end 

    Of course do not create that file by hand but use rails generator:

    rails g migration ChangeMessagesToMessage 

    That will generate new file with proper timestamp in name in 'db dir. Then run:

    rake db:migrate 

    And your app should be fine since then.