Programs & Examples On #Weblogic maven plugin

Angular 5, HTML, boolean on checkbox is checked

When you have a copy of an object the [checked] attribute might not work, in that case, you can use (change) in this way:

        <input type="checkbox" [checked]="item.selected" (change)="item.selected = !item.selected">

How to select the first element of a set with JSTL?

Sets have no order, but if you still want to get the first element you can use the following:

<c:forEach var="attachment" items="${attachments}" end="0">
     <c:out value="${attachment.id} />
</c:forEach>

ImportError: Cannot import name X

Also not directly relevant to the OP, but failing to restart a PyCharm Python console, after adding a new object to a module, is also a great way to get a very confusing ImportError: Cannot import name ...

The confusing part is that PyCharm will autocomplete the import in the console, but the import then fails.

Iterate two Lists or Arrays with one ForEach statement in C#

This is known as a Zip operation and will be supported in .NET 4.

With that, you would be able to write something like:

var numbers = new [] { 1, 2, 3, 4 };
var words = new [] { "one", "two", "three", "four" };

var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach(var nw in numbersAndWords)
{
    Console.WriteLine(nw.Number + nw.Word);
}

As an alternative to the anonymous type with the named fields, you can also save on braces by using a Tuple and its static Tuple.Create helper:

foreach (var nw in numbers.Zip(words, Tuple.Create)) 
{
    Console.WriteLine(nw.Item1 + nw.Item2);
}

How to include css files in Vue 2

If you want to append this css file to header you can do it using mounted() function of the vue file. See the example.
Note: Assume you can access the css file as http://www.yoursite/assets/styles/vendor.css in the browser.

mounted() {
        let style = document.createElement('link');
        style.type = "text/css";
        style.rel = "stylesheet";
        style.href = '/assets/styles/vendor.css';
        document.head.appendChild(style);
    }

How to POST raw whole JSON in the body of a Retrofit request?

Solved my problem based on TommySM answer (see previous). But I didn't need to make login, I used Retrofit2 for testing https GraphQL API like this:

  1. Defined my BaseResponse class with the help of json annotations (import jackson.annotation.JsonProperty).

    public class MyRequest {
        @JsonProperty("query")
        private String query;
    
        @JsonProperty("operationName")
        private String operationName;
    
        @JsonProperty("variables")
        private String variables;
    
        public void setQuery(String query) {
            this.query = query;
        }
    
        public void setOperationName(String operationName) {
            this.operationName = operationName;
        }
    
        public void setVariables(String variables) {
            this.variables = variables;
        }
    }
    
  2. Defined the call procedure in the interface:

    @POST("/api/apiname")
    Call<BaseResponse> apicall(@Body RequestBody params);
    
  3. Called apicall in the body of test: Create a variable of MyRequest type (for example "myLittleRequest").

    Map<String, Object> jsonParams = convertObjectToMap(myLittleRequest);
    RequestBody body = 
         RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                        (new JSONObject(jsonParams)).toString());
    response = hereIsYourInterfaceName().apicall(body).execute();
    

How to handle change text of span

Found the solution here

Lets say you have span1 as <span id='span1'>my text</span>
text change events can be captured with:

$(document).ready(function(){
    $("#span1").on('DOMSubtreeModified',function(){
         // text change handler
     });

 });
 

ReactJS - Get Height of an element

Here is another one if you need window resize event:

class DivSize extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
      width: 0,
      height: 0
    }
    this.resizeHandler = this.resizeHandler.bind(this);
  }

  resizeHandler() {
    const width = this.divElement.clientWidth;
    const height = this.divElement.clientHeight;
    this.setState({ width, height });
  }

  componentDidMount() {
    this.resizeHandler();
    window.addEventListener('resize', this.resizeHandler);
  }

  componentWillUnmount(){
    window.removeEventListener('resize', this.resizeHandler);
  }

  render() {
    return (
      <div 
        className="test"
        ref={ (divElement) => { this.divElement = divElement } }
      >
        Size: widht: <b>{this.state.width}px</b>, height: <b>{this.state.height}px</b>
      </div>
    )
  }
}

ReactDOM.render(<DivSize />, document.querySelector('#container'))

code pen

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

If you have installed Visual Studio 2012 RC, then it installed .NET 4.5 RC.

Uninstall .NET 4.5 RC, and install the version you need (4.0 for VS 2010). This should clear up any problems you are having.

This solved the same problem. There is no need to uninstall Visual Studio.

Python Key Error=0 - Can't find Dict error in code

The error you're getting is that self.adj doesn't already have a key 0. You're trying to append to a list that doesn't exist yet.

Consider using a defaultdict instead, replacing this line (in __init__):

self.adj = {}

with this:

self.adj = defaultdict(list)

You'll need to import at the top:

from collections import defaultdict

Now rather than raise a KeyError, self.adj[0].append(edge) will create a list automatically to append to.

How do I parse a YAML file in Ruby?

I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

This is the best solution I have found:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])
end

Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files

Redirect from asp.net web api post action

Sure:

public HttpResponseMessage Post()
{
    // ... do the job

    // now redirect
    var response = Request.CreateResponse(HttpStatusCode.Moved);
    response.Headers.Location = new Uri("http://www.abcmvc.com");
    return response;
}

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

GO is like the end of a script.

You could have multiple CREATE TABLE statements, separated by GO. It's a way of isolating one part of the script from another, but submitting it all in one block.


BEGIN and END are just like { and } in C/++/#, Java, etc.

They bound a logical block of code. I tend to use BEGIN and END at the start and end of a stored procedure, but it's not strictly necessary there. Where it IS necessary is for loops, and IF statements, etc, where you need more then one step...

IF EXISTS (SELECT * FROM my_table WHERE id = @id)
BEGIN
   INSERT INTO Log SELECT @id, 'deleted'
   DELETE my_table WHERE id = @id
END

Composer - the requested PHP extension mbstring is missing from your system

For php 7.1

sudo apt-get install php7.1-mbstring

Cheers!

Prevent overwriting a file using cmd if exist

As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.

I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (

The correct version, with the space before the bracket, would be

If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
 start "\\filer\repo\lab\software\myapp\setup.exe"
 pause
) 

CSS transition shorthand with multiple properties?

I think that this should work:

.element {
   -webkit-transition: all .3s;
   -moz-transition: all .3s;
   -o-transition: all .3s;
   transition: all .3s;
}

How to Convert double to int in C?

main() {
    double a;
    a=3669.0;
    int b;
    b=a;
    printf("b is %d",b);
  
}

output is :b is 3669

when you write b=a; then its automatically converted in int

see on-line compiler result : 

http://ideone.com/60T5b


This is called Implicit Type Conversion Read more here https://www.geeksforgeeks.org/implicit-type-conversion-in-c-with-examples/

Unzipping files

I found jszip quite useful. I've used so far only for reading, but they have create/edit capabilities as well.

Code wise it looks something like this

var new_zip = new JSZip();
new_zip.load(file);
new_zip.files["doc.xml"].asText() // this give you the text in the file

One thing I noticed is that it seems the file has to be in binary stream format (read using the .readAsArrayBuffer of FileReader(), otherwise I was getting errors saying I might have a corrupt zip file

Edit: Note from the 2.x to 3.0.0 upgrade guide:

The load() method and the constructor with data (new JSZip(data)) have been replaced by loadAsync().

Thanks user2677034

How to create a POJO?

When you aren't doing anything to make your class particularly designed to work with a given framework, ORM, or other system that needs a special sort of class, you have a Plain Old Java Object, or POJO.

Ironically, one of the reasons for coining the term is that people were avoiding them in cases where they were sensible and some people concluded that this was because they didn't have a fancy name. Ironic, because your question demonstrates that the approach worked.

Compare the older POD "Plain Old Data" to mean a C++ class that doesn't do anything a C struct couldn't do (more or less, non-virtual members that aren't destructors or trivial constructors don't stop it being considered POD), and the newer (and more directly comparable) POCO "Plain Old CLR Object" in .NET.

Why does using an Underscore character in a LIKE filter give me all the results?

As you want to specifically search for a wildcard character you need to escape that

This is done by adding the ESCAPE clause to your LIKE expression. The character that is specified with the ESCAPE clause will "invalidate" the following wildcard character.

You can use any character you like (just not a wildcard character). Most people use a \ because that is what many programming languages also use

So your query would result in:

select * 
from Manager
where managerid LIKE '\_%' escape '\'
and managername like '%\_%' escape '\';

But you can just as well use any other character:

select * 
from Manager
where managerid LIKE '#_%' escape '#'
and managername like '%#_%' escape '#';

Here is an SQLFiddle example: http://sqlfiddle.com/#!6/63e88/4

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

For me the issue was VPN, I disconnected the VPN and "npm i" command worked with no fail.

How to obtain image size using standard Python class (without using external library)?

Regarding Fred the Fantastic's answer:

Not every JPEG marker between C0-CF are SOF markers; I excluded DHT (C4), DNL (C8) and DAC (CC). Note that I haven't looked into whether it is even possible to parse any frames other than C0 and C2 in this manner. However, the other ones seem to be fairly rare (I personally haven't encountered any other than C0 and C2).

Either way, this solves the problem mentioned in comments by Malandy with Bangles.jpg (DHT erroneously parsed as SOF).

The other problem mentioned with 1431588037-WgsI3vK.jpg is due to imghdr only being able detect the APP0 (EXIF) and APP1 (JFIF) headers.

This can be fixed by adding a more lax test to imghdr (e.g. simply FFD8 or maybe FFD8FF?) or something much more complex (possibly even data validation). With a more complex approach I've only found issues with: APP14 (FFEE) (Adobe); the first marker being DQT (FFDB); and APP2 and issues with embedded ICC_PROFILEs.

Revised code below, also altered the call to imghdr.what() slightly:

import struct
import imghdr

def test_jpeg(h, f):
    # SOI APP2 + ICC_PROFILE
    if h[0:4] == '\xff\xd8\xff\xe2' and h[6:17] == b'ICC_PROFILE':
        print "A"
        return 'jpeg'
    # SOI APP14 + Adobe
    if h[0:4] == '\xff\xd8\xff\xee' and h[6:11] == b'Adobe':
        return 'jpeg'
    # SOI DQT
    if h[0:4] == '\xff\xd8\xff\xdb':
        return 'jpeg'
imghdr.tests.append(test_jpeg)

def get_image_size(fname):
    '''Determine the image type of fhandle and return its size.
    from draco'''
    with open(fname, 'rb') as fhandle:
        head = fhandle.read(24)
        if len(head) != 24:
            return
        what = imghdr.what(None, head)
        if what == 'png':
            check = struct.unpack('>i', head[4:8])[0]
            if check != 0x0d0a1a0a:
                return
            width, height = struct.unpack('>ii', head[16:24])
        elif what == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        elif what == 'jpeg':
            try:
                fhandle.seek(0) # Read 0xff next
                size = 2
                ftype = 0
                while not 0xc0 <= ftype <= 0xcf or ftype in (0xc4, 0xc8, 0xcc):
                    fhandle.seek(size, 1)
                    byte = fhandle.read(1)
                    while ord(byte) == 0xff:
                        byte = fhandle.read(1)
                    ftype = ord(byte)
                    size = struct.unpack('>H', fhandle.read(2))[0] - 2
                # We are at a SOFn block
                fhandle.seek(1, 1)  # Skip `precision' byte.
                height, width = struct.unpack('>HH', fhandle.read(4))
            except Exception: #IGNORE:W0703
                return
        else:
            return
        return width, height

Note: Created a full answer instead of a comment, since I'm not yet allowed to.

'any' vs 'Object'

Object is more restrictive than any. For example:

let a: any;
let b: Object;

a.nomethod(); // Transpiles just fine
b.nomethod(); // Error: Property 'nomethod' does not exist on type 'Object'.

The Object class does not have a nomethod() function, therefore the transpiler will generate an error telling you exactly that. If you use any instead you are basically telling the transpiler that anything goes, you are providing no information about what is stored in a - it can be anything! And therefore the transpiler will allow you to do whatever you want with something defined as any.

So in short

  • any can be anything (you can call any method etc on it without compilation errors)
  • Object exposes the functions and properties defined in the Object class.

Can I have two JavaScript onclick events in one element?

You could try something like this as well

<a href="#" onclick="one(); two();" >click</a>

<script type="text/javascript">
    function one(){
        alert('test');
    }

    function two(){
        alert('test2');
    }
</script>

Postgresql: Scripting psql execution with password

There are several ways to authenticate to PostgreSQL. You may wish to investigate alternatives to password authentication at https://www.postgresql.org/docs/current/static/client-authentication.html.

To answer your question, there are a few ways provide a password for password-based authentication. The obvious way is via the password prompt. Instead of that, you can provide the password in a pgpass file or through the PGPASSWORD environment variable. See these:

There is no option to provide the password as a command line argument because that information is often available to all users, and therefore insecure. However, in Linux/Unix environments you can provide an environment variable for a single command like this:

PGPASSWORD=yourpass psql ...

How I can filter a Datatable?

For anybody who work in VB.NET (just in case)

Dim dv As DataView = yourDatatable.DefaultView

dv.RowFilter ="query" ' ex: "parentid = 0"

How do I add images in laravel view?

If Image folder location is public/assets/img/default.jpg. You can try in view

   <img src="{{ URL::to('/assets/img/default.jpg') }}">

int array to string

I realize my opinion is probably not the popular one, but I guess I have a hard time jumping on the Linq-y band wagon. It's nifty. It's condensed. I get that and I'm not opposed to using it where it's appropriate. Maybe it's just me, but I feel like people have stopped thinking about creating utility functions to accomplish what they want and instead prefer to litter their code with (sometimes) excessively long lines of Linq code for the sake of creating a dense 1-liner.

I'm not saying that any of the Linq answers that people have provided here are bad, but I guess I feel like there is the potential that these single lines of code can start to grow longer and more obscure as you need to handle various situations. What if your array is null? What if you want a delimited string instead of just purely concatenated? What if some of the integers in your array are double-digit and you want to pad each value with leading zeros so that the string for each element is the same length as the rest?

Taking one of the provided answers as an example:

        result = arr.Aggregate(string.Empty, (s, i) => s + i.ToString());

If I need to worry about the array being null, now it becomes this:

        result = (arr == null) ? null : arr.Aggregate(string.Empty, (s, i) => s + i.ToString());

If I want a comma-delimited string, now it becomes this:

        result = (arr == null) ? null : arr.Skip(1).Aggregate(arr[0].ToString(), (s, i) => s + "," + i.ToString());

This is still not too bad, but I think it's not obvious at a glance what this line of code is doing.

Of course, there's nothing stopping you from throwing this line of code into your own utility function so that you don't have that long mess mixed in with your application logic, especially if you're doing it in multiple places:

    public static string ToStringLinqy<T>(this T[] array, string delimiter)
    {
        // edit: let's replace this with a "better" version using a StringBuilder
        //return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(array[0].ToString(), (s, i) => s + "," + i.ToString());
        return (array == null) ? null : (array.Length == 0) ? string.Empty : array.Skip(1).Aggregate(new StringBuilder(array[0].ToString()), (s, i) => s.Append(delimiter).Append(i), s => s.ToString());
    }

But if you're going to put it into a utility function anyway, do you really need it to be condensed down into a 1-liner? In that case why not throw in a few extra lines for clarity and take advantage of a StringBuilder so that you're not doing repeated concatenation operations:

    public static string ToStringNonLinqy<T>(this T[] array, string delimiter)
    {
        if (array != null)
        {
            // edit: replaced my previous implementation to use StringBuilder
            if (array.Length > 0)
            {
                StringBuilder builder = new StringBuilder();

                builder.Append(array[0]);
                for (int i = 1; i < array.Length; i++)
                {
                    builder.Append(delimiter);
                    builder.Append(array[i]);
                }

                return builder.ToString()
            }
            else
            {
                return string.Empty;
            }
        }
        else
        {
            return null;
        }
    }

And if you're really so concerned about performance, you could even turn it into a hybrid function that decides whether to do string.Join or to use a StringBuilder depending on how many elements are in the array (this is a micro-optimization, not worth doing in my opinion and possibly more harmful than beneficial, but I'm using it as an example for this problem):

    public static string ToString<T>(this T[] array, string delimiter)
    {
        if (array != null)
        {
            // determine if the length of the array is greater than the performance threshold for using a stringbuilder
            // 10 is just an arbitrary threshold value I've chosen
            if (array.Length < 10)
            {
                // assumption is that for arrays of less than 10 elements
                // this code would be more efficient than a StringBuilder.
                // Note: this is a crazy/pointless micro-optimization.  Don't do this.
                string[] values = new string[array.Length];

                for (int i = 0; i < values.Length; i++)
                    values[i] = array[i].ToString();

                return string.Join(delimiter, values);
            }
            else
            {
                // for arrays of length 10 or longer, use a StringBuilder
                StringBuilder sb = new StringBuilder();

                sb.Append(array[0]);
                for (int i = 1; i < array.Length; i++)
                {
                    sb.Append(delimiter);
                    sb.Append(array[i]);
                }

                return sb.ToString();
            }
        }
        else
        {
            return null;
        }
    }

For this example, the performance impact is probably not worth caring about, but the point is that if you are in a situation where you actually do need to be concerned with the performance of your operations, whatever they are, then it will most likely be easier and more readable to handle that within a utility function than using a complex Linq expression.

That utility function still looks kind of clunky. Now let's ditch the hybrid stuff and do this:

    // convert an enumeration of one type into an enumeration of another type
    public static IEnumerable<TOut> Convert<TIn, TOut>(this IEnumerable<TIn> input, Func<TIn, TOut> conversion)
    {
        foreach (TIn value in input)
        {
            yield return conversion(value);
        }
    }

    // concatenate the strings in an enumeration separated by the specified delimiter
    public static string Delimit<T>(this IEnumerable<T> input, string delimiter)
    {
        IEnumerator<T> enumerator = input.GetEnumerator();

        if (enumerator.MoveNext())
        {
            StringBuilder builder = new StringBuilder();

            // start off with the first element
            builder.Append(enumerator.Current);

            // append the remaining elements separated by the delimiter
            while (enumerator.MoveNext())
            {
                builder.Append(delimiter);
                builder.Append(enumerator.Current);
            }

            return builder.ToString();
        }
        else
        {
            return string.Empty;
        }
    }

    // concatenate all elements
    public static string ToString<T>(this IEnumerable<T> input)
    {
        return ToString(input, string.Empty);
    }

    // concatenate all elements separated by a delimiter
    public static string ToString<T>(this IEnumerable<T> input, string delimiter)
    {
        return input.Delimit(delimiter);
    }

    // concatenate all elements, each one left-padded to a minimum length
    public static string ToString<T>(this IEnumerable<T> input, int minLength, char paddingChar)
    {
        return input.Convert(i => i.ToString().PadLeft(minLength, paddingChar)).Delimit(string.Empty);
    }

Now we have separate and fairly compact utility functions, each of which are arguable useful on their own.

Ultimately, my point is not that you shouldn't use Linq, but rather just to say don't forget about the benefits of creating your own utility functions, even if they are small and perhaps only contain a single line that returns the result from a line of Linq code. If nothing else, you'll be able to keep your application code even more condensed than you could achieve with a line of Linq code, and if you are using it in multiple places, then using a utility function makes it easier to adjust your output in case you need to change it later.

For this problem, I'd rather just write something like this in my application code:

        int[] arr = { 0, 1, 2, 3, 0, 1 };

        // 012301
        result = arr.ToString<int>();

        // comma-separated values
        // 0,1,2,3,0,1
        result = arr.ToString(",");

        // left-padded to 2 digits
        // 000102030001
        result = arr.ToString(2, '0');

How to iterate over rows in a DataFrame in Pandas

For both viewing and modifying values, I would use iterrows(). In a for loop and by using tuple unpacking (see the example: i, row), I use the row for only viewing the value and use i with the loc method when I want to modify values. As stated in previous answers, here you should not modify something you are iterating over.

for i, row in df.iterrows():
    df_column_A = df.loc[i, 'A']
    if df_column_A == 'Old_Value':
        df_column_A = 'New_value'  

Here the row in the loop is a copy of that row, and not a view of it. Therefore, you should NOT write something like row['A'] = 'New_Value', it will not modify the DataFrame. However, you can use i and loc and specify the DataFrame to do the work.

Is there a REAL performance difference between INT and VARCHAR primary keys?

For short codes, there's probably no difference. This is especially true as the table holding these codes are likely to be very small (a couple thousand rows at most) and not change often (when is the last time we added a new US State).

For larger tables with a wider variation among the key, this can be dangerous. Think about using e-mail address/user name from a User table, for example. What happens when you have a few million users and some of those users have long names or e-mail addresses. Now any time you need to join this table using that key it becomes much more expensive.

Regular expression to search multiple strings (Textpad)

If I understand what you are asking, it is a regular expression like this:

^(8768|9875|2353)

This matches the three sets of digit strings at beginning of line only.

Convert hex to binary

Replace each hex digit with the corresponding 4 binary digits:

1 - 0001
2 - 0010
...
a - 1010
b - 1011
...
f - 1111

Sorting a DropDownList? - C#, ASP.NET

If your data is coming to you as a System.Data.DataTable, call the DataTable's .Select() method, passing in "" for the filterExpression and "COLUMN1 ASC" (or whatever column you want to sort by) for the sort. This will return an array of DataRow objects, sorted as specified, that you can then iterate through and dump into the DropDownList.

How to hide column of DataGridView when using custom DataSource?

In some cases, it might be a bad idea to first add the column to the DataGridView and then hide it.

I for example have a class that has an NHibernate proxy for an Image property for company logos. If I accessed that property (e.g. by calling its ToString method to show that in a DataGridView), it would download the image from the SQL server. If I had a list of Company objects and used that as the dataSource of the DataGridView like that, then (I suspect) it would download ALL the logos BEFORE I could hide the column.

To prevent this, I used the custom attribute

 [System.ComponentModel.Browsable(false)]

on the image property, so that the DataGridView ignores the property (doesn't create the column and doesn't call the ToString methods).

 public class Company
 {
     ...
     [System.ComponentModel.Browsable(false)]
     virtual public MyImageClass Logo { get; set;}

How to access SVG elements with Javascript

If you are using an <img> tag for the SVG, then you cannot manipulate its contents (as far as I know).

As the accepted answer shows, using <object> is an option.

I needed this recently and used gulp-inject during my gulp build to inject the contents of an SVG file directly into the HTML document as an <svg> element, which is then very easy to work with using CSS selectors and querySelector/getElementBy*.

Generate random integers between 0 and 9

>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

To get a list of ten samples:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]

How to chain scope queries with OR instead of AND?

You would do

Person.where('name=? OR lastname=?', 'John', 'Smith')

Right now, there isn't any other OR support by the new AR3 syntax (that is without using some 3rd party gem).

How can I check the size of a collection within a Django template?

You can try with:

{% if theList.object_list.count > 0 %}
    blah, blah...
{% else %}
    blah, blah....
{% endif %} 

Android: How do I prevent the soft keyboard from pushing my view up?

You can simply switch your Activity's windowSoftInputModeflag to adjustPan in your AndroidMainfest.xml file inside your activity tag.

Check the official documentation for more info.

<activity
   ...
   android:windowSoftInputMode="adjustPan"> 
</activity>

If your container is not changing size, then you likely have the height set to "match parent". If possible, set the parent to "Wrap Content", or a constraint layout with constraingts to top and bottom of parent.

The parent container will shrink to fit the available space, so it is likely that your content should be inside of a scolling view to prevent (depending on the phone manufacturer and the layout choosen...)

  1. Content being smashed together
  2. Content hanging off the screen
  3. Content being inacccessable due to it being underneath the keyboard

even if the layout it is in is a relative or constraint layout, the content could exhibit problems 1-3.

Build not visible in itunes connect

This worked for me

If build are missing from Itunes 'Activity' tab. Then check your info.plist keys. If all keys are there, then check all keys description. if their length is short then increase your keys description length.

"Instantiating" a List in Java?

A List in java is an interface that defines certain qualities a "list" must have. Specific list implementations, such as ArrayList implement this interface and flesh out how the various methods are to work. What are you trying to accomplish with this list? Most likely, one of the built-in lists will work for you.

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

Simple if-else statement in SQL Server:

DECLARE @val INT;
SET @val = 15;

IF @val < 25
PRINT 'Hi Ravi Anand';
ELSE
PRINT 'By Ravi Anand.';

GO

Nested If...else statement in SQL Server -

DECLARE @val INT;
SET @val = 15;

IF @val < 25
PRINT 'Hi Ravi Anand.';
ELSE
BEGIN
IF @val < 50
  PRINT 'what''s up?';
ELSE
  PRINT 'Bye Ravi Anand.';
END;

GO

Radio Buttons ng-checked with ng-model

Please explain why same ng-model is used? And what value is passed through ng- model and how it is passed? To be more specific, if I use console.log(color) what would be the output?

JList add/remove Item

The problem is

listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());

you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.

Try

private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
    {
        lm2 = new DefaultListModel();
        listaTitolari.setModel(lm2);
    }
    lm2.addElement(listaTitolari.getSelectedValue());
    lm1.removeElement(listaTitolari.getSelectedValue());        
} 

Authenticate with GitHub using a token

For those coming from GitLab what's worked for me:

Step 1.

add remote

git remote add origin https://<access-token-name>:<access-token>@gitlab.com/path/to/project.git

Step 2.

pull once

https://<access-token-name>:<access-token>@gitlab.com/path/to/project.git

now you are able to read/write to/from repository

How to use View.OnTouchListener instead of onClick

OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:

myView.setOnTouchListener(new View.OnTouchListener()
{
    // Implementation;
});

C# looping through an array

Here is a more general solution:

int increment = 3;
for(int i = 0; i < theData.Length; i += increment)
{
   for(int j = 0; j < increment; j++)
   {
      if(i+j < theData.Length) {
         //theData[i + j] for the current index
      }
   }

}

How can I check whether a option already exist in select by JQuery

Although most of other answers worked for me I used .find():

if ($("#yourSelect").find('option[value="value"]').length === 0){
    ...
}

Run exe file with parameters in a batch file

If you need to see the output of the execute, use CALL together with or instead of START.

Example:

CALL "C:\Program Files\Certain Directory\file.exe" -param PAUSE

This will run the file.exe and print back whatever it outputs, in the same command window. Remember the PAUSE after the call or else the window may close instantly.

Storing C++ template function definitions in a .CPP file

This should work fine everywhere templates are supported. Explicit template instantiation is part of the C++ standard.

Disable all Database related auto configuration in Spring Boot

I had the same problem here, solved like this:

Just add another application-{yourprofile}.yml where "yourprofile" could be "client".

In my case I just wanted to remove Redis in a Dev profile, so I added a application-dev.yml next to the main application.yml and it did the job.

In this file I put:

spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration

this should work with properties files as well.

I like the fact that there is no need to change the application code to do that.

Converting from longitude\latitude to Cartesian coordinates

Why implement something which has already been implemented and test-proven?

C#, for one, has the NetTopologySuite which is the .NET port of the JTS Topology Suite.

Specifically, you have a severe flaw in your calculation. The earth is not a perfect sphere, and the approximation of the earth's radius might not cut it for precise measurements.

If in some cases it's acceptable to use homebrew functions, GIS is a good example of a field in which it is much preferred to use a reliable, test-proven library.

XPath: Get parent node from child node

Just as an alternative, you can use ancestor.

//*[title="50"]/ancestor::store

It's more powerful than parent since it can get even the grandparent or great great grandparent

Where does Oracle SQL Developer store connections?

Assuming you have lost these while upgrading versions like I did, follow these steps to restore:

  1. Open SQL Developer
  2. Right click on Connections
  3. Chose Import Connections...
  4. Click Browse (should open to your SQL Developer directory)
  5. Drill down to "systemx.x.xx.xx" (replace x's with your previous version of SQL Developer)
  6. Find and drill into a folder that has ".db.connection." in it (for me, it was in o.jdeveloper.db.connection.11.1.1.4.37.59.48)
  7. select connections.xml and click open

You should then see the list of connections that will be imported

How can I represent an infinite number in Python?

In Python, you can do:

test = float("inf")

In Python 3.5, you can do:

import math
test = math.inf

And then:

test > 1
test > 10000
test > x

Will always be true. Unless of course, as pointed out, x is also infinity or "nan" ("not a number").

Additionally (Python 2.x ONLY), in a comparison to Ellipsis, float(inf) is lesser, e.g:

float('inf') < Ellipsis

would return true.

PHP date() with timezone?

Try this. You can pass either unix timestamp, or datetime string

public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s') 
    {
        $datetime = is_numeric($timestamp) ?
                    DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
                    new DateTime($timestamp, new DateTimeZone($fromTimezone));

        $datetime->setTimezone(new DateTimeZone($toTimezone));

        return $datetime->format($format);
    }

How can I make a div stick to the top of the screen once it's been scrolled to?

Here's one more version to try for those having issues with the others. It pulls together the techniques discussed in this duplicate question, and generates the required helper DIVs dynamically so no extra HTML is required.

CSS:

.sticky { position:fixed; top:0; }

JQuery:

function make_sticky(id) {
    var e = $(id);
    var w = $(window);
    $('<div/>').insertBefore(id);
    $('<div/>').hide().css('height',e.outerHeight()).insertAfter(id);
    var n = e.next();
    var p = e.prev();
    function sticky_relocate() {
      var window_top = w.scrollTop();
      var div_top = p.offset().top;
      if (window_top > div_top) {
        e.addClass('sticky');
        n.show();
      } else {
        e.removeClass('sticky');
        n.hide();
      }
    }
    w.scroll(sticky_relocate);
    sticky_relocate();
}

To make an element sticky, do:

make_sticky('#sticky-elem-id');

When the element becomes sticky, the code manages the position of the remaining content to keep it from jumping into the gap left by the sticky element. It also returns the sticky element to its original non-sticky position when scrolling back above it.

message box in jquery

If you don't wont use jquery.ui(that is highly recommended), you can take a look at Block.UI plugin.

Check if string contains only letters in javascript

You need

/^[a-zA-Z]+$/

Currently, you are matching a single character at the start of the input. If your goal is to match letter characters (one or more) from start to finish, then you need to repeat the a-z character match (using +) and specify that you want to match all the way to the end (via $)

How to hide command output in Bash

You can redirect the output to /dev/null. For more info regarding /dev/null read this link.

You can hide the output of a comand in the following ways :

echo -n "Installing nano ......"; yum install nano > /dev/null; echo " done."; 

Redirect the standard output to /dev/null, but not the standard error. This will show the errors occurring during the installation, for example if yum cannot find a package.

echo -n "Installing nano ......"; yum install nano &> /dev/null; echo " done.";

While this code will not show anything in the terminal since both standard error and standard output are redirected and thus nullified to /dev/null.

How to check if that data already exist in the database during update (Mongoose And Express)

Here is another way to accomplish this in less code.

UPDATE 3: Asynchronous model class statics

Similar to option 2, this allows you to create a function directly linked to the schema, but called from the same file using the model.

model.js

 userSchema.statics.updateUser = function(user, cb) {
  UserModel.find({name : user.name}).exec(function(err, docs) {
    if (docs.length){
      cb('Name exists already', null);
    } else {
      user.save(function(err) {
        cb(err,user);
      }
    }
  });
}

Call from file

var User = require('./path/to/model');

User.updateUser(user.name, function(err, user) {
  if(err) {
    var error = new Error('Already exists!');
    error.status = 401;
    return next(error);
  }
});

pip or pip3 to install packages for Python 3?

If you had python 2.x and then installed python3, your pip will be pointing to pip3. you can verify that by typing pip --version which would be the same as pip3 --version.

On your system you have now pip, pip2 and pip3.

If you want you can change pip to point to pip2 instead of pip3.

Test if a string contains a word in PHP?

if (strpos($string, $word) === FALSE) {
   ... not found ...
}

Note that strpos() is case sensitive, if you want a case-insensitive search, use stripos() instead.

Also note the ===, forcing a strict equality test. strpos CAN return a valid 0 if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.

Error after upgrading pip: cannot import name 'main'

I'm running on a system where I have sudo apt but no sudo pip. (And no su access.) I got myself into this same situation by following the advice from pip:

You are using pip version 8.1.1, however 18.0 is available. You should consider upgrading via the 'pip install --upgrade pip' command.

None of the other fixes worked for me, because I don't have enough admin privileges. However, a few things stuck with me from reading up on this:

  • I shouldn't have done this. Sure, pip told me to. It lied.
  • Using --user solves a lot of issues by focusing on the user-only directory.

So, I found this command line to work to revert me back to where I was. If you were using a different version than 8.1.1, you will obviously want to change that part of the line.

python -m pip install --force-reinstall pip==8.1.1 --user

That's the only thing that worked for me, but it worked perfectly!

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

In VS 2012, I was getting "SMB2 will not build: Error 1 error MSB8020: The builds tools for Visual Studio 2010 (Platform Toolset = 'v100') cannot be found. To build using the v100 build tools, either click the Project menu or right-click the solution, and then select "Update VC++ Projects...". Install Visual Studio 2010 to build using the Visual Studio 2010 build tools."

Throwing caution to the wind, I tried the suggestion: Selected the Solution in Solution Explorer, then clicked in the "Update VC++" menu item. This did some updateing and then started a build which succeeded.

The "Update VC++" menu item no longer appears in the solution menu.

Get UTC time and local time from NSDate object

I found an easier way to get UTC in Swift4. Put this code in playground

let date = Date() 
*//"Mar 15, 2018 at 4:01 PM"*

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

let newDate = dateFormatter.string(from: date) 
*//"2018-03-15 21:05:04 +0000"*

What is the best way to create and populate a numbers table?

This is a repackaging of the accepted answer - but in a way that lets you compare them all to each other for yourself - the top 3 algorithms are compared (and comments explain why other methods are excluded) and you can run against your own setup to see how they each perform with the size of sequence that you desire.

SET NOCOUNT ON;

--
-- Set the count of numbers that you want in your sequence ...
--
DECLARE @NumberOfNumbers int = 10000000;
--
--  Some notes on choosing a useful length for your sequence ...
--      For a sequence of  100 numbers -- winner depends on preference of min/max/avg runtime ... (I prefer PhilKelley algo here - edit the algo so RowSet2 is max RowSet CTE)
--      For a sequence of   1k numbers -- winner depends on preference of min/max/avg runtime ... (Sadly PhilKelley algo is generally lowest ranked in this bucket, but could be tweaked to perform better)
--      For a sequence of  10k numbers -- a clear winner emerges for this bucket
--      For a sequence of 100k numbers -- do not test any looping methods at this size or above ...
--                                        the previous winner fails, a different method is need to guarantee the full sequence desired
--      For a sequence of  1MM numbers -- the statistics aren't changing much between the algorithms - choose one based on your own goals or tweaks
--      For a sequence of 10MM numbers -- only one of the methods yields the desired sequence, and the numbers are much closer than for smaller sequences

DECLARE @TestIteration int = 0;
DECLARE @MaxIterations int = 10;
DECLARE @MethodName varchar(128);

-- SQL SERVER 2017 Syntax/Support needed
DROP TABLE IF EXISTS #TimingTest
CREATE TABLE #TimingTest (MethodName varchar(128), TestIteration int, StartDate DateTime2, EndDate DateTime2, ElapsedTime decimal(38,0), ItemCount decimal(38,0), MaxNumber decimal(38,0), MinNumber decimal(38,0))

--
--  Conduct the test ...
--
WHILE @TestIteration < @MaxIterations
BEGIN
    -- Be sure that the test moves forward
    SET @TestIteration += 1;

/*  -- This method has been removed, as it is BY FAR, the slowest method
    -- This test shows that, looping should be avoided, likely at all costs, if one places a value / premium on speed of execution ...

    --
    -- METHOD - Fast looping
    --

    -- Prep for the test
    DROP TABLE IF EXISTS [Numbers].[Test];
    CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);

    -- Method information
    SET @MethodName = 'FastLoop';

    -- Record the start of the test
    INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
    SELECT @MethodName, @TestIteration, GETDATE()

    -- Run the algorithm
    DECLARE @i INT = 1;
    WHILE @i <= @NumberOfNumbers
    BEGIN
        INSERT INTO [Numbers].[Test](Number) VALUES (@i);
        SELECT @i = @i + 1;
    END;

    ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)

    -- Record the end of the test
    UPDATE tt
        SET 
            EndDate = GETDATE()
    FROM #TimingTest tt
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    -- And the stats about the numbers in the sequence
    UPDATE tt
        SET 
            ItemCount = results.ItemCount,
            MaxNumber = results.MaxNumber,
            MinNumber = results.MinNumber
    FROM #TimingTest tt
    CROSS JOIN (
        SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
    ) results
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration
*/

/*  -- This method requires GO statements, which would break the script, also - this answer does not appear to be the fastest *AND* seems to perform "magic"
    --
    -- METHOD - "Semi-Looping"
    --

    -- Prep for the test
    DROP TABLE IF EXISTS [Numbers].[Test];
    CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);

    -- Method information
    SET @MethodName = 'SemiLoop';

    -- Record the start of the test
    INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
    SELECT @MethodName, @TestIteration, GETDATE()

    -- Run the algorithm 
    INSERT [Numbers].[Test] values (1);
--    GO --required

    INSERT [Numbers].[Test] SELECT Number + (SELECT COUNT(*) FROM [Numbers].[Test]) FROM [Numbers].[Test]
--    GO 14 --will create 16384 total rows

    ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)

    -- Record the end of the test
    UPDATE tt
        SET 
            EndDate = GETDATE()
    FROM #TimingTest tt
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    -- And the stats about the numbers in the sequence
    UPDATE tt
        SET 
            ItemCount = results.ItemCount,
            MaxNumber = results.MaxNumber,
            MinNumber = results.MinNumber
    FROM #TimingTest tt
    CROSS JOIN (
        SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
    ) results
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration
*/
    --
    -- METHOD - Philip Kelley's algo 
    --          (needs tweaking to match the desired length of sequence in order to optimize its performance, relies more on the coder to properly tweak the algorithm)
    --

    -- Prep for the test
    DROP TABLE IF EXISTS [Numbers].[Test];
    CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);

    -- Method information
    SET @MethodName = 'PhilKelley';

    -- Record the start of the test
    INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
    SELECT @MethodName, @TestIteration, GETDATE()

    -- Run the algorithm
    ; WITH
    RowSet0 as (select 1 as Item union all select 1),              --          2 rows   -- We only have to name the column in the first select, the second/union select inherits the column name
    RowSet1 as (select 1 as Item from RowSet0 as A, RowSet0 as B), --          4 rows
    RowSet2 as (select 1 as Item from RowSet1 as A, RowSet1 as B), --         16 rows
    RowSet3 as (select 1 as Item from RowSet2 as A, RowSet2 as B), --        256 rows
    RowSet4 as (select 1 as Item from RowSet3 as A, RowSet3 as B), --      65536 rows (65k)
    RowSet5 as (select 1 as Item from RowSet4 as A, RowSet4 as B), -- 4294967296 rows (4BB)
    -- Add more RowSetX to get higher and higher numbers of rows    
    -- Each successive RowSetX results in squaring the previously available number of rows
    Tally   as (select row_number() over (order by Item) as Number from RowSet5) -- This is what gives us the sequence of integers, always select from the terminal CTE expression
    -- Note: testing of this specific use case has shown that making Tally as a sub-query instead of a terminal CTE expression is slower (always) - be sure to follow this pattern closely for max performance
    INSERT INTO [Numbers].[Test] (Number)
    SELECT o.Number
    FROM Tally o
    WHERE o.Number <= @NumberOfNumbers

    ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)

    -- Record the end of the test
    UPDATE tt
        SET 
            EndDate = GETDATE()
    FROM #TimingTest tt
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    -- And the stats about the numbers in the sequence
    UPDATE tt
        SET 
            ItemCount = results.ItemCount,
            MaxNumber = results.MaxNumber,
            MinNumber = results.MinNumber
    FROM #TimingTest tt
    CROSS JOIN (
        SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
    ) results
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    --
    -- METHOD - Mladen Prajdic answer
    --

    -- Prep for the test
    DROP TABLE IF EXISTS [Numbers].[Test];
    CREATE TABLE [Numbers].[Test] (Number INT NOT NULL);

    -- Method information
    SET @MethodName = 'MladenPrajdic';

    -- Record the start of the test
    INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
    SELECT @MethodName, @TestIteration, GETDATE()

    -- Run the algorithm
    INSERT INTO [Numbers].[Test](Number)
    SELECT TOP (@NumberOfNumbers) row_number() over(order by t1.number) as N
    FROM master..spt_values t1 
    CROSS JOIN master..spt_values t2

    ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)

    -- Record the end of the test
    UPDATE tt
        SET 
            EndDate = GETDATE()
    FROM #TimingTest tt
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    -- And the stats about the numbers in the sequence
    UPDATE tt
        SET 
            ItemCount = results.ItemCount,
            MaxNumber = results.MaxNumber,
            MinNumber = results.MinNumber
    FROM #TimingTest tt
    CROSS JOIN (
        SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
    ) results
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    --
    -- METHOD - Single INSERT
    -- 

    -- Prep for the test
    DROP TABLE IF EXISTS [Numbers].[Test];
    -- The Table creation is part of this algorithm ...

    -- Method information
    SET @MethodName = 'SingleInsert';

    -- Record the start of the test
    INSERT INTO #TimingTest(MethodName, TestIteration, StartDate)
    SELECT @MethodName, @TestIteration, GETDATE()

    -- Run the algorithm
    SELECT TOP (@NumberOfNumbers) IDENTITY(int,1,1) AS Number
    INTO [Numbers].[Test]
    FROM sys.objects s1       -- use sys.columns if you don't get enough rows returned to generate all the numbers you need
    CROSS JOIN sys.objects s2 -- use sys.columns if you don't get enough rows returned to generate all the numbers you need

    ALTER TABLE [Numbers].[Test] ADD CONSTRAINT PK_Numbers_Test_Number PRIMARY KEY CLUSTERED (Number)

    -- Record the end of the test
    UPDATE tt
        SET 
            EndDate = GETDATE()
    FROM #TimingTest tt
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration

    -- And the stats about the numbers in the sequence
    UPDATE tt
        SET 
            ItemCount = results.ItemCount,
            MaxNumber = results.MaxNumber,
            MinNumber = results.MinNumber
    FROM #TimingTest tt
    CROSS JOIN (
        SELECT COUNT(Number) as ItemCount, MAX(Number) as MaxNumber, MIN(Number) as MinNumber FROM [Numbers].[Test]
    ) results
    WHERE tt.MethodName = @MethodName
    and tt.TestIteration = @TestIteration
END

-- Calculate the timespan for each of the runs
UPDATE tt
    SET
        ElapsedTime = DATEDIFF(MICROSECOND, StartDate, EndDate)
FROM #TimingTest tt

--
-- Report the results ...
--
SELECT 
    MethodName, AVG(ElapsedTime) / AVG(ItemCount) as TimePerRecord, CAST(AVG(ItemCount) as bigint) as SequenceLength,
    MAX(ElapsedTime) as MaxTime, MIN(ElapsedTime) as MinTime,
    MAX(MaxNumber) as MaxNumber, MIN(MinNumber) as MinNumber
FROM #TimingTest tt
GROUP by tt.MethodName
ORDER BY TimePerRecord ASC, MaxTime ASC, MinTime ASC

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Passing parameters to a JDBC PreparedStatement

You should use the setString() method to set the userID. This both ensures that the statement is formatted properly, and prevents SQL injection:

statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
statement.setString(1, userID);

There is a nice tutorial on how to use PreparedStatements properly in the Java Tutorials.

com.android.build.transform.api.TransformException

you can see the documentation of Android

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

    defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

How to set HTTP headers (for cache-control)?

For Apache server, you should check mod_expires for setting Expires and Cache-Control headers.

Alternatively, you can use Header directive to add Cache-Control on your own:

Header set Cache-Control "max-age=290304000, public"

Difference between numeric, float and decimal in SQL Server

The case for Decimal

What it the underlying need?

It arises from the fact that, ultimately, computers represent, internally, numbers in binary format. That leads, inevitably, to rounding errors.

Consider this:

0.1 (decimal, or "base 10") = .00011001100110011... (binary, or "base 2")

The above ellipsis [...] means 'infinite'. If you look at it carefully, there is an infinite repeating pattern (='0011')

So, at some point the computer has to round that value. This leads to accumulation errors deriving from the repeated use of numbers that are inexactly stored.

Say that you want to store financial amounts (which are numbers that may have a fractional part). First of all, you cannot use integers obviously (integers don't have a fractional part). From a purely mathematical point of view, the natural tendency would be to use a float. But, in a computer, floats have the part of a number that is located after a decimal point - the "mantissa" - limited. That leads to rounding errors.

To overcome this, computers offer specific datatypes that limit the binary rounding error in computers for decimal numbers. These are the data type that should absolutely be used to represent financial amounts. These data types typically go by the name of Decimal. That's the case in C#, for example. Or, DECIMAL in most databases.

Time complexity of Euclid's Algorithm

There's a great look at this on the wikipedia article.

It even has a nice plot of complexity for value pairs.

It is not O(a%b).

It is known (see article) that it will never take more steps than five times the number of digits in the smaller number. So the max number of steps grows as the number of digits (ln b). The cost of each step also grows as the number of digits, so the complexity is bound by O(ln^2 b) where b is the smaller number. That's an upper limit, and the actual time is usually less.

Increase distance between text and title on the y-axis

Based on this forum post: https://groups.google.com/forum/#!topic/ggplot2/mK9DR3dKIBU

Sounds like the easiest thing to do is to add a line break (\n) before your x axis, and after your y axis labels. Seems a lot easier (although dumber) than the solutions posted above.

ggplot(mpg, aes(cty, hwy)) + 
    geom_point() + 
    xlab("\nYour_x_Label") + ylab("Your_y_Label\n")

Hope that helps!

Using python PIL to turn a RGB image into a pure black and white image

from PIL import Image 
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')

yields

enter image description here

How to extract a floating number from a string

If your float is always expressed in decimal notation something like

>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4 db.")
['13.4']

may suffice.

A more robust version would be:

>>> re.findall(r"[-+]?\d*\.\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")
['-13.2', '14.2', '3']

If you want to validate user input, you could alternatively also check for a float by stepping to it directly:

user_input = "Current Level: 1e100 db"
for token in user_input.split():
    try:
        # if this succeeds, you have your (first) float
        print float(token), "is a float"
    except ValueError:
        print token, "is something else"

# => Would print ...
#
# Current is something else
# Level: is something else
# 1e+100 is a float
# db is something else

How should I edit an Entity Framework connection string?

No, you can't edit the connection string in the designer. The connection string is not part of the EDMX file it is just referenced value from the configuration file and probably because of that it is just readonly in the properties window.

Modifying configuration file is common task because you sometimes wants to make change without rebuilding the application. That is the reason why configuration files exist.

Adding click event handler to iframe

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

Add x and y labels to a pandas plot

If you label the columns and index of your DataFrame, pandas will automatically supply appropriate labels:

import pandas as pd
values = [[1, 2], [2, 5]]
df = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                  index=['Index 1', 'Index 2'])
df.columns.name = 'Type'
df.index.name = 'Index'
df.plot(lw=2, colormap='jet', marker='.', markersize=10, 
        title='Video streaming dropout by category')

enter image description here

In this case, you'll still need to supply y-labels manually (e.g., via plt.ylabel as shown in the other answers).

What is the difference between static func and class func in Swift?

Both the static and class keywords allow us to attach methods to a class rather than to instances of a class. For example, you might create a Student class with properties such as name and age, then create a static method numberOfStudents that is owned by the Student class itself rather than individual instances.

Where static and class differ is how they support inheritance. When you make a static method it becomes owned by the class and can't be changed by subclasses, whereas when you use class it may be overridden if needed.

Here is an Example code:

  class Vehicle {
    static func getCurrentSpeed() -> Int {
        return 0
    }

    class func getCurrentNumberOfPassengers() -> Int {
        return 0
    } 

  }

  class Bicycle: Vehicle {
    //This is not allowed
    //Compiler error: "Cannot override static method"
  //  static override func getCurrentSpeed() -> Int {
  //        return 15
  //  }

      class override func getCurrentNumberOfPassengers() -> Int {
        return 1
      }
  }

How to put a jpg or png image into a button in HTML

<a href="#">
        <img src="p.png"></img>
    </a>

Creating an index on a table variable

It should be understood that from a performance standpoint there are no differences between @temp tables and #temp tables that favor variables. They reside in the same place (tempdb) and are implemented the same way. All the differences appear in additional features. See this amazingly complete writeup: https://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386

Although there are cases where a temp table can't be used such as in table or scalar functions, for most other cases prior to v2016 (where even filtered indexes can be added to a table variable) you can simply use a #temp table.

The drawback to using named indexes (or constraints) in tempdb is that the names can then clash. Not just theoretically with other procedures but often quite easily with other instances of the procedure itself which would try to put the same index on its copy of the #temp table.

To avoid name clashes, something like this usually works:

declare @cmd varchar(500)='CREATE NONCLUSTERED INDEX [ix_temp'+cast(newid() as varchar(40))+'] ON #temp (NonUniqueIndexNeeded);';
exec (@cmd);

This insures the name is always unique even between simultaneous executions of the same procedure.

Visual Studio Code open tab in new window

With Visual Studio 1.43 (Q1 2020), the Ctrl+K then O keyboard shortcut will work for a file.

See issue 89989:

It should be possible to e.g. invoke the "Open Active File in New Window" command and open that file into an empty workspace in the web.

new windows -- https://user-images.githubusercontent.com/900690/73733120-aa0f6680-473b-11ea-8bcd-f2f71b75b496.png

Hashmap holding different data types as values for instance Integer, String and Object

If you don't have Your own Data Class, then you can design your map as follows

Map<Integer, Object> map=new HashMap<Integer, Object>();

Here don't forget to use "instanceof" operator while retrieving the values from MAP.

If you have your own Data class then then you can design your map as follows

Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class HashMapTest {
public static void main(String[] args) {
    Map<Integer,Demo> map=new HashMap<Integer, Demo>();
    Demo d1= new Demo(1,"hi",new Date(),1,1);
    Demo d2= new Demo(2,"this",new Date(),2,1);
    Demo d3= new Demo(3,"is",new Date(),3,1);
    Demo d4= new Demo(4,"mytest",new Date(),4,1);
    //adding values to map
    map.put(d1.getKey(), d1);
    map.put(d2.getKey(), d2);
    map.put(d3.getKey(), d3);
    map.put(d4.getKey(), d4);
    //retrieving values from map
    Set<Integer> keySet= map.keySet();
    for(int i:keySet){
        System.out.println(map.get(i));
    }
    //searching key on map
    System.out.println(map.containsKey(d1.getKey()));
    //searching value on map
    System.out.println(map.containsValue(d1));
}

}
class Demo{
    private int key;
    private String message;
    private Date time;
    private int count;
    private int version;

    public Demo(int key,String message, Date time, int count, int version){
        this.key=key;
        this.message = message;
        this.time = time;
        this.count = count;
        this.version = version;
    }
    public String getMessage() {
        return message;
    }
    public Date getTime() {
        return time;
    }
    public int getCount() {
        return count;
    }
    public int getVersion() {
        return version;
    }
    public int getKey() {
        return key;
    }
    @Override
    public String toString() {
        return "Demo [message=" + message + ", time=" + time
                + ", count=" + count + ", version=" + version + "]";
    }

}

Web scraping with Python

Here is a simple web crawler, i used BeautifulSoup and we will search for all the links(anchors) who's class name is _3NFO0d. I used Flipkar.com, it is an online retailing store.

import requests
from bs4 import BeautifulSoup
def crawl_flipkart():
    url = 'https://www.flipkart.com/'
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text, "lxml")
    for link in soup.findAll('a', {'class': '_3NFO0d'}):
        href = link.get('href')
        print(href)

crawl_flipkart()

What is the ultimate postal code and zip regex?

use these regx

$ZIPREG=array(
    "US"=>"^\d{5}([\-]?\d{4})?$",
    "UK"=>"^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$",
    "DE"=>"\b((?:0[1-46-9]\d{3})|(?:[1-357-9]\d{4})|(?:[4][0-24-9]\d{3})|(?:[6][013-9]\d{3}))\b",
    "CA"=>"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$",
    "FR"=>"^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$",
    "IT"=>"^(V-|I-)?[0-9]{5}$",
    "AU"=>"^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$",
    "NL"=>"^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$",
    "ES"=>"^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$",
    "DK"=>"^([D|d][K|k]( |-))?[1-9]{1}[0-9]{3}$",
    "SE"=>"^(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}$",
    "BE"=>"^[1-9]{1}[0-9]{3}$",
    "IN"=>"^\d{6}$"
);

C# try catch continue execution

In your second function remove the e variable in the catch block then add throw.

This will carry over the generated exception the the final function and output it.

Its very common when you dont want your business logic code to throw exception but your UI.

json_encode() escaping forward slashes

On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -

my expected:

http://localhost/api/v1/admin/logs/testLog.log

would be encoded to:

http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log

If you need to do a comparison, transforming the url using:

addcslashes($url, '/')

allowed for the proper output during my comparisons.

Testing HTML email rendering

I've used most of them and can tell you that the best method is to test directly to each client. Once you are comfortable with sending you can send tests of your emails to gmail and if the design doesn't break then it's pretty safe on modern email clients.

You can check what is supported on which client here:

http://www.email-standards.org

Input type for HTML form for integer

<input type="number" step="1" ...

By adding the step attribute, you restrict input to integers.

Of course you should always validate on the server as well. Except under carefully controlled conditions, everything received from a client needs to be treated as suspect.

rsync: how can I configure it to create target directory on server?

The -R, --relative option will do this.

For example: if you want to backup /var/named/chroot and create the same directory structure on the remote server then -R will do just that.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

ConcurrentHashMap or ConcurrentLinkedQueue or ConcurrentSkipListMap may be another option, because they will never throw any ConcurrentModificationException, even if you remove or add item.

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

PHP Regex to get youtube video ID?

preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $url, $matches);

This will account for

youtube.com/v/{vidid}
youtube.com/vi/{vidid}
youtube.com/?v={vidid}
youtube.com/?vi={vidid}
youtube.com/watch?v={vidid}
youtube.com/watch?vi={vidid}
youtu.be/{vidid}

I improved it slightly to support: http://www.youtube.com/v/5xADESocujo?feature=autoshare&version=3&autohide=1&autoplay=1

The line I use now is:

preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $link, $matches);

make a header full screen (width) css

min-height: 100%;
position: relative;

What is `git push origin master`? Help with git's refs, heads and remotes

Or as a single command:

git push -u origin master:my_test

Pushes the commits from your local master branch to a (possibly new) remote branch my_test and sets up master to track origin/my_test.

How to activate a specific worksheet in Excel?

Would the following Macro help you?

Sub activateSheet(sheetname As String)
'activates sheet of specific name
    Worksheets(sheetname).Activate
End Sub

Basically you want to make use of the .Activate function. Or you can use the .Select function like so:

Sub activateSheet(sheetname As String)
'selects sheet of specific name
    Sheets(sheetname).Select
End Sub

Fixed header, footer with scrollable content

If you're targeting browsers supporting flexible boxes you could do the following.. http://jsfiddle.net/meyertee/AH3pE/

HTML

<div class="container">
    <header><h1>Header</h1></header>
    <div class="body">Body</div>
    <footer><h3>Footer</h3></footer>
</div>

CSS

.container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
}

header {
    flex-shrink: 0;
}
.body{
    flex-grow: 1;
    overflow: auto;
    min-height: 2em;
}
footer{
    flex-shrink: 0;
}

Update:
See "Can I use" for browser support of flexible boxes.

Cannot connect to MySQL 4.1+ using old authentication

If you do not have control of the server

I just had this issue, and was able to work around it.

First, connect to the MySQL database with an older client that doesn't mind old_passwords. Connect using the user that your script will be using.

Run these queries:

SET SESSION old_passwords=FALSE;
SET PASSWORD = PASSWORD('[your password]');

In your PHP script, change your mysql_connect function to include the client flag 1:

define('CLIENT_LONG_PASSWORD', 1);
mysql_connect('[your server]', '[your username]', '[your password]', false, CLIENT_LONG_PASSWORD);

This allowed me to connect successfully.

Edit: as per Garland Pope's comment, it may not be necessary to set CLIENT_LONG_PASSWORD manually any more in your PHP code as of PHP 5.4!

Edit: courtesy of Antonio Bonifati, a PHP script to run the queries for you:

<?php const DB = [ 'host' => '...', # localhost may not work on some hosting 
    'user' => '...',
    'pwd' => '...', ]; 

if (!mysql_connect(DB['host'], DB['user'], DB['pwd'])) {
    die(mysql_error());
} if (!mysql_query($query = 'SET SESSION old_passwords=FALSE')) {
    die($query);
} if (!mysql_query($query = "SET PASSWORD = PASSWORD('" . DB['pwd'] . "')")) {
    die($query);
}

echo "Excellent, mysqli will now work"; 
?>

Angular ng-if="" with multiple arguments

For people looking to do if statements with multiple 'or' values.

<div ng-if="::(a || b || c || d || e || f)"><div>

How to remove a column from an existing table?

Your example is simple and doesn’t require any additional table changes but generally speaking this is not so trivial.

If this column is referenced by other tables then you need to figure out what to do with other tables/columns. One option is to remove foreign keys and keep referenced data in other tables.

Another option is to find all referencing columns and remove them as well if they are not needed any longer.

In such cases the real challenge is finding all foreign keys. You can do this by querying system tables or using third party tools such as ApexSQL Search (free) or Red Gate Dependency tracker (premium but more features). There a whole thread on foreign keys here

How do I connect to an MDF database file?

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Samples\MyApp\C#\bin\Debug\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

this is working for me... Is there any way to short the path? like

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=\bin\Debug\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

How to save .xlsx data to file as a blob

This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx

/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */
chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });

how to get the host url using javascript from the current page

// will return the host name and port
var host = window.location.host; 

or possibly

var host = window.location.protocol + "//" + window.location.host;

or if you like concatenation

var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.host);

// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);

// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;

If you have or expect custom ports use window.location.host instead of window.location.hostname

SQL Server Configuration Manager not found

For SQL Server 2017 it is : C:\Windows\SysWOW64\SQLServerManager14.msc

For SQL Server 2016 it is : C:\Windows\SysWOW64\SQLServerManager13.msc

For SQL Server 2016 it is :C:\Windows\SysWOW64\SQLServerManager12.msc

and to add it back to the start menu, copy it from the original location provided above and paste it to

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft SQL Server 2017\Configuration Tools\

This would put back the configuration manager under start menu.

Source: How to open sql server configuration manager in windows 10?

Auto-click button element on page load using jQuery

I tried the following ways in first jQuery, then JavaScript:

jQuery:

 window.location.href = $(".contact").attr('href');
 $('.contactformone').trigger('click');  

This is the best way in JavaScript:

 document.getElementById("id").click();

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

SQL Error: ORA-12899: value too large for column

This answer still comes up high in the list for ORA-12899 and lot of non helpful comments above, even if they are old. The most helpful comment was #4 for any professional trying to find out why they are getting this when loading data.

Some characters are more than 1 byte in length, especially true on SQL Server. And what might fit in a varchar(20) in SQLServer won't fit into a similar varchar2(20) in Oracle.

I ran across this error yesterday with SSIS loading an Oracle database with the Attunity drivers and thought I would save folks some time.

Find column whose name contains a specific string

You also can use this code:

spike_cols =[x for x in df.columns[df.columns.str.contains('spike')]]

DateTime format to SQL format using C#

only you put "T"+DateTime.Now.ToLongTimeString()+ '2015-02-23'

Read only the first line of a file?

Lots of other answers here, but to answer precisely the question you asked (before @MarkAmery went and edited the original question and changed the meaning):

>>> f = open('myfile.txt')
>>> data = f.read()
>>> # I'm assuming you had the above before asking the question
>>> first_line = data.split('\n', 1)[0]

In other words, if you've already read in the file (as you said), and have a big block of data in memory, then to get the first line from it efficiently, do a split() on the newline character, once only, and take the first element from the resulting list.

Note that this does not include the \n character at the end of the line, but I'm assuming you don't want it anyway (and a single-line file may not even have one). Also note that although it's pretty short and quick, it does make a copy of the data, so for a really large blob of memory you may not consider it "efficient". As always, it depends...

How do I send a file as an email attachment using Linux command line?

None of the mutt ones worked for me. It was thinking the email address was part of the attachemnt. Had to do:

echo "This is the message body" | mutt -a "/path/to/file.to.attach" -s "subject of message" -- [email protected]

How to collapse blocks of code in Eclipse?

Preferences -> C++ -> Editor -> Folding ?

Make a right click in the editor window and go to preferences there, then only the editor-relevant section of the preferences dialog will appear. This works for JDT, CDT etc...

How to generate unique ID with node.js

Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random().

Math.random()

Mathematically, the chances of fractions being the same in a real space [0, 1] is theoretically 0. Probability-wise it is approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.

I call this the "Fractional-Unique-ID".

Wrote code to generate 1,000,000 Math.random() numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):

random_numbers = [] 
for (i = 0; i < 1000000; i++) { 
   random_numbers.push(Math.random()); 
   //random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16 
} 

if (i === 1000000) { 
   console.log("Before checking duplicate"); 
   console.log(random_numbers.length); 
   console.log("After checking duplicate"); 
   random_set = new Set(random_numbers); // Set removes duplicates
   console.log([...random_set].length); // length is still the same after removing
} 

How do I run a Python program in the Command Prompt in Windows 7?

I also found the same problem even though i've added the path in the environment variable. Finally, I put my "C:\Python27" in the FRONT part of the "PATH" in environment variable and after restarting the cmd, it works!!! I hope this can help.

What are the differences between git branch, fork, fetch, merge, rebase and clone?

Fork Vs. Clone - two words that both mean copy

Please see this diagram. (Originally from http://www.dataschool.io/content/images/2014/Mar/github1.png).

.-------------------------.     1. Fork     .-------------------------.
| Your GitHub repo        | <-------------- | Joe's GitHub repo       |
| github.com/you/coolgame |                 | github.com/joe/coolgame |
| ----------------------- | 7. Pull Request | ----------------------- |
| master -> c224ff7       | --------------> | master -> c224ff7 (c)   |
| anidea -> 884faa1 (a)   |                 | anidea -> 884faa1 (b)   |
'-------------------------'                 '-------------------------'
    |                 ^
    | 2. Clone        |
    |                 |
    |                 |
    |                 |
    |                 |
    |                 | 6. Push (anidea => origin/anidea)
    v                 |
.-------------------------.
| Your computer           |  3. Create branch 'anidea'
| $HOME/coolgame          |
| ----------------------- |  4. Update a file
| master -> c224ff7       |
| anidea -> 884faa1       |  5. Commit (to 'anidea')
'-------------------------'

(a) - after you have pushed it
(b) - after Joe has accepted it
(c) - eventually Joe might merge 'anidea' (make 'master -> 884faa1')

Fork

  • A copy to your remote repo (cloud) that links it to Joe's
  • A copy you can then clone to your local repo and F*%$-up
  • When you are done you can push back to your remote
  • You can then ask Joe if he wants to use it in his project by clicking pull-request

Clone

  • a copy to your local repo (harddrive)

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

The NVARCHAR2 datatype was introduced by Oracle for databases that want to use Unicode for some columns while keeping another character set for the rest of the database (which uses VARCHAR2). The NVARCHAR2 is a Unicode-only datatype.

One reason you may want to use NVARCHAR2 might be that your DB uses a non-Unicode character set and you still want to be able to store Unicode data for some columns without changing the primary character set. Another reason might be that you want to use two Unicode character set (AL32UTF8 for data that comes mostly from western Europe, AL16UTF16 for data that comes mostly from Asia for example) because different character sets won't store the same data equally efficiently.

Both columns in your example (Unicode VARCHAR2(10 CHAR) and NVARCHAR2(10)) would be able to store the same data, however the byte storage will be different. Some strings may be stored more efficiently in one or the other.

Note also that some features won't work with NVARCHAR2, see this SO question:

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

Declaring variables inside loops, good practice or bad practice?

It's a very good practice, as all above answer provide very good theoretical aspect of the question let me give a glimpse of code, i was trying to solve DFS over GEEKSFORGEEKS, i encounter the optimization problem...... If you try to solve the code declaring the integer outside the loop will give you Optimization Error..

stack<int> st;
st.push(s);
cout<<s<<" ";
vis[s]=1;
int flag=0;
int top=0;
while(!st.empty()){
    top = st.top();
    for(int i=0;i<g[top].size();i++){
        if(vis[g[top][i]] != 1){
            st.push(g[top][i]);
            cout<<g[top][i]<<" ";
            vis[g[top][i]]=1;
            flag=1;
            break;
        }
    }
    if(!flag){
        st.pop();
    }
}

Now put integers inside the loop this will give you correct answer...

stack<int> st;
st.push(s);
cout<<s<<" ";
vis[s]=1;
// int flag=0;
// int top=0;
while(!st.empty()){
    int top = st.top();
    int flag = 0;
    for(int i=0;i<g[top].size();i++){
        if(vis[g[top][i]] != 1){
            st.push(g[top][i]);
            cout<<g[top][i]<<" ";
            vis[g[top][i]]=1;
            flag=1;
            break;
        }
    }
    if(!flag){
        st.pop();
    }
}

this completely reflect what sir @justin was saying in 2nd comment.... try this here https://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1. just give it a shot.... you will get it.Hope this help.

What is an .axd file?

An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files. AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.

How to combine two vectors into a data frame

df = data.frame(cond=c(rep("x",3),rep("y",3)),rating=c(x,y))

Linq Query Group By and Selecting First Items

See LINQ: How to get the latest/last record with a group by clause

var firstItemsInGroup = from b in mainButtons
                 group b by b.category into g
select g.First();

I assume that mainButtons are already sorted correctly.

If you need to specify custom sort order, use OrderBy override with Comparer.

var firstsByCompareInGroups = from p in rows
        group p by p.ID into grp
        select grp.OrderBy(a => a, new CompareRows()).First();

See an example in my post "Select First Row In Group using Custom Comparer"

Facebook share link - can you customize the message body text?

NOTE: @azure_ardee solution is no longer feasible. Facebook will not allow developers pre-fill messages. Developers may customize the story by providing OG meta tags, but it's up to the user to fill the message.

This is only possible if you are posting on the user's behalf, which requires the user authorizing your application with the publish_actions permission. AND even then:

please note that Facebook recommends using a user-initiated sharing modal.


Have a look at this answer.

Could not resolve Spring property placeholder

the following property must be added in the gradle.build file

processResources {
    filesMatching("**/*.properties") {
        expand project.properties
    }
}

Additionally, if working with Intellij, the project must be re-imported.

How to put/get multiple JSONObjects to JSONArray?

From android API Level 19, when I want to instance JSONArray object I put JSONObject directly as parameter like below:

JSONArray jsonArray=new JSONArray(jsonObject);

JSONArray has constructor to accept object.

List of macOS text editors and code editors

TextMate not for "advanced programmers". That does not make sense, TextMate contains everything an "advanced programmer" would want. It allows them to define a bundle that allows them to quickly set up the way they want their source code formatted, or one that follows the project guidelines, quick easy access to create entire structures and classes based on typing part of a construct and hitting tab.

TextMate is my tool of choice, it is fast, lightweight and yet contains all of the features I would want in a tool to program with. While it is not tightly integrated in Xcode, that is not a problem for me as I don't write software for Mac OS X. I write software for FreeBSD.

Google MAP API v3: Center & Zoom on displayed markers

for center and auto zoom on display markers

// map: an instance of google.maps.Map object

// latlng_points_array: an array of google.maps.LatLng objects

var latlngbounds = new google.maps.LatLngBounds( );

    for ( var i = 0; i < latlng_points_array.length; i++ ) {
        latlngbounds.extend( latlng_points_array[i] );
    }

map.fitBounds( latlngbounds );

How do I get the XML root node with C#?

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
string rootNode = XmlDoc.ChildNodes[0].Name;

Close popup window

In my case, I just needed to close my pop-up and redirect the user to his profile page when he clicks "ok" after reading some message I tried with a few hacks, including setTimeout + self.close(), but with IE, this was closing the whole tab...

Solution : I replaced my link with a simple submit button.
<button type="submit" onclick="window.location.href='profile.html';">buttonText</button>. Nothing more.

This may sound stupid, but I didn't think to such a simple solution, since my pop-up did not have any form.

I hope it will help some front-end noobs like me !

How do I force a favicon refresh?

Please follow below steps to change app icon:

  1. Add your .ico file in the project.
  2. Go to angular.json and in that "projects" -> "architect" -> "build" -> "options" -> "assets" and here make an entry for your icon file. Refer to the existing entry of favicon.ico to know how to do it.
  3. Go to index.html and update the path of the icon file. For example,

_x000D_
_x000D_
<link rel="icon" type="image/x-icon" href="abc.ico">
_x000D_
_x000D_
_x000D_

Alternatively, rename your icon file with favicon.ico and replace it in the directory.

  1. Restart the server.
  2. Hard refresh browser and you are good to go.

How do I create and access the global variables in Groovy?

def sum = 0

// This method stores a value in a global variable.
def add =
{ 
    input1 , input2 ->
    sum = input1 + input2;
}

// This method uses stored value.
def multiplySum =   
{
    input1 ->
        return sum*input1;
}

add(1,2);
multiplySum(10);

How to generate different random numbers in a loop in C++?

Don't use srand inside the loop, use it only once, e.g. at the start of main(). And srand() is exactly how you reset this.

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);

PHP is not recognized as an internal or external command in command prompt

Is your path correctly configured?

In Windows, you can do that as described here:

http://www.computerhope.com/issues/ch000549.htm

How to get an object's properties in JavaScript / jQuery?

i) what is the difference between these two objects

The simple answer is that [object] indicates a host object that has no internal class. A host object is an object that is not part of the ECMAScript implementation you're working with, but is provided by the host as an extension. The DOM is a common example of host objects, although in most newer implementations DOM objects inherit from the native Object and have internal class names (such as HTMLElement, Window, etc). IE's proprietary ActiveXObject is another example of a host object.

[object] is most commonly seen when alerting DOM objects in Internet Explorer 7 and lower, since they are host objects that have no internal class name.

ii) what type of Object is this

You can get the "type" (internal class) of object using Object.prototype.toString. The specification requires that it always returns a string in the format [object [[Class]]], where [[Class]] is the internal class name such as Object, Array, Date, RegExp, etc. You can apply this method to any object (including host objects), using

Object.prototype.toString.apply(obj);

Many isArray implementations use this technique to discover whether an object is actually an array (although it's not as robust in IE as it is in other browsers).


iii) what all properties does this object contains and values of each property

In ECMAScript 3, you can iterate over enumerable properties using a for...in loop. Note that most built-in properties are non-enumerable. The same is true of some host objects. In ECMAScript 5, you can get an array containing the names of all non-inherited properties using Object.getOwnPropertyNames(obj). This array will contain non-enumerable and enumerable property names.

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

Add System.Web.Extensions as a reference to your project

enter image description here

For Ref.

How to trigger an event after using event.preventDefault()

as long as "lots of stuff" isn't doing something asynchronous this is absolutely unneccessary - the event will call every handler on his way in sequence, so if theres a onklick-event on a parent-element this will fire after the onclik-event of the child has processed completely. javascript doesn't do some kind of "multithreading" here that makes "stopping" the event processing neccessary. conclusion: "pausing" an event just to resume it in the same handler doesn't make any sense.

if "lots of stuff" is something asynchronous this also doesn't make sense as it prevents the asynchonous things to do what they should do (asynchonous stuff) and make them bahave like everything is in sequence (where we come back to my first paragraph)

How do I find the PublicKeyToken for a particular dll?

sn -T <assembly> in Visual Studio command line. If an assembly is installed in the global assembly cache, it's easier to go to C:\Windows\assembly and find it in the list of GAC assemblies.

On your specific case, you might be mixing type full name with assembly reference, you might want to take a look at MSDN.

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

Setting an int to Infinity in C++

This is a message for me in the future:

Just use: (unsigned)!((int)0)

It creates the largest possible number in any machine by assigning all bits to 1s (ones) and then casts it to unsigned

Even better

#define INF (unsigned)!((int)0)

And then just use INF in your code

AngularJS : automatically detect change in model

And if you need to style your form elements according to it's state (modified/not modified) dynamically or to test whether some values has actually changed, you can use the following module, developed by myself: https://github.com/betsol/angular-input-modified

It adds additional properties and methods to the form and it's child elements. With it, you can test whether some element contains new data or even test if entire form has new unsaved data.

You can setup the following watch: $scope.$watch('myForm.modified', handler) and your handler will be called if some form elements actually contains new data or if it reversed to initial state.

Also, you can use modified property of individual form elements to actually reduce amount of data sent to a server via AJAX call. There is no need to send unchanged data.

As a bonus, you can revert your form to initial state via call to form's reset() method.

You can find the module's demo here: http://plnkr.co/edit/g2MDXv81OOBuGo6ORvdt?p=preview

Cheers!

\r\n, \r and \n what is the difference between them?

A carriage return (\r) makes the cursor jump to the first column (begin of the line) while the newline (\n) jumps to the next line and eventually to the beginning of that line. So to be sure to be at the first position within the next line one uses both.

How can I divide two integers stored in variables in Python?

x / y

quotient of x and y

x // y 

(floored) quotient of x and y

How to delete and update a record in Hive

UPDATE or DELETE a record isn't allowed in Hive, but INSERT INTO is acceptable.
A snippet from Hadoop: The Definitive Guide(3rd edition):

Updates, transactions, and indexes are mainstays of traditional databases. Yet, until recently, these features have not been considered a part of Hive's feature set. This is because Hive was built to operate over HDFS data using MapReduce, where full-table scans are the norm and a table update is achieved by transforming the data into a new table. For a data warehousing application that runs over large portions of the dataset, this works well.

Hive doesn't support updates (or deletes), but it does support INSERT INTO, so it is possible to add new rows to an existing table.

PreparedStatement with list of parameters in a IN clause

public static void main(String arg[]) {

    Connection connection = ConnectionManager.getConnection(); 
    PreparedStatement pstmt = null;
          //if the field values are in ArrayList
        List<String> fieldList = new ArrayList();

    try {

        StringBuffer sb = new StringBuffer();  

        sb.append("  SELECT *            \n");
        sb.append("   FROM TEST          \n");
        sb.append("  WHERE FIELD IN (    \n");

        for(int i = 0; i < fieldList.size(); i++) {
            if(i == 0) {
                sb.append("    '"+fieldList.get(i)+"'   \n");
            } else {
                sb.append("   ,'"+fieldList.get(i)+"'   \n");
            }
        }
        sb.append("             )     \n");

        pstmt = connection.prepareStatement(sb.toString());
        pstmt.executeQuery();

    } catch (SQLException se) {
        se.printStackTrace();
    }

}

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

I have a solution to a problem that may also apply to you. My database was in a state where a DROP TABLE failed because it couldn't find the table... but a CREATE TABLE also failed because MySQL thought the table existed. (This state could easily mess with your IF NOT EXISTS clause).

I eventually found this solution:

sudo mysqladmin flush-tables

For me, without the sudo, I got the following error:

mysqladmin: refresh failed; error: 'Access denied; you need the RELOAD privilege for this operation'

(Running on OS X 10.6)

What does the Ellipsis object do?

Its intended use shouldn't be only for these 3rd party modules. It isn't mentioned properly in the Python documentation (or maybe I just couldn't find that) but the ellipsis ... is actually used in CPython in at least one place.

It is used for representing infinite data structures in Python. I came upon this notation while playing around with lists.

See this question for more info.

Proper way to restrict text input values (e.g. only numbers)

I use this one:


import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';

@Directive({
    selector: '[ngModel][onlyNumber]',
    host: {
        "(input)": 'onInputChange($event)'
    }
})
export class OnlyNumberDirective {

    @Input() onlyNumber: boolean;
    @Output() ngModelChange: EventEmitter<any> = new EventEmitter()

    constructor(public el: ElementRef) {
    }

    public onInputChange($event){
        if ($event.target.value == '-') {
            return;
        }

        if ($event.target.value && $event.target.value.endsWith('.')) {
            return;
        }

        $event.target.value = this.parseNumber($event.target.value);
        $event.target.dispatchEvent(new Event('input'));
    }

    @HostListener('blur', ['$event'])
    public onBlur(event: Event) {
        if (!this.onlyNumber) {
            return;
        }

        this.el.nativeElement.value = this.parseNumber(this.el.nativeElement.value);
        this.el.nativeElement.dispatchEvent(new Event('input'));
    }

    private parseNumber(input: any): any {
        let trimmed = input.replace(/[^0-9\.-]+/g, '');
        let parsedNumber = parseFloat(trimmed);

        return !isNaN(parsedNumber) ? parsedNumber : '';
    }

}

and usage is following

<input onlyNumbers="true" ... />

Cutting the videos based on start and end time using ffmpeg

You probably do not have a keyframe at the 3 second mark. Because non-keyframes encode differences from other frames, they require all of the data starting with the previous keyframe.

With the mp4 container it is possible to cut at a non-keyframe without re-encoding using an edit list. In other words, if the closest keyframe before 3s is at 0s then it will copy the video starting at 0s and use an edit list to tell the player to start playing 3 seconds in.

If you are using the latest ffmpeg from git master it will do this using an edit list when invoked using the command that you provided. If this is not working for you then you are probably either using an older version of ffmpeg, or your player does not support edit lists. Some players will ignore the edit list and always play all of the media in the file from beginning to end.

If you want to cut precisely starting at a non-keyframe and want it to play starting at the desired point on a player that does not support edit lists, or want to ensure that the cut portion is not actually in the output file (for example if it contains confidential information), then you can do that by re-encoding so that there will be a keyframe precisely at the desired start time. Re-encoding is the default if you do not specify copy. For example:

ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4

When re-encoding you may also wish to include additional quality-related options or a particular AAC encoder. For details, see ffmpeg's x264 Encoding Guide for video and AAC Encoding Guide for audio.

Also, the -t option specifies a duration, not an end time. The above command will encode 8s of video starting at 3s. To start at 3s and end at 8s use -t 5. If you are using a current version of ffmpeg you can also replace -t with -to in the above command to end at the specified time.

Validating with an XML schema in Python

lxml provides etree.DTD

from the tests on http://lxml.de/api/lxml.tests.test_dtd-pysrc.html

...
root = etree.XML(_bytes("<b/>")) 
dtd = etree.DTD(BytesIO("<!ELEMENT b EMPTY>")) 
self.assert_(dtd.validate(root)) 

How to detect orientation change?

Here is an easy way to detect the device orientation: (Swift 3)

override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
            handleViewRotaion(orientation: toInterfaceOrientation)
        }

    //MARK: - Rotation controls
    func handleViewRotaion(orientation:UIInterfaceOrientation) -> Void {
        switch orientation {
        case .portrait :
            print("portrait view")
            break
        case .portraitUpsideDown :
            print("portraitUpsideDown view")
            break
        case .landscapeLeft :
            print("landscapeLeft view")
            break
        case .landscapeRight :
            print("landscapeRight view")
            break
        case .unknown :
            break
        }
    }

MS SQL 2008 - get all table names and their row counts in a DB

SELECT sc.name +'.'+ ta.name TableName
 ,SUM(pa.rows) RowCnt
 FROM sys.tables ta
 INNER JOIN sys.partitions pa
 ON pa.OBJECT_ID = ta.OBJECT_ID
 INNER JOIN sys.schemas sc
 ON ta.schema_id = sc.schema_id
 WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
 GROUP BY sc.name,ta.name
 ORDER BY SUM(pa.rows) DESC

See this:

How to implement an android:background that doesn't stretch?

The key is to set the drawable as the image of the button, not as a background. Like this:

rb.setButtonDrawable(R.drawable.whatever_drawable);

Rename multiple files in a directory in Python

This works for me.

import os
for afile in os.listdir('.'):
    filename, file_extension = os.path.splitext(afile)
    if not file_extension == '.xyz':
        os.rename(afile, filename + '.abc')

Disable ONLY_FULL_GROUP_BY

    mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    mysql> exit;

What are the uses of the exec command in shell scripts?

Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec.

If you're still here, the following discussion should hopefully reveal why. When you run, say,

sh -c 'command'

you run a sh instance, then start command as a child of that sh instance. When command finishes, the sh instance also finishes.

sh -c 'exec command'

runs a sh instance, then replaces that sh instance with the command binary, and runs that instead.

Of course, both of these are useless in this limited context; you simply want

command

There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command. This is pretty much the sole situation where exec command is useful.

#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command

This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh instance with the command process, rather than have sh run it as a child process and wait for it, then exit as soon as it finishes.

Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec that command as an optimization.

If something forces you to run sh but you really wanted to run something else, exec something else is of course a workaround to replace the undesired sh instance (like for example if you really wanted to run your own spiffy gosh instead of sh but yours isn't listed in /etc/shells so you can't specify it as your login shell).

The second use of exec to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec is followed by a redirect instead of a command name.

Return in Scala

It's not as simple as just omitting the return keyword. In Scala, if there is no return then the last expression is taken to be the return value. So, if the last expression is what you want to return, then you can omit the return keyword. But if what you want to return is not the last expression, then Scala will not know that you wanted to return it.

An example:

def f() = {
  if (something)
    "A"
  else
    "B"
}

Here the last expression of the function f is an if/else expression that evaluates to a String. Since there is no explicit return marked, Scala will infer that you wanted to return the result of this if/else expression: a String.

Now, if we add something after the if/else expression:

def f() = {
  if (something)
    "A"
  else
    "B"

  if (somethingElse)
    1
  else
    2
}

Now the last expression is an if/else expression that evaluates to an Int. So the return type of f will be Int. If we really wanted it to return the String, then we're in trouble because Scala has no idea that that's what we intended. Thus, we have to fix it by either storing the String to a variable and returning it after the second if/else expression, or by changing the order so that the String part happens last.

Finally, we can avoid the return keyword even with a nested if-else expression like yours:

def f() = {
  if(somethingFirst) {
    if (something)      // Last expression of `if` returns a String
     "A"
    else
     "B"
  }
  else {
    if (somethingElse)
      1
    else
      2

    "C"                // Last expression of `else` returns a String
  }

}

Shortest distance between a point and a line segment

In F#, the distance from the point c to the line segment between a and b is given by:

let pointToLineSegmentDistance (a: Vector, b: Vector) (c: Vector) =
  let d = b - a
  let s = d.Length
  let lambda = (c - a) * d / s
  let p = (lambda |> max 0.0 |> min s) * d / s
  (a + p - c).Length

The vector d points from a to b along the line segment. The dot product of d/s with c-a gives the parameter of the point of closest approach between the infinite line and the point c. The min and max function are used to clamp this parameter to the range 0..s so that the point lies between a and b. Finally, the length of a+p-c is the distance from c to the closest point on the line segment.

Example use:

pointToLineSegmentDistance (Vector(0.0, 0.0), Vector(1.0, 0.0)) (Vector(-1.0, 1.0))

Powershell: A positional parameter cannot be found that accepts argument "xxx"

I had this issue after converting my Write-Host cmdlets to Write-Information and I was missing quotes and parens around the parameters. The cmdlet signatures are evidently not the same.

Write-Host this is a good idea $here
Write-Information this is a good idea $here <=BAD

This is the cmdlet signature that corrected after spending 20-30 minutes digging down the function stack...

Write-Information ("this is a good idea $here") <=GOOD

text flowing out of div

You need to apply the following CSS property to the container block (div):

overflow-wrap: break-word;

According to the specifications (source CSS | MDN):

The overflow-wrap CSS property specifies whether or not the browser should insert line breaks within words to prevent text from overflowing its content box.

With the value set to break-word

To prevent overflow, normally unbreakable words may be broken at arbitrary points if there are no otherwise acceptable break points in the line.

Worth mentioning...

The property was originally a nonstandard and unprefixed Microsoft extension called word-wrap, and was implemented by most browsers with the same name. It has since been renamed to overflow-wrap, with word-wrap being an alias.


If you care about legacy browsers support it's worth specifying both:

word-wrap    : break-word;
overflow-wrap: break-word;

Ex. IE9 does not recognize overflow-wrap but works fine with word-wrap

SyntaxError: cannot assign to operator

Python is upset because you are attempting to assign a value to something that can't be assigned a value.

((t[1])/length) * t[1] += string

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn't a "container".

Based on what you've written, you're just misunderstanding how this operator works. Just switch your operands, like so.

string += str(((t[1])/length) * t[1])

Note that I've wrapped the assigned value in str in order to convert it into a str so that it is compatible with the string variable it is being assigned to. (Numbers and strings can't be added together.)

oracle.jdbc.driver.OracleDriver ClassNotFoundException

try to add ojdbc6.jar or other version through the server lib "C:\apache-tomcat-7.0.47\lib",

Then restart the server in eclipse.

MongoDB relationships: embed or reference?

In general, embed is good if you have one-to-one or one-to-many relationships between entities, and reference is good if you have many-to-many relationships.

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

Python dictionary: Get list of values for list of keys

A couple of other ways than list-comp:

  • Build list and throw exception if key not found: map(mydict.__getitem__, mykeys)
  • Build list with None if key not found: map(mydict.get, mykeys)

Alternatively, using operator.itemgetter can return a tuple:

from operator import itemgetter
myvalues = itemgetter(*mykeys)(mydict)
# use `list(...)` if list is required

Note: in Python3, map returns an iterator rather than a list. Use list(map(...)) for a list.

How can I convert JSON to CSV?

With the pandas library, this is as easy as using two commands!

pandas.read_json()

To convert a JSON string to a pandas object (either a series or dataframe). Then, assuming the results were stored as df:

df.to_csv()

Which can either return a string or write directly to a csv-file.

Based on the verbosity of previous answers, we should all thank pandas for the shortcut.

How to calculate cumulative normal distribution?

Simple like this:

import math
def my_cdf(x):
    return 0.5*(1+math.erf(x/math.sqrt(2)))

I found the formula in this page https://www.danielsoper.com/statcalc/formulas.aspx?id=55

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

This error shows when you add component declaration in imports: [] instead of declarations: [], e.g:

declarations: [
  AppComponent,
],
imports: [
  BrowserModule,
  AppRoutingModule,
  SomeComponent <-----------wrong
],

Angular.js directive dynamic templateURL

Thanks to @pgregory, I could resolve my problem using this directive for inline editing

.directive("superEdit", function($compile){
    return{
        link: function(scope, element, attrs){
            var colName = attrs["superEdit"];
            alert(colName);

            scope.getContentUrl = function() {
                if (colName == 'Something') {
                    return 'app/correction/templates/lov-edit.html';
                }else {
                    return 'app/correction/templates/simple-edit.html';
                }
            }

            var template = '<div ng-include="getContentUrl()"></div>';

            var linkFn = $compile(template);
            var content = linkFn(scope);
            element.append(content);
        }
    }
})

Displaying the Error Messages in Laravel after being Redirected from controller

@if ($errors->has('category'))
    <span class="error">{{ $errors->first('category') }}</span>
@endif

Android getText from EditText field

Try this -

EditText myEditText =  (EditText) findViewById(R.id.vnosEmaila);

String text = myEditText.getText().toString();

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

I was getting this problem when using IBM RSA 9.6.1 when building a brand new development machine. The problem for me ended up being because of HTTPS on the Global Maven repository. My solution was to create a Maven settings.xml that forced it to use HTTP.

The key to me was that the central repository was empty when I exploded it under Maven Repositories -- > Global Repositories

Using the following settings file worked for me:

<settings>
  <activeProfiles>
    <!--make the profile active all the time -->
    <activeProfile>insecurecentral</activeProfile>
  </activeProfiles>
  <profiles>
    <profile>
      <id>insecurecentral</id>
      <!--Override the repository (and pluginRepository) "central" from the Maven Super POM -->
      <repositories>
        <repository>
          <id>central</id>
          <url>http://repo.maven.apache.org/maven2</url>
          <releases>
            <enabled>true</enabled>
          </releases>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>central</id>
          <url>http://repo.maven.apache.org/maven2</url>
          <releases>
            <enabled>true</enabled>
          </releases>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
</settings>

I got the idea from this stackoverflow question.

Forward slash in Java Regex

The problem is actually that you need to double-escape backslashes in the replacement string. You see, "\\/" (as I'm sure you know) means the replacement string is \/, and (as you probably don't know) the replacement string \/ actually just inserts /, because Java is weird, and gives \ a special meaning in the replacement string. (It's supposedly so that \$ will be a literal dollar sign, but I think the real reason is that they wanted to mess with people. Other languages don't do it this way.) So you have to write either:

"Hello/You/There".replaceAll("/", "\\\\/");

or:

"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));

(Using java.util.regex.Matcher.quoteReplacement(String).)

DataTables: Cannot read property style of undefined

In my case, I was updating the server-sided datatable twice and it gives me this error. Hope it helps someone.

Equivalent function for DATEADD() in Oracle

--ORACLE SQL EXAMPLE
SELECT
SYSDATE
,TO_DATE(SUBSTR(LAST_DAY(ADD_MONTHS(SYSDATE, -1)),1,10),'YYYY-MM-DD')
FROM DUAL

How to emulate a do-while loop in Python?

My code below might be a useful implementation, highlighting the main difference between vs as I understand it.

So in this one case, you always go through the loop at least once.

first_pass = True
while first_pass or condition:
    first_pass = False
    do_stuff()

How to grep, excluding some patterns?

Another solution without chaining grep:

egrep '(^|[^g])loom' ~/projects/**/trunk/src/**/*.@(h|cpp)

Between brackets, you exclude the character g before any occurrence of loom, unless loom is the first chars of the line.

nginx: [emerg] "server" directive is not allowed here

The path to the nginx.conf file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf.

You may access and edit this file by typing this at the terminal

cd /etc/nginx

/etc/nginx$ sudo nano nginx.conf

Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.

I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf file which is the primary Configuration file for Nginx.

Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d . Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-

http{
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

Further to this you may comment out from the PRIMARY Config file , the line

http{
    #include /etc/nginx/sites-available/some_file.conf; # Comment Out 
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

and need not keep any Config Files in /etc/nginx/sites-available/ and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/ , kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .

EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/ , this was the older practice and is DEPRECIATED now .

Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf; .

Quote from Nginx CookBook page - 5 .

"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."

c++ boost split string

My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:

-----------test2-------test3

What happened is the machine actually printed this:

test-------test2-------test3\r-------

That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).

Removing body margin in CSS

The right answer for this question is "css reset".

* {
    margin: 0;
    padding: 0;
}

It removes all default margin and padding for every object on the page, no holds barred, regardless of browser.

Alter column, add default constraint

Try this

alter table TableName 
 add constraint df_ConstraintNAme 
 default getutcdate() for [Date]

example

create table bla (id int)

alter table bla add constraint dt_bla default 1 for id



insert bla default values

select * from bla

also make sure you name the default constraint..it will be a pain in the neck to drop it later because it will have one of those crazy system generated names...see also How To Name Default Constraints And How To Drop Default Constraint Without A Name In SQL Server

Does my application "contain encryption"?

All of this can be very confusing for an app developer that's simply using TLS to connect to their own web servers. Because ATS (App Transport Security) is becoming more important and we are encouraged to convert everything to https - I think more developers are going to encounter this issue.

My app simply exchanges data between our server and the user using the https protocol. Seeing the words "USES ENCRYPTION" in the disclaimers is a bit scary so I gave the US government office a call at their office and spoke to a representative of the Bureau of Industry and Security (BIS) http://www.bis.doc.gov/index.php/about-bis/contact-bis.

The representative asked me about my app and since it passed the "primary function test" in that it had nothing to do with security/communications and simply uses https as a channel for connecting my customer data to our servers - it fell in the EAR99 category which means it's exempt from getting government permission (see https://www.bis.doc.gov/index.php/licensing/commerce-control-list-classification/export-control-classification-number-eccn)

I hope this helps other app developers.

Can't connect to MySQL server error 111

It probably means that your MySQL server is only listening the localhost interface.

If you have lines like this :

bind-address = 127.0.0.1

In your my.cnf configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.

sudo service mysql restart

Of course, to do this, you must be the administrator of the server.

replace NULL with Blank value or Zero in sql server

Try This

SELECT Title  from #Movies
    SELECT CASE WHEN Title = '' THEN 'No Title' ELSE Title END AS Titile from #Movies

OR

SELECT [Id], [CategoryId], ISNULL(nullif(Title,''),'No data') as Title, [Director], [DateReleased] FROM #Movies

Get first n characters of a string

$width = 10;

$a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);

or with wordwrap

$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);

/bin/sh: pushd: not found

sudo dpkg-reconfigure dash 

Then select no.

Plot different DataFrames in the same figure

To do this for multiple dataframes, you can do a for loop over them:

fig = plt.figure(num=None, figsize=(10, 8))
ax = dict_of_dfs['FOO'].column.plot()
for BAR in dict_of_dfs.keys():
    if BAR == 'FOO':
        pass
    else:
        dict_of_dfs[BAR].column.plot(ax=ax)

Generate a heatmap in MatPlotLib using a scatter data set

Instead of using np.hist2d, which in general produces quite ugly histograms, I would like to recycle py-sphviewer, a python package for rendering particle simulations using an adaptive smoothing kernel and that can be easily installed from pip (see webpage documentation). Consider the following code, which is based on the example:

import numpy as np
import numpy.random
import matplotlib.pyplot as plt
import sphviewer as sph

def myplot(x, y, nb=32, xsize=500, ysize=500):   
    xmin = np.min(x)
    xmax = np.max(x)
    ymin = np.min(y)
    ymax = np.max(y)

    x0 = (xmin+xmax)/2.
    y0 = (ymin+ymax)/2.

    pos = np.zeros([len(x),3])
    pos[:,0] = x
    pos[:,1] = y
    w = np.ones(len(x))

    P = sph.Particles(pos, w, nb=nb)
    S = sph.Scene(P)
    S.update_camera(r='infinity', x=x0, y=y0, z=0, 
                    xsize=xsize, ysize=ysize)
    R = sph.Render(S)
    R.set_logscale()
    img = R.get_image()
    extent = R.get_extent()
    for i, j in zip(xrange(4), [x0,x0,y0,y0]):
        extent[i] += j
    print extent
    return img, extent
    
fig = plt.figure(1, figsize=(10,10))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)


# Generate some test data
x = np.random.randn(1000)
y = np.random.randn(1000)

#Plotting a regular scatter plot
ax1.plot(x,y,'k.', markersize=5)
ax1.set_xlim(-3,3)
ax1.set_ylim(-3,3)

heatmap_16, extent_16 = myplot(x,y, nb=16)
heatmap_32, extent_32 = myplot(x,y, nb=32)
heatmap_64, extent_64 = myplot(x,y, nb=64)

ax2.imshow(heatmap_16, extent=extent_16, origin='lower', aspect='auto')
ax2.set_title("Smoothing over 16 neighbors")

ax3.imshow(heatmap_32, extent=extent_32, origin='lower', aspect='auto')
ax3.set_title("Smoothing over 32 neighbors")

#Make the heatmap using a smoothing over 64 neighbors
ax4.imshow(heatmap_64, extent=extent_64, origin='lower', aspect='auto')
ax4.set_title("Smoothing over 64 neighbors")

plt.show()

which produces the following image:

enter image description here

As you see, the images look pretty nice, and we are able to identify different substructures on it. These images are constructed spreading a given weight for every point within a certain domain, defined by the smoothing length, which in turns is given by the distance to the closer nb neighbor (I've chosen 16, 32 and 64 for the examples). So, higher density regions typically are spread over smaller regions compared to lower density regions.

The function myplot is just a very simple function that I've written in order to give the x,y data to py-sphviewer to do the magic.

How does the FetchMode work in Spring Data JPA

Spring-jpa creates the query using the entity manager, and Hibernate will ignore the fetch mode if the query was built by the entity manager.

The following is the work around that I used:

  1. Implement a custom repository which inherits from SimpleJpaRepository

  2. Override the method getQuery(Specification<T> spec, Sort sort):

    @Override
    protected TypedQuery<T> getQuery(Specification<T> spec, Sort sort) { 
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> query = builder.createQuery(getDomainClass());
    
        Root<T> root = applySpecificationToCriteria(spec, query);
        query.select(root);
    
        applyFetchMode(root);
    
        if (sort != null) {
            query.orderBy(toOrders(sort, root, builder));
        }
    
        return applyRepositoryMethodMetadata(entityManager.createQuery(query));
    }
    

    In the middle of the method, add applyFetchMode(root); to apply the fetch mode, to make Hibernate create the query with the correct join.

    (Unfortunately we need to copy the whole method and related private methods from the base class because there was no other extension point.)

  3. Implement applyFetchMode:

    private void applyFetchMode(Root<T> root) {
        for (Field field : getDomainClass().getDeclaredFields()) {
    
            Fetch fetch = field.getAnnotation(Fetch.class);
    
            if (fetch != null && fetch.value() == FetchMode.JOIN) {
                root.fetch(field.getName(), JoinType.LEFT);
            }
        }
    }
    

How can I find the link URL by link text with XPath?

Too late for you, but for anyone else with the same question...

//a[contains(text(), 'programming')]/@href

Of course, 'programming' can be any text fragment.

How to search for a string inside an array of strings

It's as simple as iterating the array and looking for the regexp

function searchStringInArray (str, strArray) {
    for (var j=0; j<strArray.length; j++) {
        if (strArray[j].match(str)) return j;
    }
    return -1;
}

Edit - make str as an argument to function.

Go Back to Previous Page

Depends what it is that you're trying to do it with. You could use something like this:

echo "<a href=\"javascript:history.go(-1)\">GO BACK</a>";

That's the simplest option. The other poster is right about having a proper flow of history but this is an example for you.

Just edited, orig version wasn't indented and looked like nothing. ;)

Synchronous request in Node.js

This code can be used to execute an array of promises synchronously & sequentially after which you can execute your final code in the .then() call.

const allTasks = [() => promise1, () => promise2, () => promise3];

function executePromisesSync(tasks) {
  return tasks.reduce((task, nextTask) => task.then(nextTask), Promise.resolve());
}

executePromisesSync(allTasks).then(
  result => console.log(result),
  error => console.error(error)
);

How to get cumulative sum

The latest version of SQL Server (2012) permits the following.

SELECT 
    RowID, 
    Col1,
    SUM(Col1) OVER(ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId

or

SELECT 
    GroupID, 
    RowID, 
    Col1,
    SUM(Col1) OVER(PARTITION BY GroupID ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId

This is even faster. Partitioned version completes in 34 seconds over 5 million rows for me.

Thanks to Peso, who commented on the SQL Team thread referred to in another answer.

How to create timer in angular2

Set Timer and auto call service after certain time
// Initialize from ngInit
ngOnInit(): void {this.getNotifications();}

getNotifications() {
    setInterval(() => {this.getNewNotifications();
    }, 60000);  // 60000 milliseconds interval 
}
getNewNotifications() {
    this.notifyService.getNewNotifications().subscribe(
        data => { // call back },
        error => { },
    );
}

Display rows with one or more NaN values in pandas dataframe

Use df[df.isnull().any(axis=1)] for python 3.6 or above.

How can I remove the top and right axis in matplotlib?

This is the suggested Matplotlib 3 solution from the official website HERE:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

ax = plt.subplot(111)
ax.plot(x, y)

# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')

plt.show()

enter image description here

How to go to each directory and execute a command?

for p in [0-9][0-9][0-9];do
    (
        cd $p
        for f in [0-9][0-9][0-9][0-9]*.txt;do
            ls $f; # Your operands
        done
    )
done