Programs & Examples On #Subscriptions

Can't perform a React state update on an unmounted component

Functional component approach (Minimal Demo, Full Demo):

import React, { useState } from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpFetch from "cp-fetch"; //cancellable c-promise fetch wrapper

export default function TestComponent(props) {
  const [text, setText] = useState("");

  useAsyncEffect(
    function* () {
      setText("fetching...");
      const response = yield cpFetch(props.url);
      const json = yield response.json();
      setText(`Success: ${JSON.stringify(json)}`);
    },
    [props.url]
  );

  return <div>{text}</div>;
}

Class component (Live demo)

import { async, listen, cancel, timeout } from "c-promise2";
import cpFetch from "cp-fetch";

export class TestComponent extends React.Component {
  state = {
    text: ""
  };

  @timeout(5000)
  @listen
  @async
  *componentDidMount() {
    console.log("mounted");
    const response = yield cpFetch(this.props.url);
    this.setState({ text: `json: ${yield response.text()}` });
  }

  render() {
    return <div>{this.state.text}</div>;
  }

  @cancel()
  componentWillUnmount() {
    console.log("unmounted");
  }
}

Angular/RxJs When should I unsubscribe from `Subscription`

You usually need to unsubscribe when the components get destroyed, but Angular is going to handle it more and more as we go, for example in new minor version of Angular4, they have this section for routing unsubscribe:

Do you need to unsubscribe?

As described in the ActivatedRoute: the one-stop-shop for route information section of the Routing & Navigation page, the Router manages the observables it provides and localizes the subscriptions. The subscriptions are cleaned up when the component is destroyed, protecting against memory leaks, so you don't need to unsubscribe from the route paramMap Observable.

Also the example below is a good example from Angular to create a component and destroy it after, look at how component implements OnDestroy, if you need onInit, you also can implements it in your component, like implements OnInit, OnDestroy

import { Component, Input, OnDestroy } from '@angular/core';  
import { MissionService } from './mission.service';
import { Subscription }   from 'rxjs/Subscription';

@Component({
  selector: 'my-astronaut',
  template: `
    <p>
      {{astronaut}}: <strong>{{mission}}</strong>
      <button
        (click)="confirm()"
        [disabled]="!announced || confirmed">
        Confirm
      </button>
    </p>
  `
})

export class AstronautComponent implements OnDestroy {
  @Input() astronaut: string;
  mission = '<no mission announced>';
  confirmed = false;
  announced = false;
  subscription: Subscription;

  constructor(private missionService: MissionService) {
    this.subscription = missionService.missionAnnounced$.subscribe(
      mission => {
        this.mission = mission;
        this.announced = true;
        this.confirmed = false;
    });
  }

  confirm() {
    this.confirmed = true;
    this.missionService.confirmMission(this.astronaut);
  }

  ngOnDestroy() {
    // prevent memory leak when component destroyed
    this.subscription.unsubscribe();
  }
}

Angular 2 Sibling Component Communication

You need to set up the parent-child relationship between your components. The problem is that you might simply inject the child components in the constructor of the parent component and store it in a local variable. Instead, you should declare the child components in your parent component by using the @ViewChild property declarator. This is how your parent component should look like:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ListComponent } from './list.component';
import { DetailComponent } from './detail.component';

@Component({
  selector: 'app-component',
  template: '<list-component></list-component><detail-component></detail-component>',
  directives: [ListComponent, DetailComponent]
})
class AppComponent implements AfterViewInit {
  @ViewChild(ListComponent) listComponent:ListComponent;
  @ViewChild(DetailComponent) detailComponent: DetailComponent;

  ngAfterViewInit() {
    // afther this point the children are set, so you can use them
    this.detailComponent.doSomething();
  }
}

https://angular.io/docs/ts/latest/api/core/index/ViewChild-var.html

https://angular.io/docs/ts/latest/cookbook/component-communication.html#parent-to-view-child

Beware, the child component will not be available in the constructor of the parent component, just after the ngAfterViewInit lifecycle hook is called. To catch this hook simple implement the AfterViewInit interface in you parent class the same way you would do with OnInit.

But, there are other property declarators as explained in this blog note: http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/

How can I close a dropdown on click outside?

You can write directive:

@Directive({
  selector: '[clickOut]'
})
export class ClickOutDirective implements AfterViewInit {
  @Input() clickOut: boolean;

  @Output() clickOutEvent: EventEmitter<any> = new EventEmitter<any>();

  @HostListener('document:mousedown', ['$event']) onMouseDown(event: MouseEvent) {

       if (this.clickOut && 
         !event.path.includes(this._element.nativeElement))
       {
           this.clickOutEvent.emit();
       }
  } 


}

In your component:

@Component({
  selector: 'app-root',
  template: `
    <h1 *ngIf="isVisible" 
      [clickOut]="true" 
      (clickOutEvent)="onToggle()"
    >{{title}}</h1>
`,
  styleUrls: ['./app.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  title = 'app works!';

  isVisible = false;

  onToggle() {
    this.isVisible = !this.isVisible;
  }
}

This directive emit event when html element is containing in DOM and when [clickOut] input property is 'true'. It listen mousedown event to handle event before element will be removed from DOM.

And one note: firefox doesn't contain property 'path' on event you can use function to create path:

const getEventPath = (event: Event): HTMLElement[] => {
  if (event['path']) {
    return event['path'];
  }
  if (event['composedPath']) {
    return event['composedPath']();
  }
  const path = [];
  let node = <HTMLElement>event.target;
  do {
    path.push(node);
  } while (node = node.parentElement);
  return path;
};

So you should change event handler on the directive: event.path should be replaced getEventPath(event)

This module can help. https://www.npmjs.com/package/ngx-clickout It contains the same logic but also handle esc event on source html element.

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

This error is because of multiple project having the offending resources.

Try out adding the dependencies projects other way around. (like in pom.xml or external depandancies)

enter image description here

How to get the azure account tenant Id?

My team really got sick of trying to find the tenant ID for our O365 and Azure projects. The devs, the support team, the sales team, everyone needs it at some point and never remembers how to do it.

So we've built this small site in the same vein as whatismyip.com. Hope you find it useful!

How to find my Microsoft 365, Azure or SharePoint Online tenant ID?

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I solved this problem by reverting the changes that nuget had made to my web.config after running nuget. Revert the changes to a previous working version.

  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
  </dependentAssembly>

How to bring back "Browser mode" in IE11?

In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good

How to select count with Laravel's fluent query builder?

$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Looks like you have a query that is taking longer than it should. From your stack trace and your code you should be able to determine exactly what query that is.

This type of timeout can have three causes;

  1. There's a deadlock somewhere
  2. The database's statistics and/or query plan cache are incorrect
  3. The query is too complex and needs to be tuned

A deadlock can be difficult to fix, but it's easy to determine whether that is the case. Connect to your database with Sql Server Management Studio. In the left pane right-click on the server node and select Activity Monitor. Take a look at the running processes. Normally most will be idle or running. When the problem occurs you can identify any blocked process by the process state. If you right-click on the process and select details it'll show you the last query executed by the process.

The second issue will cause the database to use a sub-optimal query plan. It can be resolved by clearing the statistics:

exec sp_updatestats

If that doesn't work you could also try

dbcc freeproccache

You should not do this when your server is under heavy load because it will temporarily incur a big performace hit as all stored procs and queries are recompiled when first executed. However, since you state the issue occurs sometimes, and the stack trace indicates your application is starting up, I think you're running a query that is only run on occasionally. You may be better off by forcing SQL Server not to reuse a previous query plan. See this answer for details on how to do that.

I've already touched on the third issue, but you can easily determine whether the query needs tuning by executing the query manually, for example using Sql Server Management Studio. If the query takes too long to complete, even after resetting the statistics you'll probably need to tune it. For help with that, you should post the exact query in a new question.

Detect if PHP session exists

If you are on php 5.4+, it is cleaner to use session_status():

if (session_status() == PHP_SESSION_ACTIVE) {
  echo 'Session is active';
}
  • PHP_SESSION_DISABLED if sessions are disabled.
  • PHP_SESSION_NONE if sessions are enabled, but none exists.
  • PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

IF/ELSE Stored Procedure

Are you missing the 'SET' statement when assigning to your variables in the IF .. ELSE block?

MySQL join with where clause

Try this

  SELECT *
    FROM categories
    LEFT JOIN user_category_subscriptions 
         ON user_category_subscriptions.category_id = categories.category_id 
   WHERE user_category_subscriptions.user_id = 1 
          or user_category_subscriptions.user_id is null

Collection was modified; enumeration operation may not execute

Here is a specific scenario that warrants a specialized approach:

  1. The Dictionary is enumerated frequently.
  2. The Dictionary is modified infrequently.

In this scenario creating a copy of the Dictionary (or the Dictionary.Values) before every enumeration can be quite costly. My idea about solving this problem is to reuse the same cached copy in multiple enumerations, and watch an IEnumerator of the original Dictionary for exceptions. The enumerator will be cached along with the copied data, and interrogated before starting a new enumeration. In case of an exception the cached copy will be discarded, and a new one will be created. Here is my implementation of this idea:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

public class EnumerableSnapshot<T> : IEnumerable<T>, IDisposable
{
    private IEnumerable<T> _source;
    private IEnumerator<T> _enumerator;
    private ReadOnlyCollection<T> _cached;

    public EnumerableSnapshot(IEnumerable<T> source)
    {
        _source = source ?? throw new ArgumentNullException(nameof(source));
    }

    public IEnumerator<T> GetEnumerator()
    {
        if (_source == null) throw new ObjectDisposedException(this.GetType().Name);
        if (_enumerator == null)
        {
            _enumerator = _source.GetEnumerator();
            _cached = new ReadOnlyCollection<T>(_source.ToArray());
        }
        else
        {
            var modified = false;
            if (_source is ICollection collection) // C# 7 syntax
            {
                modified = _cached.Count != collection.Count;
            }
            if (!modified)
            {
                try
                {
                    _enumerator.MoveNext();
                }
                catch (InvalidOperationException)
                {
                    modified = true;
                }
            }
            if (modified)
            {
                _enumerator.Dispose();
                _enumerator = _source.GetEnumerator();
                _cached = new ReadOnlyCollection<T>(_source.ToArray());
            }
        }
        return _cached.GetEnumerator();
    }

    public void Dispose()
    {
        _enumerator?.Dispose();
        _enumerator = null;
        _cached = null;
        _source = null;
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

public static class EnumerableSnapshotExtensions
{
    public static EnumerableSnapshot<T> ToEnumerableSnapshot<T>(
        this IEnumerable<T> source) => new EnumerableSnapshot<T>(source);
}

Usage example:

private static IDictionary<Guid, Subscriber> _subscribers;
private static EnumerableSnapshot<Subscriber> _subscribersSnapshot;

//...(in the constructor)
_subscribers = new Dictionary<Guid, Subscriber>();
_subscribersSnapshot = _subscribers.Values.ToEnumerableSnapshot();

// ...(elsewere)
foreach (var subscriber in _subscribersSnapshot)
{
    //...
}

Unfortunately this idea cannot be used currently with the class Dictionary in .NET Core 3.0, because this class does not throw a Collection was modified exception when enumerated and the methods Remove and Clear are invoked. All other containers I checked are behaving consistently. I checked systematically these classes: List<T>, Collection<T>, ObservableCollection<T>, HashSet<T>, SortedSet<T>, Dictionary<T,V> and SortedDictionary<T,V>. Only the two aforementioned methods of the Dictionary class in .NET Core are not invalidating the enumeration.


Update: I fixed the above problem by comparing also the lengths of the cached and the original collection. This fix assumes that the dictionary will be passed directly as an argument to the EnumerableSnapshot's constructor, and its identity will not be hidden by (for example) a projection like: dictionary.Select(e => e).??EnumerableSnapshot().


Important: The above class is not thread safe. It is intended to be used from code running exclusively in a single thread.

How can I clear event subscriptions in C#?

Remove all events, assume the event is an "Action" type:

Delegate[] dary = TermCheckScore.GetInvocationList();

if ( dary != null )
{
    foreach ( Delegate del in dary )
    {
        TermCheckScore -= ( Action ) del;
    }
}

Build android release apk on Phonegap 3.x CLI

just wondered around a lot because I got the same issue but in my installation the command "cordova" was never available and "phone gap build android --release" just ignored the platform/android/ant.properties.

so looking inside my platform filter I found a folder named "cordova" and inside of it there was an "build" binary that accepted the --release argument, it asked me for the key chains and I ended with a signed and ready for production APK.

this was never documented in any part of the phone gap site and frankly speaking now I kinda hate phonegap :( it was supposed to make the things easier but everything was just complicated :(

sorting and paging with gridview asp.net

More simple way...:

    Dim dt As DataTable = DirectCast(GridView1.DataSource, DataTable)
    Dim dv As New DataView(dt)

    If GridView1.Attributes("dir") = SortDirection.Ascending Then
        dv.Sort = e.SortExpression & " DESC" 
        GridView1.Attributes("dir") = SortDirection.Descending

    Else
        GridView1.Attributes("dir") = SortDirection.Ascending
        dv.Sort = e.SortExpression & " ASC"

    End If

    GridView1.DataSource = dv
    GridView1.DataBind()

Octave/Matlab: Adding new elements to a vector

As mentioned before, the use of x(end+1) = newElem has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.

However, what should not be forgotten is that x = [x newElem] will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]


All in all, if you want a solution that allows you to concatenate your existing vector x with newElem that may or may not be a scalar, this should do the trick:

 x(end+(1:numel(newElem)))=newElem

How to use Object.values with typescript?

Having my tslint rules configuration here always replacing the line Object["values"](myObject) with Object.values(myObject).

Two options if you have same issue:

(Object as any).values(myObject)

or

/*tslint:disable:no-string-literal*/
`Object["values"](myObject)`

Convert nested Python dict to object?

I had some problems with __getattr__ not being called so I constructed a new style class version:

class Struct(object):
    '''The recursive class for building and representing objects with.'''
    class NoneStruct(object):
        def __getattribute__(*args):
            return Struct.NoneStruct()

        def __eq__(self, obj):
            return obj == None

    def __init__(self, obj):
        for k, v in obj.iteritems():
            if isinstance(v, dict):
                setattr(self, k, Struct(v))
            else:
                setattr(self, k, v)

    def __getattribute__(*args):
        try:
            return object.__getattribute__(*args)
        except:            
            return Struct.NoneStruct()

    def __repr__(self):
        return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for 
(k, v) in self.__dict__.iteritems()))

This version also has the addition of NoneStruct that is returned when an attribute is called that is not set. This allows for None testing to see if an attribute is present. Very usefull when the exact dict input is not known (settings etc.).

bla = Struct({'a':{'b':1}})
print(bla.a.b)
>> 1
print(bla.a.c == None)
>> True

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

you make the use of the HTML Helper and have

    @using(Html.BeginForm())
    {
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    }

or use the Url helper

<form method="post" action="@Url.Action("MyAction", "MyController")" >

Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:

@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    < ... >
}

If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete

public ActionResult Delete(int id)
{
   var model = db.GetPostById(id);
   return View(model);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var model = db.GetPostById(id);
    if(model != null) 
        db.DeletePost(id);

    return RedirectToView("Index");
}

and your html page would be something like:

<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>

@using(Html.BeginForm())
{
    <input type="submit" class="btn btn-danger" value="Delete Post"/>
    <text>or</text>
    @Url.ActionLink("go to list", "Index")
}

Filter items which array contains any of given values

You should use Terms Query

{
    "query" : {
        "terms" : {
            "tags" : ["c", "d"]
        }
    }
}

placeholder for select tag

This my function for select box placeholder.

HTML

<select name="country" id="country">
  <option value="" disabled selected>Country</option>
  <option value="c1">England</option>
  <option value="c2">Russia</option>
  <option value="c3">USA</option>
</select>

jQuery

     jQuery(function($) {
      /*function for placeholder select*/
      function selectPlaceholder(selectID){
        var selected = $(selectID + ' option:selected');
        var val = selected.val();
        $(selectID + ' option' ).css('color', '#333');
        selected.css('color', '#999');
        if (val == "") {
          $(selectID).css('color', '#999');
        };
        $(selectID).change(function(){
          var val = $(selectID + ' option:selected' ).val();
          if (val == "") {
            $(selectID).css('color', '#999');
          }else{
            $(selectID).css('color', '#333');
          };
        });
      };

      selectPlaceholder('#country');

    });

Writing a string to a cell in excel

try this instead

Set TxtRng = ActiveWorkbook.Sheets("Game").Range("A1")

ADDITION

Maybe the file is corrupt - this has happened to me several times before and the only solution is to copy everything out into a new file.

Please can you try the following:

  • Save a new xlsm file and call it "MyFullyQualified.xlsm"
  • Add a sheet with no protection and call it "mySheet"
  • Add a module to the workbook and add the following procedure

Does this run?

 Sub varchanger()

 With Excel.Application
    .ScreenUpdating = True
    .Calculation = Excel.xlCalculationAutomatic
    .EnableEvents = True
 End With

 On Error GoTo Whoa:

    Dim myBook As Excel.Workbook
    Dim mySheet As Excel.Worksheet
    Dim Rng  As Excel.Range

    Set myBook = Excel.Workbooks("MyFullyQualified.xlsm")
    Set mySheet = myBook.Worksheets("mySheet")
    Set Rng = mySheet.Range("A1")

    'ActiveSheet.Unprotect


    Rng.Value = "SubTotal"

    Excel.Workbooks("MyFullyQualified.xlsm").Worksheets("mySheet").Range("A1").Value = "Asdf"

LetsContinue:
        Exit Sub
Whoa:
        MsgBox Err.Number
        GoTo LetsContinue

End Sub

How to recursively delete an entire directory with PowerShell 2.0?

Really simple:

remove-item -path <type in file or directory name>, press Enter

In Angular, how to add Validator to FormControl after control is created?

If you are using reactiveFormModule and have formGroup defined like this:

public exampleForm = new FormGroup({
        name: new FormControl('Test name', [Validators.required, Validators.minLength(3)]),
        email: new FormControl('[email protected]', [Validators.required, Validators.maxLength(50)]),
        age: new FormControl(45, [Validators.min(18), Validators.max(65)])
});

than you are able to add a new validator (and keep old ones) to FormControl with this approach:

this.exampleForm.get('age').setValidators([
        Validators.pattern('^[0-9]*$'),
        this.exampleForm.get('age').validator
]);
this.exampleForm.get('email').setValidators([
        Validators.email,
        this.exampleForm.get('email').validator
]);

FormControl.validator returns a compose validator containing all previously defined validators.

How to fill the whole canvas with specific color?

_x000D_
_x000D_
let canvas = document.getElementById('canvas');_x000D_
canvas.setAttribute('width', window.innerWidth);_x000D_
canvas.setAttribute('height', window.innerHeight);_x000D_
let ctx = canvas.getContext('2d');_x000D_
_x000D_
//Draw Canvas Fill mode_x000D_
ctx.fillStyle = 'blue';_x000D_
ctx.fillRect(0,0,canvas.width, canvas.height);
_x000D_
* { margin: 0; padding: 0; box-sizing: border-box; }_x000D_
body { overflow: hidden; }
_x000D_
<canvas id='canvas'></canvas>
_x000D_
_x000D_
_x000D_

how to avoid extra blank page at end while printing?

The extra page problem in my case was caused by table element on the page. I tried many of the solutions offered here, but to solve the problem I had to change the table css to:

table {
    width: 99%;
    height: 99%;
}

Save results to csv file with Python

This is how I do it

 import csv
    file = open('???.csv', 'r')
    read = csv.reader(file)
    for column in read:
            file = open('???.csv', 'r')
            read = csv.reader(file)
            file.close()
            file = open('????.csv', 'a', newline='')
            write = csv.writer(file, delimiter = ",")
            write.writerow((, ))
            file.close()

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Shortcut for changing font size

In the Macros explorer under samples/accessibility there is an IncreaseTextEditorFontSize and a DecreaseTextEditorFontSize. Bind those to some keyboard shortcuts.

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

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

Example

Commenting in a Bash script inside a multiline command

In addition to the examples by DigitalRoss, here's another form that you can use if you prefer $() instead of backticks `

echo abc $(: comment) \
     def $(: comment) \
     xyz

Of course, you can use the colon syntax with backticks as well:

echo abc `: comment` \
     def `: comment` \
     xyz

Additional Notes

The reason $(#comment) doesn't work is because once it sees the #, it treats the rest of the line as comments, including the closing parentheses: comment). So the parentheses is never closed.

Backticks parse differently and will detect the closing backtick even after a #.

?: operator (the 'Elvis operator') in PHP

Another important consideration: The Elvis Operator breaks the Zend Opcache tokenization process. I found this the hard way! While this may have been fixed in later versions, I can confirm this problem exists in PHP 5.5.38 (with in-built Zend Opcache v7.0.6-dev).

If you find that some of your files 'refuse' to be cached in Zend Opcache, this may be one of the reasons... Hope this helps!

Check if table exists without using "select from"

Rather than relying on errors, you can query INFORMATION_SCHEMA.TABLES to see if the table exists. If there's a record, it exists. If there's no record, it doesn't exist.

Subtract days from a DateTime

You can do:

DateTime.Today.AddDays(-1)

Branch from a previous commit using Git

git checkout -b <branch-name> <sha1-of-commit>

Cannot implicitly convert type 'int' to 'short'

That's because the result of adding two Int16 is an Int32. Check the "conversions" paragraph here: http://msdn.microsoft.com/en-us/library/ybs77ex4%28v=vs.71%29.aspx

What is the Maximum Size that an Array can hold?

Since Length is an int I'd say Int.MaxValue

Cannot find or open the PDB file in Visual Studio C++ 2010

Answer by Paul is right, I am just putting the visual to easily get there.

Go to Tools->Options->Debugging->Symbols

Set the checkbox marked in red and it will download the pdb files from microsoft. When you set the checkbox, it will also set a default path for the pdb files in the edit box under, you don't need to change that.

enter image description here

Call a VBA Function into a Sub Procedure

Calling a Sub Procedure – 3 Way technique

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.

Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"

msgbox strFullName
End Sub

Sub Exercise()
    CreateCustomer
End Sub

Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    Call CreateCustomer
End Sub

When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    CreateCustomer()
End Sub

Procedures and Access Levels

Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:

Private Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

The rules that were applied to global variables are the same:

Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.

Also, when a procedure is private, its name does not appear in the Macros dialog box

Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.

Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there

Why doesn't importing java.util.* include Arrays and Lists?

Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.

Update


It gives that warning because your the line should actually be

List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();

You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.

disable a hyperlink using jQuery

I know it's an old question but it seems unsolved still. Follows my solution...

Simply add this global handler:

$('a').click(function()
{
     return ($(this).attr('disabled')) ? false : true;
});

Here's a quick demo: http://jsbin.com/akihik/3

you can even add a bit of css to give a different style to all the links with the disabled attribute.

e.g

a[disabled]
{
    color: grey; 
}

Anyway it seems that the disabled attribute is not valid for a tags. If you prefer to follow the w3c specs you can easily adopt an html5 compliant data-disabled attribute. In this case you have to modify the previous snippet and use $(this).data('disabled').

How do I schedule jobs in Jenkins?

Try using 0 8 * * *. It should work

How to map atan2() to degrees 0-360

angle = Math.atan2(x,y)*180/Math.PI;

I have made a Formula for orienting angle into 0 to 360

angle + Math.ceil( -angle / 360 ) * 360;

What is the difference between '@' and '=' in directive scope in AngularJS?

the main difference between them is just

@ Attribute string binding
= Two-way model binding
& Callback method binding

Android Studio Emulator and "Process finished with exit code 0"

I was getting the following error when starting the emulator and none of the answers fixed it.

Emulator: Process finished with exit code -1073741515 (0xC0000135)

Finally I found that Visual C++ is not installed in my system. If it is not installed please install Visual C++ and check.

Please find the link below to download latest Visual C++.

https://support.microsoft.com/en-in/help/2977003/the-latest-supported-visual-c-downloads

Serialize and Deserialize Json and Json Array in Unity

IF you are using Vector3 this is what i did

1- I create a class Name it Player

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Player
{
    public Vector3[] Position;

}

2- then i call it like this

if ( _ispressed == true)
        {
            Player playerInstance = new Player();
            playerInstance.Position = newPos;
            string jsonData = JsonUtility.ToJson(playerInstance);

            reference.Child("Position" + Random.Range(0, 1000000)).SetRawJsonValueAsync(jsonData);
            Debug.Log(jsonData);
            _ispressed = false;
        }

3- and this is the result

"Position":[ {"x":-2.8567452430725099,"y":-2.4323320388793947,"z":0.0}]}

Add/delete row from a table

jQuery has a nice function for removing elements from the DOM.

The closest() function is cool because it will "get the first element that matches the selector by testing the element itself and traversing up through its ancestors."

$(this).closest("tr").remove();

Each delete button could run that very succinct code with a function call.

Truncate Two decimal places without rounding

        public static void ReminderDigints(decimal? number, out decimal? Value,  out decimal? Reminder)
        {
            Reminder = null;
            Value = null;
            if (number.HasValue)
            {
                Value = Math.Floor(number.Value);
                Reminder = (number - Math.Truncate(number.Value));
            }
        }



        decimal? number= 50.55m;             
        ReminderDigints(number, out decimal? Value, out decimal? Reminder);

How to detect escape key press with pure JS or jQuery?

pure JS (no JQuery)

document.addEventListener('keydown', function(e) {
    if(e.keyCode == 27){
      //add your code here
    }
});

How can I check if a directory exists?

Use the following code to check if a folder exists. It works on both Windows & Linux platforms.

#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char* argv[])
{
    const char* folder;
    //folder = "C:\\Users\\SaMaN\\Desktop\\Ppln";
    folder = "/tmp";
    struct stat sb;

    if (stat(folder, &sb) == 0 && S_ISDIR(sb.st_mode)) {
        printf("YES\n");
    } else {
        printf("NO\n");
    }
}

Chrome Fullscreen API

In Google's closure library project , there is a module which has do the job , below is the API and source code.

Closure library fullscreen.js API

Closure libray fullscreen.js Code

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

convert string date to java.sql.Date

This works for me without throwing an exception:

package com.sandbox;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Sandbox {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date parsed = format.parse("20110210");
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
    }


}

mysql delete under safe mode

Googling around, the popular answer seems to be "just turn off safe mode":

SET SQL_SAFE_UPDATES = 0;
DELETE FROM instructor WHERE salary BETWEEN 13000 AND 15000;
SET SQL_SAFE_UPDATES = 1;

If I'm honest, I can't say I've ever made a habit of running in safe mode. Still, I'm not entirely comfortable with this answer since it just assumes you should go change your database config every time you run into a problem.

So, your second query is closer to the mark, but hits another problem: MySQL applies a few restrictions to subqueries, and one of them is that you can't modify a table while selecting from it in a subquery.

Quoting from the MySQL manual, Restrictions on Subqueries:

In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms:

DELETE FROM t WHERE ... (SELECT ... FROM t ...);
UPDATE t ... WHERE col = (SELECT ... FROM t ...);
{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);

Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:

UPDATE t ... WHERE col = (SELECT * FROM (SELECT ... FROM t...) AS _t ...);

Here the result from the subquery in the FROM clause is stored as a temporary table, so the relevant rows in t have already been selected by the time the update to t takes place.

That last bit is your answer. Select target IDs in a temporary table, then delete by referencing the IDs in that table:

DELETE FROM instructor WHERE id IN (
  SELECT temp.id FROM (
    SELECT id FROM instructor WHERE salary BETWEEN 13000 AND 15000
  ) AS temp
);

SQLFiddle demo.

Sorting HTML table with JavaScript

It does WAY more than "just sorting", but dataTables.net does what you need. I use it daily and is well supported and VERY fast (does require jQuery)

http://datatables.net/

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.

Google Visualizations is another option, but requires a bit more setup that dataTables, but does NOT require any particular framework/library (other than google.visualizations):

http://code.google.com/apis/ajax/playground/?type=visualization#table

And there are other options to... especially if you're using one of the other JS frameworks. Dojo, Prototype, etc all have usable "table enhancement" plugins that provide at minimum table sorting functionality. Many provide more, but I'll restate...I've yet to come across one as powerful and as FAST as datatables.net.

C - casting int to char and append char to char

Casting int to char involves losing data and the compiler will probably warn you.

Extracting a particular byte from an int sounds more reasonable and can be done like this:

number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */

Export P7b file with all the certificate chain into CER file

The selected answer didn't work for me, but it's close. I found a tutorial that worked for me and the certificate I obtained from StartCom.

  1. Open the .p7b in a text editor.
  2. Change the leader and trailer so the file looks similar to this:

    -----BEGIN PKCS7-----
    [... certificate content here ...]
    -----END PKCS7-----
    

For example, my StartCom certificate began with:

    -----BEGIN CERTIFICATE----- 

and ended with:

    -----END CERTIFICATE----- 
  1. Save and close the .p7b.
  2. Run the following OpenSSL command (works on Ubuntu 14.04.4, as of this writing):

    openssl pkcs7 -print_certs –in pkcs7.p7b -out pem.cer
    

The output is a .cer with the certificate chain.

Reference: http://www.freetutorialssubmit.com/extract-certificates-from-P7B/2206

What do the result codes in SVN mean?

SVN status columns

$ svn status
L index.html

The output of the command is split into six columns, but that is not obvious because sometimes the columns are empty. Perhaps it would have made more sense to indicate the empty columns with dashes, the way ls -l does, instead of nothing. Then, for example, L index.html would look like --L--- index.html, which makes it obvious the only information we have is in the third column the one about locking. Anyway, once you know that it begins to make more sense.

SVN Status first column: A, D, M, R, C, X, I, ?, !, ~

The first column indicates that an item was added, deleted, or otherwise changed.

      No modifications.

 A    Item is scheduled for Addition.

 D    Item is scheduled for Deletion.

 M    Item has been modified.

 R    Item has been replaced in your working copy. This means the file was scheduled for deletion, and then a new file with the same name was scheduled for addition in its place.

 C    The contents (as opposed to the properties) of the item conflict with updates received from the repository.

 X    Item is related to an externals definition.

 I    Item is being ignored (e.g. with the svn:ignore property).

 ?    Item is not under version control.

 !    Item is missing (e.g. you moved or deleted it without using svn). This also indicates that a directory is incomplete (a checkout or update was interrupted).

 ~    Item is versioned as one kind of object (file, directory, link), but has been replaced by different kind of object.

SVN Status second column: M, C

The second column tells the status of a file’s or directory’s properties.

      No modifications.

 M    Properties for this item have been modified.

 C    Properties for this item are in conflict with property updates received from the repository.

SVN Status third column: L

The third column is populated only if the working copy directory is locked (an svn cleanup should normally be enough to clear it out)

      Item is not locked.

 L    Item is locked.

SVN Status fourth column: +

The fourth column is populated only if the item is scheduled for addition-with-history.

      No history scheduled with commit.

 +    History scheduled with commit.

SVN Status fifth column: S

The fifth column is populated only if the item’s working copy is switched relative to its parent

      Item is a child of its parent directory.

 S    Item is switched.

SVN Status sixth column: K, O, T, B

The sixth column is populated with lock information.

      When –show-updates is used, the file is not locked. If –show-updates is not used, this merely means that the file is not locked in this working copy.

 K    File is locked in this working copy.

 O    File is locked either by another user or in another working copy. This only appears when –show-updates is used.

 T    File was locked in this working copy, but the lock has been stolen and is invalid. The file is currently locked in the repository. This only appears when –show-updates is used.-

 B    File was locked in this working copy, but the lock has been broken and is invalid. The file is no longer locked This only appears when –show-updates is used.

SVN Status seventh column: *

The out-of-date information appears in the seventh column (only if you pass the –show-updates switch). This is something people who are new to SVN expect the command to do, not realizing it only compare the current state of the file with what information it fetched from the server on the last update.

      The item in your working copy is up-to-date.

 *    A newer revision of the item exists on the server.

How to program a fractal?

I think you might not see fractals as an algorithm or something to program. Fractals is a concept! It is a mathematical concept of detailed pattern repeating itself.

Therefore you can create a fractal in many ways, using different approaches, as shown in the image below.

enter image description here

Choose an approach and then investigate how to implement it. These four examples were implemented using Marvin Framework. The source codes are available here

docker command not found even though installed with apt-get

SET UP THE REPOSITORY

For Ubuntu 14.04/16.04/16.10/17.04:

sudo add-apt-repository "deb [arch=amd64] \
     https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

For Ubuntu 17.10:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"

Add Docker’s official GPG key:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Then install

$ sudo apt-get update && sudo apt-get -y install docker-ce

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

This error comes when you are trying to load jasper report file with the extension .jasper
For Example 
c://reports//EmployeeReport.jasper"

While you should load jasper report file with the extension .jrxml
For Example 
c://reports//EmployeeReport.jrxml"
[See Problem Screenshot ][1] [1]: https://i.stack.imgur.com/D5SzR.png
[See Solution Screenshot][2] [2]: https://i.stack.imgur.com/VeQb9.png

  
  

Java: Static vs inner class

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

How to fix Cannot find module 'typescript' in Angular 4?

I had the same problem. If you have installed first nodejs by apt and then you use the tar.gz from nodejs.org, you have to delete the folder located in /usr/lib/node_modules.

Server configuration by allow_url_fopen=0 in

@blytung Has a nice function to replace that function

<?php
$url = "http://www.example.org/";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
if (curl_errno($ch)) {
  echo curl_error($ch);
  echo "\n<br />";
  $contents = '';
} else {
  curl_close($ch);
}

if (!is_string($contents) || !strlen($contents)) {
echo "Failed to get contents.";
$contents = '';
}

echo $contents;
?>    

How to write an async method with out parameter?

Here's the code of @dcastro's answer modified for C# 7.0 with named tuples and tuple deconstruction, which streamlines the notation:

public async void Method1()
{
    // Version 1, named tuples:
    // just to show how it works
    /*
    var tuple = await GetDataTaskAsync();
    int op = tuple.paramOp;
    int result = tuple.paramResult;
    */

    // Version 2, tuple deconstruction:
    // much shorter, most elegant
    (int op, int result) = await GetDataTaskAsync();
}

public async Task<(int paramOp, int paramResult)> GetDataTaskAsync()
{
    //...
    return (1, 2);
}

For details about the new named tuples, tuple literals and tuple deconstructions see: https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/

Changing the width of Bootstrap popover

I had the same problem. Spent quite some time searching for an answer and found my own solution: Add following text to the head:

<style type="text/css">
    .popover{
        max-width:600px;
    }
</style>

configure: error: C compiler cannot create executables

I furiously read all of this page, hoping to find a solution for:

"configure: error: C compiler cannot create executables"

In the end nothing worked, because my problem was a "typing" one, and was related to CFLAGS. In my .bash_profile file I had:

export ARM_ARCH="arm64”
export CFLAGS="-arch ${ARM_ARCH}"

As you can observe --- export ARM_ARCH="arm64” --- the last quote sign is not the same with the first quote sign. The first one ( " ) is legal while the second one ( ” ) is not.
This happended because I made the mistake to use TextEdit (I'm working under MacOS), and this is apparently a feature called SmartQuotes: the quote sign CHANGES BY ITSELF TO THE ILLEGAL STYLE whenever you edit something just next to it.
Lesson learned: use a proper text editor...

Is there a php echo/print equivalent in javascript

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

Using window.log will allow you to perform the same action as console.log, but it checks if the browser you are using has the ability to use console.log first, so as not to error out for compatibility reasons (IE 6, etc.).

Count number of rows within each group

Following @Joshua's suggestion, here's one way you might count the number of observations in your df dataframe where Year = 2007 and Month = Nov (assuming they are columns):

nrow(df[,df$YEAR == 2007 & df$Month == "Nov"])

and with aggregate, following @GregSnow:

aggregate(x ~ Year + Month, data = df, FUN = length)

Replace an element into a specific position of a vector

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

Moving Panel in Visual Studio Code to right side

VSCode 1.42 (January 2020) introduces:

Panel on the left/right

The panel can now be moved to the left side of the editor with the setting:

"workbench.panel.defaultLocation": "left"

This removes the command View: Toggle Panel Position (workbench.action.togglePanelPosition) in favor of the following new commands:

  • View: Move Panel Left (workbench.action.positionPanelLeft)
  • View: Move Panel Right (workbench.action.positionPanelRight)
  • View: Move Panel To Bottom (workbench.action.positionPanelBottom)

Add 'x' number of hours to date

I use this , its working cool.

//set timezone
date_default_timezone_set('GMT');

//set an date and time to work with
$start = '2014-06-01 14:00:00';

//display the converted time
echo date('Y-m-d H:i',strtotime('+1 hour +20 minutes',strtotime($start)));

How do I manage conflicts with git submodules?

I have not seen that exact error before. But I have a guess about the trouble you are encountering. It looks like because the master and one.one branches of supery contain different refs for the subby submodule, when you merge changes from master git does not know which ref - v1.0 or v1.1 - should be kept and tracked by the one.one branch of supery.

If that is the case, then you need to select the ref that you want and commit that change to resolve the conflict. Which is exactly what you are doing with the reset command.

This is a tricky aspect of tracking different versions of a submodule in different branches of your project. But the submodule ref is just like any other component of your project. If the two different branches continue to track the same respective submodule refs after successive merges, then git should be able to work out the pattern without raising merge conflicts in future merges. On the other hand you if switch submodule refs frequently you may have to put up with a lot of conflict resolving.

Rename computer and join to domain in one step with PowerShell

Here is another way to do with "Computer Name/Domain Change" Windows of System Properties.

In other words, bring up System Properties| Computer Name Tab then click Change using powershell. It is different approach, it is useful in my situation and it could be helpful for someone else.

add-type -AssemblyName microsoft.VisualBasic add-type -AssemblyName System.Windows.Forms

SystemPropertiesComputerName start-sleep –Seconds 1

[Microsoft.VisualBasic.Interaction]::AppActivate(“System Properties”)

[System.Windows.Forms.SendKeys]::SendWait(“{TAB}”) start-sleep –Seconds 1

[System.Windows.Forms.SendKeys]::SendWait(“{ENTER}”)

c# regex matches example

This pattern should work:

#\d

foreach(var match in System.Text.RegularExpressions.RegEx.Matches(input, "#\d"))
{
    Console.WriteLine(match.Value);
}

(I'm not in front of Visual Studio, but even if that doesn't compile as-is, it should be close enough to tweak into something that works).

Using str_replace so that it only acts on the first match?

$str = "/property/details&id=202&test=123#tab-6p";
$position = strpos($str,"&");
echo substr_replace($str,"?",$position,1);

Using substr_replace we can replace the occurrence of first character only in string. as & is repeated multiple times but only at first position we have to replace & with ?

This Handler class should be static or leaks might occur: IncomingHandler

With the help of @Sogger's answer, I created a generic Handler:

public class MainThreadHandler<T extends MessageHandler> extends Handler {

    private final WeakReference<T> mInstance;

    public MainThreadHandler(T clazz) {
        // Remove the following line to use the current thread.
        super(Looper.getMainLooper());
        mInstance = new WeakReference<>(clazz);
    }

    @Override
    public void handleMessage(Message msg) {
        T clazz = mInstance.get();
        if (clazz != null) {
            clazz.handleMessage(msg);
        }
    }
}

The interface:

public interface MessageHandler {

    void handleMessage(Message msg);

}

I'm using it as follows. But I'm not 100% sure if this is leak-safe. Maybe someone could comment on this:

public class MyClass implements MessageHandler {

    private static final int DO_IT_MSG = 123;

    private MainThreadHandler<MyClass> mHandler = new MainThreadHandler<>(this);

    private void start() {
        // Do it in 5 seconds.
        mHandler.sendEmptyMessageDelayed(DO_IT_MSG, 5 * 1000);
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case DO_IT_MSG:
                doIt();
                break;
        }
    }

    ...

}

Using Jasmine to spy on a function without an object

There is 2 alternative which I use (for jasmine 2)

This one is not quite explicit because it seems that the function is actually a fake.

test = createSpy().and.callFake(test); 

The second more verbose, more explicit, and "cleaner":

test = createSpy('testSpy', test).and.callThrough();

-> jasmine source code to see the second argument

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

How to open a new window on form submit

For a similar effect to form's target attribute, you can also use the formtarget attribute of input[type="submit]" or button[type="submit"].

From MDN:

...this attribute is a name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the target attribute of the elements's form owner. The following keywords have special meanings:

  • _self: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
  • _blank: Load the response into a new unnamed browsing context.
  • _parent: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
  • _top: Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self.

Find files containing a given text

Try something like grep -r -n -i --include="*.html *.php *.js" searchstrinhere .

the -i makes it case insensitlve

the . at the end means you want to start from your current directory, this could be substituted with any directory.

the -r means do this recursively, right down the directory tree

the -n prints the line number for matches.

the --include lets you add file names, extensions. Wildcards accepted

For more info see: http://www.gnu.org/software/grep/

Getting current directory in VBScript

Use With in the code.

Try this way :

''''Way 1

currentdir=Left(WScript.ScriptFullName,InStrRev(WScript.ScriptFullName,"\"))


''''Way 2

With CreateObject("WScript.Shell")
CurrentPath=.CurrentDirectory
End With


''''Way 3

With WSH
CD=Replace(.ScriptFullName,.ScriptName,"")
End With

How to split strings into text and number?

This is a little longer, but more versatile for cases where there are multiple, randomly placed, numbers in the string. Also, it requires no imports.

def getNumbers( input ):
    # Collect Info
    compile = ""
    complete = []

    for letter in input:
        # If compiled string
        if compile:
            # If compiled and letter are same type, append letter
            if compile.isdigit() == letter.isdigit():
                compile += letter
            
            # If compiled and letter are different types, append compiled string, and begin with letter
            else:
                complete.append( compile )
                compile = letter
            
        # If no compiled string, begin with letter
        else:
            compile = letter
        
    # Append leftover compiled string
    if compile:
        complete.append( compile )
    
    # Return numbers only
    numbers = [ word for word in complete if word.isdigit() ]
        
    return numbers

Avoid browser popup blockers

from Google's oauth JavaScript API:

http://code.google.com/p/google-api-javascript-client/wiki/Authentication

See the area where it reads:

Setting up Authentication

The client's implementation of OAuth 2.0 uses a popup window to prompt the user to sign-in and approve the application. The first call to gapi.auth.authorize can trigger popup blockers, as it opens the popup window indirectly. To prevent the popup blocker from triggering on auth calls, call gapi.auth.init(callback) when the client loads. The supplied callback will be executed when the library is ready to make auth calls.

I would guess its relating to the real answer above in how it explains if there is an immediate response, it won't trip the popup alarm. The "gapi.auth.init" is making it so the api happens immediately.

Practical Application

I made an open source authentication microservice using node passport on npm and the various passport packages for each provider. I used a standard redirect approach to the 3rd party giving it a redirect URL to come back to. This was programmatic so I could have different places to redirect back to if login/signup and on particular pages.

github.com/sebringj/athu

passportjs.org

What's the fastest way to convert String to Number in JavaScript?

This is probably not that fast, but has the added benefit of making sure your number is at least a certain value (e.g. 0), or at most a certain value:

Math.max(input, 0);

If you need to ensure a minimum value, usually you'd do

var number = Number(input);
if (number < 0) number = 0;

Math.max(..., 0) saves you from writing two statements.

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

Setting up the Two-tone color:

As described above you can use the color css key except for materials Two-tone theme which seems to be glitchy ;-)

A workaround is described in one of several angular material github issue's by using a custom css filter. This custom filter can be generated here.

E.g.:

Html:

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Round|Material+Icons+Two+Tone|Material+Icons+Sharp">

<i class="material-icons-two-tone red">home</i>

css:

.red {
filter: invert(8%) sepia(94%) saturate(4590%) hue-rotate(358deg) brightness(101%) contrast(112%);
}

Attachments:

Why doesn't os.path.join() work in this case?

It's because your '/new_sandbox/' begins with a / and thus is assumed to be relative to the root directory. Remove the leading /.

Oracle 10g: Extract data (select) from XML (CLOB Type)

Try this instead:

select xmltype(t.xml).extract('//fax/text()').getStringVal() from mytab t

How can I pass a username/password in the header to a SOAP WCF Service

There is probably a smarter way, but you can add the headers manually like this:

var client = new IdentityProofingService.IdentityProofingWSClient();

using (new OperationContextScope(client.InnerChannel))
{
    OperationContext.Current.OutgoingMessageHeaders.Add(
        new SecurityHeader("UsernameToken-49", "12345/userID", "password123"));
    client.invokeIdentityService(new IdentityProofingRequest());
}

Here, SecurityHeader is a custom implemented class, which needs a few other classes since I chose to use attributes to configure the XML serialization:

public class SecurityHeader : MessageHeader
{
    private readonly UsernameToken _usernameToken;

    public SecurityHeader(string id, string username, string password)
    {
        _usernameToken = new UsernameToken(id, username, password);
    }

    public override string Name
    {
        get { return "Security"; }
    }

    public override string Namespace
    {
        get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
    }

    protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(UsernameToken));
        serializer.Serialize(writer, _usernameToken);
    }
}


[XmlRoot(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")]
public class UsernameToken
{
    public UsernameToken()
    {
    }

    public UsernameToken(string id, string username, string password)
    {
        Id = id;
        Username = username;
        Password = new Password() {Value = password};
    }

    [XmlAttribute(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")]
    public string Id { get; set; }

    [XmlElement]
    public string Username { get; set; }

    [XmlElement]
    public Password Password { get; set; }
}

public class Password
{
    public Password()
    {
        Type = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";
    }

    [XmlAttribute]
    public string Type { get; set; }

    [XmlText]
    public string Value { get; set; }
}

I have not added the Nonce bit to the UsernameToken XML, but it is very similar to the Password one. The Created element also needs to be added still, but it's a simple [XmlElement].

Passing a varchar full of comma delimited values to a SQL Server IN function

Thanks, for your function I Used IT........................ This is my EXAMPLE

**UPDATE [RD].[PurchaseOrderHeader]
SET     [DispatchCycleNumber] ='10'
 WHERE  OrderNumber in(select * FROM XA.fn_SplitOrderIDs(@InvoiceNumberList))**


CREATE FUNCTION [XA].[fn_SplitOrderIDs]
(
    @OrderList varchar(500)
)
RETURNS 
@ParsedList table
(
    OrderID int
)
AS
BEGIN
    DECLARE @OrderID varchar(10), @Pos int

    SET @OrderList = LTRIM(RTRIM(@OrderList))+ ','
    SET @Pos = CHARINDEX(',', @OrderList, 1)

    IF REPLACE(@OrderList, ',', '') <> ''
    BEGIN
        WHILE @Pos > 0
        BEGIN
                SET @OrderID = LTRIM(RTRIM(LEFT(@OrderList, @Pos - 1)))
                IF @OrderID <> ''
                BEGIN
                        INSERT INTO @ParsedList (OrderID) 
                        VALUES (CAST(@OrderID AS int)) --Use Appropriate conversion
                END
                SET @OrderList = RIGHT(@OrderList, LEN(@OrderList) - @Pos)
                SET @Pos = CHARINDEX(',', @OrderList, 1)

        END
    END 
    RETURN
END

Is there a "theirs" version of "git merge -s ours"?

I solved my problem using

git checkout -m old
git checkout -b new B
git merge -s ours old

Difference between "or" and || in Ruby?

As the others have already explained, the only difference is the precedence. However, I would like to point out that there are actually two differences between the two:

  1. and, or and not have much lower precedence than &&, || and !
  2. and and or have the same precedence, while && has higher precedence than ||

In general, it is good style to avoid the use of and, or and not and use &&, || and ! instead. (The Rails core developers, for example, reject patches which use the keyword forms instead of the operator forms.)

The reason why they exist at all, is not for boolean formulae but for control flow. They made their way into Ruby via Perl's well-known do_this or do_that idiom, where do_this returns false or nil if there is an error and only then is do_that executed instead. (Analogous, there is also the do_this and then_do_that idiom.)

Examples:

download_file_via_fast_connection or download_via_slow_connection
download_latest_currency_rates and store_them_in_the_cache

Sometimes, this can make control flow a little bit more fluent than using if or unless.

It's easy to see why in this case the operators have the "wrong" (i.e. identical) precedence: they never show up together in the same expression anyway. And when they do show up together, you generally want them to be evaluated simply left-to-right.

#include errors detected in vscode

1.Install Mingw-w64

2.Then Edit environment variables for your account "C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin"

3.Reload

  • For MAC

    1.Open search ,command + shift +P, and run this code “c/c++ edit configurations (ui)”

    2.open file c_cpp_properties.json and update the includePath from "${workspaceFolder}/**" to "${workspaceFolder}/inc"

How to read a list of files from a folder using PHP?

There is this function scandir():

$dir = 'dir';
$files = scandir($dir, 0);
for($i = 2; $i < count($files); $i++)
    print $files[$i]."<br>";

More here in the php.net manual

String to LocalDate

DateTimeFormatter has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and NOV wont work:

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");

try {
    LocalDate datetime = LocalDate.parse(oldDate, pattern);
    System.out.println(datetime); 
} catch (DateTimeParseException e) {
    // DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
    // Exception handling message/mechanism/logging as per company standard
}

DateTimeFormatterBuilder provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.

DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
        .append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
    LocalDate datetime = LocalDate.parse(oldDate, f);
    System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
     // Exception handling message/mechanism/logging as per company standard
}

How to check if a process id (PID) exists

The best way is:

if ps -p $PID > /dev/null
then
   echo "$PID is running"
   # Do something knowing the pid exists, i.e. the process with $PID is running
fi

The problem with:

kill -0 $PID

is the exit code will be non-zero even if the pid is running and you dont have permission to kill it. For example:

kill -0 1

and

kill -0 $non-running-pid

have an indistinguishable (non-zero) exit code for a normal user, but the init process (PID 1) is certainly running.

DISCUSSION

The answers discussing kill and race conditions are exactly right if the body of the test is a "kill". I came looking for the general "how do you test for a PID existence in bash".

The /proc method is interesting, but in some sense breaks the spirit of the "ps" command abstraction, i.e. you dont need to go looking in /proc because what if Linus decides to call the "exe" file something else?

How to disable HTML button using JavaScript?

<button disabled=true>text here</button>

You can still use an attribute. Just use the 'disabled' attribute instead of 'value'.

Using GSON to parse a JSON array

public static <T> List<T> toList(String json, Class<T> clazz) {
    if (null == json) {
        return null;
    }
    Gson gson = new Gson();
    return gson.fromJson(json, new TypeToken<T>(){}.getType());
}

sample call:

List<Specifications> objects = GsonUtils.toList(products, Specifications.class);

Identifying Exception Type in a handler Catch Block

You should always catch exceptions as concrete as possible, so you should use

try
{
    //code
}
catch (Web2PDFException ex)
{
    //Handle the exception here
}

You chould of course use something like this if you insist:

try
{
}
catch (Exception err)
{
    if (err is Web2PDFException)
    {
        //Code
    }
}

Detecting the character encoding of an HTTP POST request

The Charset used in the POST will match that of the Charset specified in the HTML hosting the form. Hence if your form is sent using UTF-8 encoding that is the encoding used for the posted content. The URL encoding is applied after the values are converted to the set of octets for the character encoding.

How do I split a string, breaking at a particular character?

JavaScript: Convert String to Array JavaScript Split

_x000D_
_x000D_
    var str = "This-javascript-tutorial-string-split-method-examples-tutsmake."_x000D_
 _x000D_
    var result = str.split('-'); _x000D_
     _x000D_
    console.log(result);_x000D_
     _x000D_
    document.getElementById("show").innerHTML = result; 
_x000D_
<html>_x000D_
<head>_x000D_
<title>How do you split a string, breaking at a particular character in javascript?</title>_x000D_
</head>_x000D_
<body>_x000D_
 _x000D_
<p id="show"></p> _x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

https://www.tutsmake.com/javascript-convert-string-to-array-javascript/

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

How do I set a textbox's value using an anchor with jQuery?

To assign value of a text box whose id is ?textbox? in jQuery please do the following

$("#textbox").val('Blah');

How to check if the string is empty?

not str(myString)

This expression is True for strings that are empty. Non-empty strings, None and non-string objects will all produce False, with the caveat that objects may override __str__ to thwart this logic by returning a falsy value.

How to start Apache and MySQL automatically when Windows 8 comes up

You could copy the XAMPP shortcut into "Local Disk C /users/YourUserName/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Start-up"...

This will make the control panel start up with the computer. Then if you were to select the configuration in the top right hand corner of the control panel you can make Apache and MySQL auto start... This is a quite long-winded get around, but it works for Windows 10.

Get the value in an input text box

To get the textbox value, you can use the jQuery val() function.

For example,

$('input:textbox').val() – Get textbox value.

$('input:textbox').val("new text message") – Set the textbox value.

CXF: No message body writer found for class - automatically mapping non-simple resources

You can try with mentioning "Accept: application/json" in your rest client header as well, if you are expecting your object as JSON in response.

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1, any true value will do.

How can I create Min stl priority_queue?

One way would be to define a suitable comparator with which to operate on the ordinary priority queue, such that its priority gets reversed:

 #include <iostream>  
 #include <queue>  
 using namespace std;  

 struct compare  
 {  
   bool operator()(const int& l, const int& r)  
   {  
       return l > r;  
   }  
 };  

 int main()  
 {  
     priority_queue<int,vector<int>, compare > pq;  

     pq.push(3);  
     pq.push(5);  
     pq.push(1);  
     pq.push(8);  
     while ( !pq.empty() )  
     {  
         cout << pq.top() << endl;  
         pq.pop();  
     }  
     cin.get();  
 }

Which would output 1, 3, 5, 8 respectively.

Some examples of using priority queues via STL and Sedgewick's implementations are given here.

What are the advantages and disadvantages of recursion?

Expressiveness

Most problems are naturally expressed by recursion such as Fibonacci, Merge sorting and quick sorting. In this respect, the code is written for humans, not machines.

Immutability

Iterative solutions often rely on varying temporary variables which makes the code hard to read. This can be avoided with recursion.

Performance

Recursion is not stack friendly. Stack can overflow when the recursion is not well designed or tail optimization is not supported.

Parsing string as JSON with single quotes?

I know it's an old post, but you can use JSON5 for this purpose.

<script src="json5.js"></script>
<script>JSON.stringify(JSON5.parse('{a:1}'))</script>

Can you force Visual Studio to always run as an Administrator in Windows 8?

This is a copy of my answer to a similar post on SuperUser:

Option 1 - Set VSLauncher.exe and DevEnv.exe to always run as admin

To have Visual Studio always run as admin when opening any .sln file:

  1. Navigate to C:\Program Files (x86)\Common Files\Microsoft Shared\MSEnv\VSLauncher.exe.
  2. Right-click on VSLauncher.exe and choose Troubleshoot compatibility.
  3. Choose Troubleshoot program.
  4. Check off The program requires additional permissions and hit Next.
  5. Click the Test the program... button to launch VS.
  6. Click Next, then hit Yes, save these settings for this program, and then the close buton.

To have Visual Studio always run as an admin when just opening visual studio directly, do the same thing to the DevEnv.exe file(s). These file are located at:

Visual Studio 2010

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe

Visual Studio 2012

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe

Visual Studio 2013

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe

Visual Studio 2015

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe

Visual Studio 2017

C:\Program Files (x86)\Microsoft Visual Studio\2017\[VS SKU]\Common7\IDE\devenv.exe

Option 2 - Use VSCommands extension for Visual Studio

Install the free VSCommands extension for Visual Studio (it's in the Visual Studio Extensions Gallery) and then configure it to always have Visual Studio start with admin privileges by going to Tools -> VSCommands -> Options -> IDE Enhancements -> General and check off Always start Visual Studio with elevated permissions and click the Save button.

Note: VSCommands is not currently available for VS 2015, but their site says they are working on updating it to support VS 2015.

My Opinion

I prefer Option 2 because:

  • it also allows you to easily turn off this functionality.
  • VSCommands comes with lots of other great features so I always have it installed anyways.
  • it's just easier to do than option 1.

When I catch an exception, how do I get the type, file, and line number?

Source (Py v2.7.3) for traceback.format_exception() and called/related functions helps greatly. Embarrassingly, I always forget to Read the Source. I only did so for this after searching for similar details in vain. A simple question, "How to recreate the same output as Python for an exception, with all the same details?" This would get anybody 90+% to whatever they're looking for. Frustrated, I came up with this example. I hope it helps others. (It sure helped me! ;-)

import sys, traceback

traceback_template = '''Traceback (most recent call last):
  File "%(filename)s", line %(lineno)s, in %(name)s
%(type)s: %(message)s\n''' # Skipping the "actual line" item

# Also note: we don't walk all the way through the frame stack in this example
# see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
# (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.)

try:
    1/0
except:
    # http://docs.python.org/2/library/sys.html#sys.exc_info
    exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default

    '''
    Reason this _can_ be bad: If an (unhandled) exception happens AFTER this,
    or if we do not delete the labels on (not much) older versions of Py, the
    reference we created can linger.

    traceback.format_exc/print_exc do this very thing, BUT note this creates a
    temp scope within the function.
    '''

    traceback_details = {
                         'filename': exc_traceback.tb_frame.f_code.co_filename,
                         'lineno'  : exc_traceback.tb_lineno,
                         'name'    : exc_traceback.tb_frame.f_code.co_name,
                         'type'    : exc_type.__name__,
                         'message' : exc_value.message, # or see traceback._some_str()
                        }

    del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling
    # This still isn't "completely safe", though!
    # "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback
    # with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

    print
    print traceback.format_exc()
    print
    print traceback_template % traceback_details
    print

In specific answer to this query:

sys.exc_info()[0].__name__, os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename), sys.exc_info()[2].tb_lineno

Email address validation in C# MVC 4 application: with or without using Regex

Don't.

Use a regex for a quick sanity check, something like .@.., but almost all langauges / frameworks have better methods for checking an e-mail address. Use that.

It is possible to validate an e-mail address with a regex, but it is a long regex. Very long.
And in the end you will be none the wiser. You'll only know that the format is valid, but you still don't know if it's an active e-mail address. The only way to find out, is by sending a confirmation e-mail.

When to use NSInteger vs. int

OS X is "LP64". This means that:

int is always 32-bits.

long long is always 64-bits.

NSInteger and long are always pointer-sized. That means they're 32-bits on 32-bit systems, and 64 bits on 64-bit systems.

The reason NSInteger exists is because many legacy APIs incorrectly used int instead of long to hold pointer-sized variables, which meant that the APIs had to change from int to long in their 64-bit versions. In other words, an API would have different function signatures depending on whether you're compiling for 32-bit or 64-bit architectures. NSInteger intends to mask this problem with these legacy APIs.

In your new code, use int if you need a 32-bit variable, long long if you need a 64-bit integer, and long or NSInteger if you need a pointer-sized variable.

Convert varchar into datetime in SQL Server

use Try_Convert:Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

DECLARE @DateString VARCHAR(10) ='20160805'
SELECT TRY_CONVERT(DATETIME,@DateString)

SET @DateString ='Invalid Date'
SELECT TRY_CONVERT(DATETIME,@DateString)

Link:MSDN TRY_CONVERT (Transact-SQL)

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

Syntactic sugar, makes it more obvious to the casual reader that the join isn't an inner one.

How to echo out table rows from the db (php)

$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
    echo "<tr>";
    foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
        echo "<td>" . $value . "</td>"; 
    }
    echo "</tr>";
}
echo "</table>";

In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

I found another solution for new Sonar versions where JaCoCo's binary report format (*.exec) was deprecated and the preferred format is XML (SonarJava 5.12 and higher). The solution is very simple and similar to the previous solution with *.exec reports in parent directory from this topic: https://stackoverflow.com/a/15535970/4448263.

Assuming that our project structure is:

moduleC - aggregate project's pom
  |- moduleA - some classes without tests
  |- moduleB - some classes depending from moduleA and tests for classes in both modules: moduleA and moduleB

You need following maven build plugin configuration in aggregate project's pom:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.5</version>
    <executions>
        <execution>
            <id>prepare-and-report</id>
            <goals>
                <goal>prepare-agent</goal>
                <goal>report</goal>
            </goals>
        </execution>
        <execution>
            <id>report-aggregate</id>
            <phase>verify</phase>
            <goals>
                <goal>report-aggregate</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.basedir}/../target/site/jacoco-aggregate</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

Then build project with maven:

mvn clean verify

And for Sonar you should set property in administration GUI:

sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml,../target/site/jacoco-aggregate/jacoco.xml

or using command line:

mvn sonar:sonar -Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml,../target/site/jacoco-aggregate/jacoco.xml

Description

This creates binary reports for each module in default directories: target/jacoco.exec. Then creates XML reports for each module in default directories: target/site/jacoco/jacoco.xml. Then creates an aggregate report for each module in custom directory ${project.basedir}/../target/site/jacoco-aggregate/ that is relative to parent directory for each module. For moduleA and moduleB this will be common path moduleC/target/site/jacoco-aggregate/.

As moduleB depends on moduleA, moduleB will be built last and its report will be used as an aggregate coverage report in Sonar for both modules A and B.

In addition to the aggregate report, we need a normal module report as JaCoCo aggregate reports contain coverage data only for dependencies.

Together, these two types of reports providing full coverage data for Sonar.

There is one little restriction: you should be able to write a report in the project's parent directory (should have permission). Or you can set property jacoco.skip=true in root project's pom.xml (moduleC) and jacoco.skip=false in modules with classes and tests (moduleA and moduleB).

How to increase maximum execution time in php

use below statement if safe_mode is off

set_time_limit(0);

How to get the absolute path to the public_html folder?

Out of curiosity, why don't you just use the url for the said folder?

http://www.mysite.com/images

Assuming that the folder never changes location, that would be the easiest way to do it.

SQL Server using wildcard within IN

How about something like this?

declare @search table
(
    searchString varchar(10)
)

-- add whatever criteria you want...
insert into @search select '0711%' union select '0712%'

select j.*
from jobdetails j
    join @search s on j.job_no like s.searchString

Copy from one workbook and paste into another

This should do it, let me know if you have trouble with it:

Sub foo()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy

'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial

'Close x:
x.Close

End Sub

Alternatively, you could just:

Sub foo2()
Dim x As Workbook
Dim y As Workbook

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1") 

'Close x:
x.Close

End Sub

To extend this to the entire sheet:

With x.Sheets("name of copying sheet").UsedRange
    'Now, paste to y worksheet:
    y.Sheets("sheet name").Range("A1").Resize( _
        .Rows.Count, .Columns.Count) = .Value
End With

And yet another way, store the value as a variable and write the variable to the destination:

Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant

'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value

'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals 

'Close x:
x.Close

End Sub

The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:

Copy/PasteSpecial vs Range.Value = Range.Value

That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.

In C++ check if std::vector<string> contains a certain value

  1. If your container only contains unique values, consider using std::set instead. It allows querying of set membership with logarithmic complexity.

     std::set<std::string> s;
     s.insert("abc");
     s.insert("xyz");
     if (s.find("abc") != s.end()) { ...
    
  2. If your vector is kept sorted, use std::binary_search, it offers logarithmic complexity as well.

  3. If all else fails, fall back to std::find, which is a simple linear search.

Rails DB Migration - How To Drop a Table?

The simple and official way would be this:

  rails g migration drop_tablename

Now go to your db/migrate and look for your file which contains the drop_tablename as the filename and edit it to this.

    def change
      drop_table :table_name
    end

Then you need to run

    rake db:migrate 

on your console.

How to change date format using jQuery?

You can use date.js to achieve this:

var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');

Alternatively, you can do it natively like this:

_x000D_
_x000D_
var dateAr = '2014-01-06'.split('-');_x000D_
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);_x000D_
_x000D_
console.log(newDate);
_x000D_
_x000D_
_x000D_

Passing data to a jQuery UI Dialog

In terms of what you are doing with jQuery, my understanding is that you can chain functions like you have and the inner ones have access to variables from the outer ones. So is your ShowDialog(x) function contains these other functions, you can re-use the x variable within them and it will be taken as a reference to the parameter from the outer function.

I agree with mausch, you should really look at using POST for these actions, which will add a <form> tag around each element, but make the chances of an automated script or tool triggering the Cancel event much less likely. The Change action can remain as is because it (presumably just opens an edit form).

Recyclerview and handling different type of row inflation

You have to implement getItemViewType() method in RecyclerView.Adapter. By default onCreateViewHolder(ViewGroup parent, int viewType) implementation viewType of this method returns 0. Firstly you need view type of the item at position for the purposes of view recycling and for that you have to override getItemViewType() method in which you can pass viewType which will return your position of item. Code sample is given below

@Override
public MyViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
    int listViewItemType = getItemViewType(viewType);
    switch (listViewItemType) {
         case 0: return new ViewHolder0(...);
         case 2: return new ViewHolder2(...);
    }
}

@Override
public int getItemViewType(int position) {   
    return position;
}

// and in the similar way you can set data according 
// to view holder position by passing position in getItemViewType
@Override
public void onBindViewHolder(MyViewholder viewholder, int position) {
    int listViewItemType = getItemViewType(position);
    // ...
}

Python 3.1.1 string to hex

binascii methodes are easier by the way

>>> import binascii
>>> x=b'test'
>>> x=binascii.hexlify(x)
>>> x
b'74657374'
>>> y=str(x,'ascii')
>>> y
'74657374'
>>> x=binascii.unhexlify(x)
>>> x
b'test'
>>> y=str(x,'ascii')
>>> y
'test'

Hope it helps. :)

Download data url file

Your problem essentially boils down to "not all browsers will support this".

You could try a workaround and serve the unzipped files from a Flash object, but then you'd lose the JS-only purity (anyway, I'm not sure whether you currently can "drag files into browser" without some sort of Flash workaround - is that a HTML5 feature maybe?)

SQL SERVER, SELECT statement with auto generate row id

Here is a simple method which ranks the rows after however they are ordered, i.e. inserted in your table. In your SELECT statement simply add the field

ROW_NUMBER() OVER (ORDER BY CAST(GETDATE() AS TIMESTAMP)) AS RowNumber.

Apply pandas function to column to create multiple new columns?

This is what I've done in the past

df = pd.DataFrame({'textcol' : np.random.rand(5)})

df
    textcol
0  0.626524
1  0.119967
2  0.803650
3  0.100880
4  0.017859

df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1}))
   feature1  feature2
0  1.626524 -0.373476
1  1.119967 -0.880033
2  1.803650 -0.196350
3  1.100880 -0.899120
4  1.017859 -0.982141

Editing for completeness

pd.concat([df, df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1}))], axis=1)
    textcol feature1  feature2
0  0.626524 1.626524 -0.373476
1  0.119967 1.119967 -0.880033
2  0.803650 1.803650 -0.196350
3  0.100880 1.100880 -0.899120
4  0.017859 1.017859 -0.982141

Running conda with proxy

The best way I settled with is to set proxy environment variables right before using conda or pip install/update commands. Simply run:

set HTTP_PROXY=http://username:password@proxy_url:port

For example, your actual command could be like

set HTTP_PROXY=http://yourname:[email protected]_company.com:8080

If your company uses https proxy, then also

set HTTPS_PROXY=https://username:password@proxy_url:port

Once you exit Anaconda prompt then this setting is gone, so your username/password won't be saved after the session.

I didn't choose other methods mentioned in Anaconda documentation or some other sources, because they all require hardcoding of username/password into

  • Windows environment variables (also this requires restart of Anaconda prompt for the first time)
  • Conda .condarc or .netrc configuration files (also this won't work for PIP)
  • A batch/script file loaded while starting Anaconda prompt (also this might require configuring the path)

All of these are unsafe and will require constant update later. And if you forget where to update? More troubleshooting will come your way...

How to export data from Spark SQL to CSV

enter code here IN DATAFRAME:

val p=spark.read.format("csv").options(Map("header"->"true","delimiter"->"^")).load("filename.csv")

How to get the second column from command output?

If you could use something other than 'awk' , then try this instead

echo '1540 "A B"' | cut -d' ' -f2-

-d is a delimiter, -f is the field to cut and with -f2- we intend to cut the 2nd field until end.

How to start an Android application from the command line?

You can use:

adb shell monkey -p com.package.name -c android.intent.category.LAUNCHER 1

This will start the LAUNCHER Activity of the application using monkeyrunner test tool.

Volley JsonObjectRequest Post request not working

Easy one for me ! I got it few weeks ago :

This goes in getBody() method, not in getParams() for a post request.

Here is mine :

    @Override
/**
 * Returns the raw POST or PUT body to be sent.
 *
 * @throws AuthFailureError in the event of auth failure
 */
public byte[] getBody() throws AuthFailureError {
    //        Map<String, String> params = getParams();
    Map<String, String> params = new HashMap<String, String>();
    params.put("id","1");
    params.put("name", "myname");
    if (params != null && params.size() > 0) {
        return encodeParameters(params, getParamsEncoding());
    }
    return null;

}

(I assumed you want to POST the params you wrote in your getParams)

I gave the params to the request inside the constructor, but since you are creating the request on the fly, you can hard coded them inside your override of the getBody() method.

This is what my code looks like :

    Bundle param = new Bundle();
    param.putString(HttpUtils.HTTP_CALL_TAG_KEY, tag);
    param.putString(HttpUtils.HTTP_CALL_PATH_KEY, url);
    param.putString(HttpUtils.HTTP_CALL_PARAM_KEY, params);

    switch (type) {
    case RequestType.POST:
        param.putInt(HttpUtils.HTTP_CALL_TYPE_KEY, RequestType.POST);
        SCMainActivity.mRequestQueue.add(new SCRequestPOST(Method.POST, url, this, tag, receiver, params));

and if you want even more this last string params comes from :

param = JsonUtils.XWWWUrlEncoder.encode(new JSONObject(paramasJObj)).toString();

and the paramasJObj is something like this : {"id"="1","name"="myname"} the usual JSON string.

What does 'var that = this;' mean in JavaScript?

Here is an example `

$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();

            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                    var imgAlt = $(this).find('img').attr('alt'); //Here value of "this" is '.our-work-single-page'. 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

So you can see that value of this is two different values depending on the DOM element you target but when you add "that" to the code above you change the value of "this" you are targeting.

`$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();
            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                var that = this;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                   ***$(that).css("background-color", "#ffe700");*** //Here value of "that" is ".our-work-group > p > a"....
                    var imgAlt = $(this).find('img').attr('alt'); 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

.....$(that).css("background-color", "#ffe700"); //Here value of "that" is ".our-work-group > p > a" because the value of var that = this; so even though we are at "this"= '.our-work-single-page', still we can use "that" to manipulate previous DOM element.

Cannot connect to Database server (mysql workbench)

Run the ALTER USER command. Be sure to change password to a strong password of your choosing.

  1. sudo mysql # Login to mysql`

  2. Run the below command

    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
    

Now you can access it by using the new password.

Ref : https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-18-04

What is the use of static synchronized method in java?

In general, synchronized methods are used to protect access to resources that are accessed concurrently. When a resource that is being accessed concurrently belongs to each instance of your class, you use a synchronized instance method; when the resource belongs to all instances (i.e. when it is in a static variable) then you use a synchronized static method to access it.

For example, you could make a static factory method that keeps a "registry" of all objects that it has produced. A natural place for such registry would be a static collection. If your factory is used from multiple threads, you need to make the factory method synchronized (or have a synchronized block inside the method) to protect access to the shared static collection.

Note that using synchronized without a specific lock object is generally not the safest choice when you are building a library to be used in code written by others. This is because malicious code could synchronize on your object or a class to block your own methods from executing. To protect your code against this, create a private "lock" object, instance or static, and synchronize on that object instead.

How to split one text file into multiple *.txt files?

John's answer won't produce .txt files as the OP wants. Use:

split -b=1M -d  file.txt file --additional-suffix=.txt

Can an abstract class have a constructor?

Of Course, abstract class can have a constructor.Generally class constructor is used to initialise fields.So, an abstract class constructor is used to initialise fields of the abstract class. You would provide a constructor for an abstract class if you want to initialise certain fields of the abstract class before the instantiation of a child-class takes place. An abstract class constructor can also be used to execute code that is relevant for every child class. This prevents code duplication.

We cannot create an instance of an abstract class,But we can create instances of classes those are derived from the abstract class. So, when an instance of derived class is created, the parent abstract class constructor is automatically called.

Reference :This Article

Use and meaning of "in" in an if statement?

You are used to using the javascript if, and I assume you know how it works.

in is a Pythonic way of implementing iteration. It's supposed to be easier for non-programmatic thinkers to adopt, but that can sometimes make it harder for programmatic thinkers, ironically.

When you say if x in y, you are literally saying:

"if x is in y", which assumes that y has an index. In that if statement then, each object at each index in y is checked against the condition.

Similarly,

for x in y

iterates through x's in y, where y is that indexable set of items.

Think of the if situation this way (pseudo-code):

for i in next:
    if i == "0" || i == "1":
        how_much = int(next)

It takes care of the iteration over next for you.

Happy coding!

How do you append an int to a string in C++?

Your example seems to indicate that you would like to display the a string followed by an integer, in which case:

string text = "Player: ";
int i = 4;
cout << text << i << endl;

would work fine.

But, if you're going to be storing the string places or passing it around, and doing this frequently, you may benefit from overloading the addition operator. I demonstrate this below:

#include <sstream>
#include <iostream>
using namespace std;

std::string operator+(std::string const &a, int b) {
  std::ostringstream oss;
  oss << a << b;
  return oss.str();
}

int main() {
  int i = 4;
  string text = "Player: ";
  cout << (text + i) << endl;
}

In fact, you can use templates to make this approach more powerful:

template <class T>
std::string operator+(std::string const &a, const T &b){
  std::ostringstream oss;
  oss << a << b;
  return oss.str();
}

Now, as long as object b has a defined stream output, you can append it to your string (or, at least, a copy thereof).

Matlab: Running an m-file from command-line

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

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

How to convert a String to CharSequence?

Attempting to provide some (possible) context for OP's question by posting my own trouble. I'm working in Scala, but the error messages I'm getting all reference Java types, and the error message reads a lot like the compiler complaining that CharSequence is not a String. I confirmed in the source code that String implements the CharSequence interface, but the error message draws attention to the difference between String and CharSequence while hiding the real source of the trouble:

scala> cols
res8: Iterable[String] = List(Item, a, b)

scala> val header = String.join(",", cols)
<console>:13: error: overloaded method value join with alternatives:
  (x$1: CharSequence,x$2: java.lang.Iterable[_ <: CharSequence])String <and>
  (x$1: CharSequence,x$2: CharSequence*)String
 cannot be applied to (String, Iterable[String])
       val header = String.join(",", cols)

I was able to fix this problem with the realization that the problem wasn't String / CharSequence, but rather a mismatch between java.lang.Iterable and Scala's built-in Iterable.

scala> val header = String.join(",", coll: _*)
header: String = Item,a,b

My particular problem can also be solved via the answers at Scala: join an iterable of strings

In summary, OP and others who come across similar problems should parse the error messages very closely and see what other type conversions might be involved.

How to resize superview to fit all subviews with autolayout?

The correct API to use is UIView systemLayoutSizeFittingSize:, passing either UILayoutFittingCompressedSize or UILayoutFittingExpandedSize.

For a normal UIView using autolayout this should just work as long as your constraints are correct. If you want to use it on a UITableViewCell (to determine row height for example) then you should call it against your cell contentView and grab the height.

Further considerations exist if you have one or more UILabel's in your view that are multiline. For these it is imperitive that the preferredMaxLayoutWidth property be set correctly such that the label provides a correct intrinsicContentSize, which will be used in systemLayoutSizeFittingSize's calculation.

EDIT: by request, adding example of height calculation for a table view cell

Using autolayout for table-cell height calculation isn't super efficient but it sure is convenient, especially if you have a cell that has a complex layout.

As I said above, if you're using a multiline UILabel it's imperative to sync the preferredMaxLayoutWidth to the label width. I use a custom UILabel subclass to do this:

@implementation TSLabel

- (void) layoutSubviews
{
    [super layoutSubviews];

    if ( self.numberOfLines == 0 )
    {
        if ( self.preferredMaxLayoutWidth != self.frame.size.width )
        {
            self.preferredMaxLayoutWidth = self.frame.size.width;
            [self setNeedsUpdateConstraints];
        }
    }
}

- (CGSize) intrinsicContentSize
{
    CGSize s = [super intrinsicContentSize];

    if ( self.numberOfLines == 0 )
    {
        // found out that sometimes intrinsicContentSize is 1pt too short!
        s.height += 1;
    }

    return s;
}

@end

Here's a contrived UITableViewController subclass demonstrating heightForRowAtIndexPath:

#import "TSTableViewController.h"
#import "TSTableViewCell.h"

@implementation TSTableViewController

- (NSString*) cellText
{
    return @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
}

#pragma mark - Table view data source

- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView
{
    return 1;
}

- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger) section
{
    return 1;
}

- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
    static TSTableViewCell *sizingCell;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        sizingCell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell"];
    });

    // configure the cell
    sizingCell.text = self.cellText;

    // force layout
    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];

    // get the fitting size
    CGSize s = [sizingCell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize];
    NSLog( @"fittingSize: %@", NSStringFromCGSize( s ));

    return s.height;
}

- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
    TSTableViewCell *cell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell" ];

    cell.text = self.cellText;

    return cell;
}

@end

A simple custom cell:

#import "TSTableViewCell.h"
#import "TSLabel.h"

@implementation TSTableViewCell
{
    IBOutlet TSLabel* _label;
}

- (void) setText: (NSString *) text
{
    _label.text = text;
}

@end

And, here's a picture of the constraints defined in the Storyboard. Note that there are no height/width constraints on the label - those are inferred from the label's intrinsicContentSize:

enter image description here

How do you extract a column from a multi-dimensional array?

All columns from a matrix into a new list:

N = len(matrix) 
column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]

Angular 2 optional route parameter

{path: 'users', redirectTo: 'users/', pathMatch: 'full'},
{path: 'users/:userId', component: UserComponent}

This way the component isn't re-rendered when the parameter is added.

How to debug a Flask app

From the 1.1.x documentation, you can enable debug mode by exporting an environment variable to your shell prompt:

export FLASK_APP=/daemon/api/views.py  # path to app
export FLASK_DEBUG=1
python -m flask run --host=0.0.0.0

Are the days of passing const std::string & as a parameter over?

IMO using the C++ reference for std::string is a quick and short local optimization, while using passing by value could be (or not) a better global optimization.

So the answer is: it depends on circumstances:

  1. If you write all the code from the outside to the inside functions, you know what the code does, you can use the reference const std::string &.
  2. If you write the library code or use heavily library code where strings are passed, you likely gain more in global sense by trusting std::string copy constructor behavior.

Spark java.lang.OutOfMemoryError: Java heap space

I have a few suggestions:

  • If your nodes are configured to have 6g maximum for Spark (and are leaving a little for other processes), then use 6g rather than 4g, spark.executor.memory=6g. Make sure you're using as much memory as possible by checking the UI (it will say how much mem you're using)
  • Try using more partitions, you should have 2 - 4 per CPU. IME increasing the number of partitions is often the easiest way to make a program more stable (and often faster). For huge amounts of data you may need way more than 4 per CPU, I've had to use 8000 partitions in some cases!
  • Decrease the fraction of memory reserved for caching, using spark.storage.memoryFraction. If you don't use cache() or persist in your code, this might as well be 0. It's default is 0.6, which means you only get 0.4 * 4g memory for your heap. IME reducing the mem frac often makes OOMs go away. UPDATE: From spark 1.6 apparently we will no longer need to play with these values, spark will determine them automatically.
  • Similar to above but shuffle memory fraction. If your job doesn't need much shuffle memory then set it to a lower value (this might cause your shuffles to spill to disk which can have catastrophic impact on speed). Sometimes when it's a shuffle operation that's OOMing you need to do the opposite i.e. set it to something large, like 0.8, or make sure you allow your shuffles to spill to disk (it's the default since 1.0.0).
  • Watch out for memory leaks, these are often caused by accidentally closing over objects you don't need in your lambdas. The way to diagnose is to look out for the "task serialized as XXX bytes" in the logs, if XXX is larger than a few k or more than an MB, you may have a memory leak. See https://stackoverflow.com/a/25270600/1586965
  • Related to above; use broadcast variables if you really do need large objects.
  • If you are caching large RDDs and can sacrifice some access time consider serialising the RDD http://spark.apache.org/docs/latest/tuning.html#serialized-rdd-storage. Or even caching them on disk (which sometimes isn't that bad if using SSDs).
  • (Advanced) Related to above, avoid String and heavily nested structures (like Map and nested case classes). If possible try to only use primitive types and index all non-primitives especially if you expect a lot of duplicates. Choose WrappedArray over nested structures whenever possible. Or even roll out your own serialisation - YOU will have the most information regarding how to efficiently back your data into bytes, USE IT!
  • (bit hacky) Again when caching, consider using a Dataset to cache your structure as it will use more efficient serialisation. This should be regarded as a hack when compared to the previous bullet point. Building your domain knowledge into your algo/serialisation can minimise memory/cache-space by 100x or 1000x, whereas all a Dataset will likely give is 2x - 5x in memory and 10x compressed (parquet) on disk.

http://spark.apache.org/docs/1.2.1/configuration.html

EDIT: (So I can google myself easier) The following is also indicative of this problem:

java.lang.OutOfMemoryError : GC overhead limit exceeded

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

Datagridview: How to set a cell in editing mode?

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.Handled = true;
            DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.CurrentCell = cell;
            dataGridView1.BeginEdit(true);               
        }
    }

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

MySQL Error: #1142 - SELECT command denied to user

You should have to just clear sessions data thats it everything will work

How to compute the similarity between two text documents?

If you are more interested in measuring semantic similarity of two pieces of text, I suggest take a look at this gitlab project. You can run it as a server, there is also a pre-built model which you can use easily to measure the similarity of two pieces of text; even though it is mostly trained for measuring the similarity of two sentences, you can still use it in your case.It is written in java but you can run it as a RESTful service.

Another option also is DKPro Similarity which is a library with various algorithm to measure the similarity of texts. However, it is also written in java.

code example:

// this similarity measure is defined in the dkpro.similarity.algorithms.lexical-asl package
// you need to add that to your .pom to make that example work
// there are some examples that should work out of the box in dkpro.similarity.example-gpl 
TextSimilarityMeasure measure = new WordNGramJaccardMeasure(3);    // Use word trigrams

String[] tokens1 = "This is a short example text .".split(" ");   
String[] tokens2 = "A short example text could look like that .".split(" ");

double score = measure.getSimilarity(tokens1, tokens2);

System.out.println("Similarity: " + score);

Javascript: best Singleton pattern

Extending the above post by Tom, if you need a class type declaration and access the singleton instance using a variable, the code below might be of help. I like this notation as the code is little self guiding.

function SingletonClass(){
    if ( arguments.callee.instance )
        return arguments.callee.instance;
    arguments.callee.instance = this;
}


SingletonClass.getInstance = function() {
    var singletonClass = new SingletonClass();
    return singletonClass;
};

To access the singleton, you would

var singleTon = SingletonClass.getInstance();

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Quoting from the gcc website:

C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.

So probably you use a version of g++ which doesn't support -std=c++11. Try -std=c++0x instead.

Availability of C++11 features is for versions >= 4.3 only.

How to check if object property exists with a variable holding the property name?

var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}

Or

var myProp = 'prop';
if(myProp in myObj){
    alert("yes, i have that property");
}

Or

if('prop' in myObj){
    alert("yes, i have that property");
}

Note that hasOwnProperty doesn't check for inherited properties, whereas in does. For example 'constructor' in myObj is true, but myObj.hasOwnProperty('constructor') is not.

How do I profile memory usage in Python?

Python 3.4 includes a new module: tracemalloc. It provides detailed statistics about which code is allocating the most memory. Here's an example that displays the top three lines allocating memory.

from collections import Counter
import linecache
import os
import tracemalloc

def display_top(snapshot, key_type='lineno', limit=3):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        print("#%s: %s:%s: %.1f KiB"
              % (index, filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))


tracemalloc.start()

counts = Counter()
fname = '/usr/share/dict/american-english'
with open(fname) as words:
    words = list(words)
    for word in words:
        prefix = word[:3]
        counts[prefix] += 1
print('Top prefixes:', counts.most_common(3))

snapshot = tracemalloc.take_snapshot()
display_top(snapshot)

And here are the results:

Top prefixes: [('con', 1220), ('dis', 1002), ('pro', 809)]
Top 3 lines
#1: scratches/memory_test.py:37: 6527.1 KiB
    words = list(words)
#2: scratches/memory_test.py:39: 247.7 KiB
    prefix = word[:3]
#3: scratches/memory_test.py:40: 193.0 KiB
    counts[prefix] += 1
4 other: 4.3 KiB
Total allocated size: 6972.1 KiB

When is a memory leak not a leak?

That example is great when the memory is still being held at the end of the calculation, but sometimes you have code that allocates a lot of memory and then releases it all. It's not technically a memory leak, but it's using more memory than you think it should. How can you track memory usage when it all gets released? If it's your code, you can probably add some debugging code to take snapshots while it's running. If not, you can start a background thread to monitor memory usage while the main thread runs.

Here's the previous example where the code has all been moved into the count_prefixes() function. When that function returns, all the memory is released. I also added some sleep() calls to simulate a long-running calculation.

from collections import Counter
import linecache
import os
import tracemalloc
from time import sleep


def count_prefixes():
    sleep(2)  # Start up time.
    counts = Counter()
    fname = '/usr/share/dict/american-english'
    with open(fname) as words:
        words = list(words)
        for word in words:
            prefix = word[:3]
            counts[prefix] += 1
            sleep(0.0001)
    most_common = counts.most_common(3)
    sleep(3)  # Shut down time.
    return most_common


def main():
    tracemalloc.start()

    most_common = count_prefixes()
    print('Top prefixes:', most_common)

    snapshot = tracemalloc.take_snapshot()
    display_top(snapshot)


def display_top(snapshot, key_type='lineno', limit=3):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        print("#%s: %s:%s: %.1f KiB"
              % (index, filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))


main()

When I run that version, the memory usage has gone from 6MB down to 4KB, because the function released all its memory when it finished.

Top prefixes: [('con', 1220), ('dis', 1002), ('pro', 809)]
Top 3 lines
#1: collections/__init__.py:537: 0.7 KiB
    self.update(*args, **kwds)
#2: collections/__init__.py:555: 0.6 KiB
    return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
#3: python3.6/heapq.py:569: 0.5 KiB
    result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]
10 other: 2.2 KiB
Total allocated size: 4.0 KiB

Now here's a version inspired by another answer that starts a second thread to monitor memory usage.

from collections import Counter
import linecache
import os
import tracemalloc
from datetime import datetime
from queue import Queue, Empty
from resource import getrusage, RUSAGE_SELF
from threading import Thread
from time import sleep

def memory_monitor(command_queue: Queue, poll_interval=1):
    tracemalloc.start()
    old_max = 0
    snapshot = None
    while True:
        try:
            command_queue.get(timeout=poll_interval)
            if snapshot is not None:
                print(datetime.now())
                display_top(snapshot)

            return
        except Empty:
            max_rss = getrusage(RUSAGE_SELF).ru_maxrss
            if max_rss > old_max:
                old_max = max_rss
                snapshot = tracemalloc.take_snapshot()
                print(datetime.now(), 'max RSS', max_rss)


def count_prefixes():
    sleep(2)  # Start up time.
    counts = Counter()
    fname = '/usr/share/dict/american-english'
    with open(fname) as words:
        words = list(words)
        for word in words:
            prefix = word[:3]
            counts[prefix] += 1
            sleep(0.0001)
    most_common = counts.most_common(3)
    sleep(3)  # Shut down time.
    return most_common


def main():
    queue = Queue()
    poll_interval = 0.1
    monitor_thread = Thread(target=memory_monitor, args=(queue, poll_interval))
    monitor_thread.start()
    try:
        most_common = count_prefixes()
        print('Top prefixes:', most_common)
    finally:
        queue.put('stop')
        monitor_thread.join()


def display_top(snapshot, key_type='lineno', limit=3):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        print("#%s: %s:%s: %.1f KiB"
              % (index, filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))


main()

The resource module lets you check the current memory usage, and save the snapshot from the peak memory usage. The queue lets the main thread tell the memory monitor thread when to print its report and shut down. When it runs, it shows the memory being used by the list() call:

2018-05-29 10:34:34.441334 max RSS 10188
2018-05-29 10:34:36.475707 max RSS 23588
2018-05-29 10:34:36.616524 max RSS 38104
2018-05-29 10:34:36.772978 max RSS 45924
2018-05-29 10:34:36.929688 max RSS 46824
2018-05-29 10:34:37.087554 max RSS 46852
Top prefixes: [('con', 1220), ('dis', 1002), ('pro', 809)]
2018-05-29 10:34:56.281262
Top 3 lines
#1: scratches/scratch.py:36: 6527.0 KiB
    words = list(words)
#2: scratches/scratch.py:38: 16.4 KiB
    prefix = word[:3]
#3: scratches/scratch.py:39: 10.1 KiB
    counts[prefix] += 1
19 other: 10.8 KiB
Total allocated size: 6564.3 KiB

If you're on Linux, you may find /proc/self/statm more useful than the resource module.

Android ListView Text Color

if you didnot set your activity style it shows you black background .if you want to make changes such as white background, black text of listview then it is difficult process.

ADD android:theme="@style/AppTheme" in Android Manifest.

Trigger insert old values- values that was updated

    createTRIGGER [dbo].[Table] ON [dbo].[table] 
FOR UPDATE
AS
    declare @empid int;
    declare @empname varchar(100);
    declare @empsal decimal(10,2);
    declare @audit_action varchar(100);
    declare @old_v varchar(100)

    select @empid=i.Col_Name1 from inserted i;  
    select @empname=i.Col_Name2  from inserted i;   
    select @empsal=i.Col_Name2 from inserted i;
    select @old_v=d.Col_Name from deleted d

    if update(Col_Name1)
        set @audit_action='Updated Record -- After Update Trigger.';
    if update(Col_Name2)
        set @audit_action='Updated Record -- After Update Trigger.';

    insert into Employee_Test_Audit1(Col_name1,Col_name2,Col_name3,Col_name4,Col_name5,Col_name6(Old_values)) 
    values(@empid,@empname,@empsal,@audit_action,getdate(),@old_v);

    PRINT '----AFTER UPDATE Trigger fired-----.'

how to check which version of nltk, scikit learn installed?

import nltk is Python syntax, and as such won't work in a shell script.

To test the version of nltk and scikit_learn, you can write a Python script and run it. Such a script may look like

import nltk
import sklearn

print('The nltk version is {}.'.format(nltk.__version__))
print('The scikit-learn version is {}.'.format(sklearn.__version__))

# The nltk version is 3.0.0.
# The scikit-learn version is 0.15.2.

Note that not all Python packages are guaranteed to have a __version__ attribute, so for some others it may fail, but for nltk and scikit-learn at least it will work.

Retrieve filename from file descriptor in C

As Tyler points out, there's no way to do what you require "directly and reliably", since a given FD may correspond to 0 filenames (in various cases) or > 1 (multiple "hard links" is how the latter situation is generally described). If you do still need the functionality with all the limitations (on speed AND on the possibility of getting 0, 2, ... results rather than 1), here's how you can do it: first, fstat the FD -- this tells you, in the resulting struct stat, what device the file lives on, how many hard links it has, whether it's a special file, etc. This may already answer your question -- e.g. if 0 hard links you will KNOW there is in fact no corresponding filename on disk.

If the stats give you hope, then you have to "walk the tree" of directories on the relevant device until you find all the hard links (or just the first one, if you don't need more than one and any one will do). For that purpose, you use readdir (and opendir &c of course) recursively opening subdirectories until you find in a struct dirent thus received the same inode number you had in the original struct stat (at which time if you want the whole path, rather than just the name, you'll need to walk the chain of directories backwards to reconstruct it).

If this general approach is acceptable, but you need more detailed C code, let us know, it won't be hard to write (though I'd rather not write it if it's useless, i.e. you cannot withstand the inevitably slow performance or the possibility of getting != 1 result for the purposes of your application;-).

Call a function after previous function is complete

Specify an anonymous callback, and make function1 accept it:

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable, function() {
          function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});


function function1(param, callback) {
  ...do stuff
  callback();
} 

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

Edit seaborn legend

If you just want to change the legend title, you can do the following:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=True
)

g._legend.set_title("New Title")

What is this date format? 2011-08-12T20:17:46.384Z

tl;dr

Standard ISO 8601 format is used by your input string.

Instant.parse ( "2011-08-12T20:17:46.384Z" ) 

ISO 8601

This format is defined by the sensible practical standard, ISO 8601.

The T separates the date portion from the time-of-day portion. The Z on the end means UTC (that is, an offset-from-UTC of zero hours-minutes-seconds). The Z is pronounced “Zulu”.

java.time

The old date-time classes bundled with the earliest versions of Java have proven to be poorly designed, confusing, and troublesome. Avoid them.

Instead, use the java.time framework built into Java 8 and later. The java.time classes supplant both the old date-time classes and the highly successful Joda-Time library.

The java.time classes use ISO 8601 by default when parsing/generating textual representations of date-time values.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds. That class can directly parse your input string without bothering to define a formatting pattern.

Instant instant = Instant.parse ( "2011-08-12T20:17:46.384Z" ) ;

Table of date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

Run-time error '1004' - Method 'Range' of object'_Global' failed

When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.

If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.

inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.

The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like

With ThisWorkbook.Worksheets("Template")
    .Range(inputTemplateHeader).Value = NO_ENTRY
    .Range(inputTemplateContent).Value = NO_ENTRY
End With

Adjust the workbook and worksheet references to fit your particular situation.

Get the length of a String

As of Swift 4+

It's just:

test1.count

for reasons.

(Thanks to Martin R)

As of Swift 2:

With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is:

test1.characters.count

(Thanks to JohnDifool for the heads up)

As of Swift 1

Use the count characters method:

let unusualMenagerie = "Koala &#128040;, Snail &#128012;, Penguin &#128039;, Dromedary &#128042;"
println("unusualMenagerie has \(count(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"

right from the Apple Swift Guide

(note, for versions of Swift earlier than 1.2, this would be countElements(unusualMenagerie) instead)

for your variable, it would be

length = count(test1) // was countElements in earlier versions of Swift

Or you can use test1.utf16count

How to implement a binary search tree in Python?

Another Python BST solution

class Node(object):
    def __init__(self, value):
        self.left_node = None
        self.right_node = None
        self.value = value

    def __str__(self):
        return "[%s, %s, %s]" % (self.left_node, self.value, self.right_node)

    def insertValue(self, new_value):
        """
        1. if current Node doesnt have value then assign to self
        2. new_value lower than current Node's value then go left
        2. new_value greater than current Node's value then go right
        :return:
        """
        if self.value:
            if new_value < self.value:
                # add to left
                if self.left_node is None:  # reached start add value to start
                    self.left_node = Node(new_value)
                else:
                    self.left_node.insertValue(new_value)  # search
            elif new_value > self.value:
                # add to right
                if self.right_node is None:  # reached end add value to end
                    self.right_node = Node(new_value)
                else:
                    self.right_node.insertValue(new_value)  # search
        else:
            self.value = new_value

    def findValue(self, value_to_find):
        """
        1. value_to_find is equal to current Node's value then found
        2. if value_to_find is lower than Node's value then go to left
        3. if value_to_find is greater than Node's value then go to right
        """
        if value_to_find == self.value:
            return "Found"
        elif value_to_find < self.value and self.left_node:
            return self.left_node.findValue(value_to_find)
        elif value_to_find > self.value and self.right_node:
            return self.right_node.findValue(value_to_find)
        return "Not Found"

    def printTree(self):
        """
        Nodes will be in sequence
        1. Print LHS items
        2. Print value of node
        3. Print RHS items
        """
        if self.left_node:
            self.left_node.printTree()
        print(self.value),
        if self.right_node:
            self.right_node.printTree()

    def isEmpty(self):
        return self.left_node == self.right_node == self.value == None


def main():
    root_node = Node(12)
    root_node.insertValue(6)
    root_node.insertValue(3)
    root_node.insertValue(7)

    # should return 3 6 7 12
    root_node.printTree()

    # should return found
    root_node.findValue(7)
    # should return found
    root_node.findValue(3)
    # should return Not found
    root_node.findValue(24)

if __name__ == '__main__':
    main()

How do I create a file and write to it?

Here are some of the possible ways to create and write a file in Java :

Using FileOutputStream

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
  bw.write("Write somthing to the file ...");
  bw.newLine();
  bw.close();
} catch (FileNotFoundException e){
  // File was not found
  e.printStackTrace();
} catch (IOException e) {
  // Problem when writing to the file
  e.printStackTrace();
}

Using FileWriter

try {
  FileWriter fw = new FileWriter("myOutFile.txt");
  fw.write("Example of content");
  fw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

Using PrintWriter

try {
  PrintWriter pw = new PrintWriter("myOutFile.txt");
  pw.write("Example of content");
  pw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

Using OutputStreamWriter

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  osw.write("Soe content ...");
  osw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

For further check this tutorial about How to read and write files in Java .

Difference between return and exit in Bash functions

I don't think anyone has really fully answered the question because they don't describe how the two are used. OK, I think we know that exit kills the script, wherever it is called and you can assign a status to it as well such as exit or exit 0 or exit 7 and so forth. This can be used to determine how the script was forced to stop if called by another script, etc. Enough on exit.

return, when called, will return the value specified to indicate the function's behavior, usually a 1 or a 0. For example:

    #!/bin/bash
    isdirectory() {
      if [ -d "$1" ]
      then
        return 0
      else
        return 1
      fi
    echo "you will not see anything after the return like this text"
    }

Check like this:

    if isdirectory $1; then echo "is directory"; else echo "not a directory"; fi

Or like this:

    isdirectory || echo "not a directory"

In this example, the test can be used to indicate if the directory was found. Notice that anything after the return will not be executed in the function. 0 is true, but false is 1 in the shell, different from other programming languages.

For more information on functions: Returning Values from Bash Functions

Note: The isdirectory function is for instructional purposes only. This should not be how you perform such an option in a real script.*

How to perform OR condition in django queryset?

Both options are already mentioned in the existing answers:

from django.db.models import Q
q1 = User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

and

q2 = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)

However, there seems to be some confusion regarding which one is to prefer.

The point is that they are identical on the SQL level, so feel free to pick whichever you like!

The Django ORM Cookbook talks in some detail about this, here is the relevant part:


queryset = User.objects.filter(
        first_name__startswith='R'
    ) | User.objects.filter(
    last_name__startswith='D'
)

leads to

In [5]: str(queryset.query)
Out[5]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

and

qs = User.objects.filter(Q(first_name__startswith='R') | Q(last_name__startswith='D'))

leads to

In [9]: str(qs.query)
Out[9]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
 "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
  "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
  "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
  WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

source: django-orm-cookbook


How to negate 'isblank' function

The solution is isblank(cell)=false

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

That's probably useful for someone, who uses unittest, if imported modules use request library. To suppress warnings in requests' vendored urllib3, add

warnings.filterwarnings('ignore', message='Unverified HTTPS request')

to setUp method in your testclass, i.e:

import unittest, warnings

class MyTests(unittest.TestCase):
    
    def setUp(self):
        warnings.filterwarnings('ignore', message='Unverified HTTPS request')
    
    (all test methods here)

Get file content from URL?

Don't forget: to get HTTPS contents, your OPENSSL extension should be enabled in your php.ini. (how to get contents of site use HTTPS)

Can't find android device using "adb devices" command

restart the adb server works for me, in emulator, vmwware and virtual

adb kill-server
adb start-server

if you´re using a virtual machine, make sure you have an IP assigned with:

Alt + 1
type: netcfg

to go back:

Alt + 7

if you have:

 eth0: DOWN 0.0.0.0/XX

change your configuration to:

NAT or BRIDGE

Restart the virtual machine and server, and tried again.

if you´re using a phone or tablet:

  • unplug your device

  • wait a moment and plug it again

  • and restart the adb server

Hope this help you

CardView not showing Shadow in Android L

My recyclerview was slow in loading so by reading the stackoverflow.com I changed hardwareAccelerated to "false" then the elevation is not showing in the device. The I changed back to true. It works for me.

How to start rails server?

For the latest version of Rails (Rails 5.1.4 released September 7, 2017), you need to start Rails server like below:

hello_world_rails_project$ ./bin/rails server

=> Booting Puma
=> Rails 5.1.4 application starting in development 
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.10.0 (ruby 2.4.2-p198), codename: Russell's Teapot
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000

More help information:

hello_world_rails_project$ ./bin/rails --help

The most common rails commands are:
generate     Generate new code (short-cut alias: "g")
console      Start the Rails console (short-cut alias: "c")
server       Start the Rails server (short-cut alias: "s")
test         Run tests except system tests (short-cut alias: "t")
test:system  Run system tests
dbconsole    Start a console for the database specified in 
config/database.yml
             (short-cut alias: "db")

new          Create a new Rails application. "rails new my_app" creates a
             new application called MyApp in "./my_app"

Plotting two variables as lines using ggplot2 on the same graph

The general approach is to convert the data to long format (using melt() from package reshape or reshape2) or gather()/pivot_longer() from the tidyr package:

library("reshape2")
library("ggplot2")

test_data_long <- melt(test_data, id="date")  # convert to long format

ggplot(data=test_data_long,
       aes(x=date, y=value, colour=variable)) +
       geom_line()

ggplot2 output

Also see this question on reshaping data from wide to long.

Two HTML tables side by side, centered on the page

If it was me - I would do with the table something like this:

_x000D_
_x000D_
<style type="text/css" media="screen">_x000D_
  table {_x000D_
    border: 1px solid black;_x000D_
    float: left;_x000D_
    width: 148px;_x000D_
  }_x000D_
  _x000D_
  #table_container {_x000D_
    width: 300px;_x000D_
    margin: 0 auto;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
<div id="table_container">_x000D_
  <table>_x000D_
    <tr>_x000D_
      <th>a</th>_x000D_
      <th>b</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>9</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>16</td>_x000D_
      <td>25</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <th>a</th>_x000D_
      <th>b</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>9</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>16</td>_x000D_
      <td>25</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set specific window (frame) size in java swing?

Most layout managers work best with a component's preferredSize, and most GUI's are best off allowing the components they contain to set their own preferredSizes based on their content or properties. To use these layout managers to their best advantage, do call pack() on your top level containers such as your JFrames before making them visible as this will tell these managers to do their actions -- to layout their components.

Often when I've needed to play a more direct role in setting the size of one of my components, I'll override getPreferredSize and have it return a Dimension that is larger than the super.preferredSize (or if not then it returns the super's value).

For example, here's a small drag-a-rectangle app that I created for another question on this site:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MoveRect extends JPanel {
   private static final int RECT_W = 90;
   private static final int RECT_H = 70;
   private static final int PREF_W = 600;
   private static final int PREF_H = 300;
   private static final Color DRAW_RECT_COLOR = Color.black;
   private static final Color DRAG_RECT_COLOR = new Color(180, 200, 255);
   private Rectangle rect = new Rectangle(25, 25, RECT_W, RECT_H);
   private boolean dragging = false;
   private int deltaX = 0;
   private int deltaY = 0;

   public MoveRect() {
      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (rect != null) {
         Color c = dragging ? DRAG_RECT_COLOR : DRAW_RECT_COLOR;
         g.setColor(c);
         Graphics2D g2 = (Graphics2D) g;
         g2.draw(rect);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   private class MyMouseAdapter extends MouseAdapter {

      @Override
      public void mousePressed(MouseEvent e) {
         Point mousePoint = e.getPoint();
         if (rect.contains(mousePoint)) {
            dragging = true;
            deltaX = rect.x - mousePoint.x;
            deltaY = rect.y - mousePoint.y;
         }
      }

      @Override
      public void mouseReleased(MouseEvent e) {
         dragging = false;
         repaint();
      }

      @Override
      public void mouseDragged(MouseEvent e) {
         Point p2 = e.getPoint();
         if (dragging) {
            int x = p2.x + deltaX;
            int y = p2.y + deltaY;
            rect = new Rectangle(x, y, RECT_W, RECT_H);
            MoveRect.this.repaint();
         }
      }
   }

   private static void createAndShowGui() {
      MoveRect mainPanel = new MoveRect();

      JFrame frame = new JFrame("MoveRect");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Note that my main class is a JPanel, and that I override JPanel's getPreferredSize:

public class MoveRect extends JPanel {
   //.... deleted constants

   private static final int PREF_W = 600;
   private static final int PREF_H = 300;

   //.... deleted fields and constants

   //... deleted methods and constructors

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

Also note that when I display my GUI, I place it into a JFrame, call pack(); on the JFrame, set its position, and then call setVisible(true); on my JFrame:

   private static void createAndShowGui() {
      MoveRect mainPanel = new MoveRect();

      JFrame frame = new JFrame("MoveRect");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Escaping single quotes in JavaScript string for JavaScript evaluation

strInputString = strInputString.replace(/'/g, "''");

php implode (101) with quotes

$ids = sprintf("'%s'", implode("','", $ids ) );

Increase bootstrap dropdown menu width

Add the following css class

.dropdown-menu {
    width: 300px !important;
    height: 400px !important;
}

Of course you can use what matches your need.

Code signing is required for product type 'Application' in SDK 'iOS5.1'

You can get around this by using the simulator if you don't actually need to be deploying to a device. That solved it for me.

Most efficient way to increment a Map value in Java

Another way would be creating a mutable integer:

class MutableInt {
  int value = 0;
  public void inc () { ++value; }
  public int get () { return value; }
}
...
Map<String,MutableInt> map = new HashMap<String,MutableInt> ();
MutableInt value = map.get (key);
if (value == null) {
  value = new MutableInt ();
  map.put (key, value);
} else {
  value.inc ();
}

of course this implies creating an additional object but the overhead in comparison to creating an Integer (even with Integer.valueOf) should not be so much.

http to https through .htaccess

# Switch rewrite engine off in case this was installed under HostPay.
RewriteEngine Off

SetEnv DEFAULT_PHP_VERSION 7

DirectoryIndex index.cgi index.php

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# RewriteCond %{HTTP_HOST} ^compasscommunity.co.uk\.com$ [NC]
# RewriteRule ^(.*)$ https://www.compasscommunity.co.uk/$1 [L,R=301]

Property 'value' does not exist on type 'EventTarget'

consider $any()

<textarea (keyup)="emitWordCount($any($event))"></textarea>

Best Practice to Use HttpClient in Multithreaded Environment

I think you will want to use ThreadSafeClientConnManager.

You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html

Or in the AndroidHttpClient which uses it internally.

What is difference between @RequestBody and @RequestParam?

Here is an example with @RequestBody, First look at the controller !!

  public ResponseEntity<Void> postNewProductDto(@RequestBody NewProductDto newProductDto) {

   ...
        productService.registerProductDto(newProductDto);
        return new ResponseEntity<>(HttpStatus.CREATED);
   ....

}

And here is angular controller

function postNewProductDto() {
                var url = "/admin/products/newItem";
                $http.post(url, vm.newProductDto).then(function () {
                            //other things go here...
                            vm.newProductMessage = "Product successful registered";
                        }
                        ,
                        function (errResponse) {
                            //handling errors ....
                        }
                );
            }

And a short look at form

 <label>Name: </label>
 <input ng-model="vm.newProductDto.name" />

<label>Price </label> 
 <input ng-model="vm.newProductDto.price"/>

 <label>Quantity </label>
  <input ng-model="vm.newProductDto.quantity"/>

 <label>Image </label>
 <input ng-model="vm.newProductDto.photo"/>

 <Button ng-click="vm.postNewProductDto()" >Insert Item</Button>

 <label > {{vm.newProductMessage}} </label>

Android/Eclipse: how can I add an image in the res/drawable folder?

Do you want to add an image from your computer? Just right click the folder in Eclipse and click Import

Check for database connection, otherwise display message

Try this:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>

use jQuery's find() on JSON object

The pure javascript solution is better, but a jQuery way would be to use the jQuery grep and/or map methods. Probably not much better than using $.each

jQuery.grep(TestObj, function(obj) {
    return obj.id === "A";
});

or

jQuery.map(TestObj, function(obj) {
    if(obj.id === "A")
         return obj; // or return obj.name, whatever.
});

Returns an array of the matching objects, or of the looked-up values in the case of map. Might be able to do what you want simply using those.

But in this example you'd have to do some recursion, because the data isn't a flat array, and we're accepting arbitrary structures, keys, and values, just like the pure javascript solutions do.

function getObjects(obj, key, val) {
    var retv = [];

    if(jQuery.isPlainObject(obj))
    {
        if(obj[key] === val) // may want to add obj.hasOwnProperty(key) here.
            retv.push(obj);

        var objects = jQuery.grep(obj, function(elem) {
            return (jQuery.isArray(elem) || jQuery.isPlainObject(elem));
        });

        retv.concat(jQuery.map(objects, function(elem){
            return getObjects(elem, key, val);
        }));
    }

    return retv;
}

Essentially the same as Box9's answer, but using the jQuery utility functions where useful.

········

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

Internet Explorer 11- issue with security certificate error prompt

This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level

You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property

You can do that by following steps:

  1. Click on Gear icon at the top of the browser window.
  2. Select Internet Options.
  3. Select the Security tab at the top.
  4. Click the Custom Level... button.
  5. Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
  6. Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
  7. Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
  8. Close and restart the browser.

enter image description here

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

Failing to run jar file from command line: “no main manifest attribute”

You can select the "Runnable JAR File" after you click on "Export".

You can specify your main driver in "Launch Configuration"

enter image description here enter image description here

jQuery UI Dialog OnBeforeUnload

The correct way to display the alert is to simply return a string. Don't call the alert() method yourself.

<script type="text/javascript">
    $(window).on('beforeunload', function() {
        if (iWantTo) {
            return 'you are an idiot!';
        }
    }); 
</script>

See also: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

How to change the size of the radio button using CSS?

try this code... it may be the ans what you exactly looking for

_x000D_
_x000D_
body, html{_x000D_
  height: 100%;_x000D_
  background: #222222;_x000D_
}_x000D_
_x000D_
.container{_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  margin: 40px auto;_x000D_
  height: auto;_x000D_
  width: 500px;_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
 color: #AAAAAA;_x000D_
}_x000D_
_x000D_
.container ul{_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
 overflow: auto;_x000D_
}_x000D_
_x000D_
ul li{_x000D_
  color: #AAAAAA;_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  width: 100%;_x000D_
  height: 100px;_x000D_
 border-bottom: 1px solid #333;_x000D_
}_x000D_
_x000D_
ul li input[type=radio]{_x000D_
  position: absolute;_x000D_
  visibility: hidden;_x000D_
}_x000D_
_x000D_
ul li label{_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  font-weight: 300;_x000D_
  font-size: 1.35em;_x000D_
  padding: 25px 25px 25px 80px;_x000D_
  margin: 10px auto;_x000D_
  height: 30px;_x000D_
  z-index: 9;_x000D_
  cursor: pointer;_x000D_
  -webkit-transition: all 0.25s linear;_x000D_
}_x000D_
_x000D_
ul li:hover label{_x000D_
 color: #FFFFFF;_x000D_
}_x000D_
_x000D_
ul li .check{_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border: 5px solid #AAAAAA;_x000D_
  border-radius: 100%;_x000D_
  height: 25px;_x000D_
  width: 25px;_x000D_
  top: 30px;_x000D_
  left: 20px;_x000D_
 z-index: 5;_x000D_
 transition: border .25s linear;_x000D_
 -webkit-transition: border .25s linear;_x000D_
}_x000D_
_x000D_
ul li:hover .check {_x000D_
  border: 5px solid #FFFFFF;_x000D_
}_x000D_
_x000D_
ul li .check::before {_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
 content: '';_x000D_
  border-radius: 100%;_x000D_
  height: 15px;_x000D_
  width: 15px;_x000D_
  top: 5px;_x000D_
 left: 5px;_x000D_
  margin: auto;_x000D_
 transition: background 0.25s linear;_x000D_
 -webkit-transition: background 0.25s linear;_x000D_
}_x000D_
_x000D_
input[type=radio]:checked ~ .check {_x000D_
  border: 5px solid #0DFF92;_x000D_
}_x000D_
_x000D_
input[type=radio]:checked ~ .check::before{_x000D_
  background: #0DFF92;_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    <input type="radio" id="f-option" name="selector">_x000D_
    <label for="f-option">Male</label>_x000D_
    _x000D_
    <div class="check"></div>_x000D_
  </li>_x000D_
  _x000D_
  <li>_x000D_
    <input type="radio" id="s-option" name="selector">_x000D_
    <label for="s-option">Female</label>_x000D_
    _x000D_
    <div class="check"><div class="inside"></div></div>_x000D_
  </li>_x000D_
  _x000D_
  <li>_x000D_
    <input type="radio" id="t-option" name="selector">_x000D_
    <label for="t-option">Transgender</label>_x000D_
    _x000D_
    <div class="check"><div class="inside"></div></div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Disable keyboard on EditText

Disable the keyboard (API 11 to current)

This is the best answer I have found so far to disable the keyboard (and I have seen a lot of them).

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
    editText.setShowSoftInputOnFocus(false);
} else { // API 11-20
    editText.setTextIsSelectable(true);
}

There is no need to use reflection or set the InputType to null.

Re-enable the keyboard

Here is how you re-enable the keyboard if needed.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
    editText.setShowSoftInputOnFocus(true);
} else { // API 11-20
    editText.setTextIsSelectable(false);
    editText.setFocusable(true);
    editText.setFocusableInTouchMode(true);
    editText.setClickable(true);
    editText.setLongClickable(true);
    editText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
    editText.setText(editText.getText(), TextView.BufferType.SPANNABLE);
}

See this Q&A for why the complicated pre API 21 version is needed to undo setTextIsSelectable(true):

This answer needs to be more thoroughly tested.

I have tested the setShowSoftInputOnFocus on higher API devices, but after @androiddeveloper's comment below, I see that this needs to be more thoroughly tested.

Here is some cut-and-paste code to help test this answer. If you can confirm that it does or doesn't work for API 11 to 20, please leave a comment. I don't have any API 11-20 devices and my emulator is having problems.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:background="@android:color/white">

    <EditText
        android:id="@+id/editText"
        android:textColor="@android:color/black"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:text="enable keyboard"
        android:onClick="enableButtonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:text="disable keyboard"
        android:onClick="disableButtonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    EditText editText;

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

        editText = (EditText) findViewById(R.id.editText);
    }

    // when keyboard is hidden it should appear when editText is clicked
    public void enableButtonClick(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
            editText.setShowSoftInputOnFocus(true);
        } else { // API 11-20
            editText.setTextIsSelectable(false);
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            editText.setClickable(true);
            editText.setLongClickable(true);
            editText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
            editText.setText(editText.getText(), TextView.BufferType.SPANNABLE);
        }
    }

    // when keyboard is hidden it shouldn't respond when editText is clicked
    public void disableButtonClick(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
            editText.setShowSoftInputOnFocus(false);
        } else { // API 11-20
            editText.setTextIsSelectable(true);
        }
    }
}

"Could not find a valid gem in any repository" (rubygame and others)

Use :

gem sources --add http://rubygems.org/

Do you want to add this insecure source? [yn] [YES]

then use

gem install sass

and done

Compare every item to every other item in ArrayList

In some cases this is the best way because your code may have change something and j=i+1 won't check that.

for (int i = 0; i < list.size(); i++){  
    for (int j = 0; j < list.size(); j++) {
                if(i == j) {
               //to do code here
                    continue;
                }

}

}

How to serialize Joda DateTime with Jackson JSON processor?

In the object you're mapping:

@JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDate() { ... }

In CustomDateSerializer:

public class CustomDateSerializer extends JsonSerializer<DateTime> {

    private static DateTimeFormatter formatter = 
        DateTimeFormat.forPattern("dd-MM-yyyy");

    @Override
    public void serialize(DateTime value, JsonGenerator gen, 
                          SerializerProvider arg2)
        throws IOException, JsonProcessingException {

        gen.writeString(formatter.print(value));
    }
}

Setting state on componentDidMount()

According to the React Documentation it's perfectly OK to call setState() from within the componentDidMount() function.

It will cause render() to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.

You can find the documentation here:

https://reactjs.org/docs/react-component.html#componentdidmount

Here is the excerpt from the documentation:

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...