Programs & Examples On #Stanford nlp

Suite of Java libraries for natural language processing (NLP) from Stanford University.

Combining two lists and removing duplicates, without removing duplicates in original list

resulting_list = first_list + [i for i in second_list if i not in first_list]

adding and removing classes in angularJs using ng-click

There is a simple and clean way of doing this with only directives.

<div ng-class="{'class-name': clicked}" ng-click="clicked = !clicked"></div>

Python in Xcode 4+?

I've created Xcode 4 templates to simplify the steps provided by Tyler.
The result is Python Project Template for Xcode 4.

Now what you need to do is download the templates, move it to /Developer/Library/Xcode/Templates/Project Templates/Mac/Others/ and then new a Python project with Xcode 4.

It still needs manual Scheme setup (you can refer to steps 12–20 provided by Tyler.)

In SQL Server, what does "SET ANSI_NULLS ON" mean?

I guess the main thing here is:

Never user:

  • @anything = NULL
  • @anything <> NULL
  • @anything != null

Always use:

  • @anything IS NULL
  • @anything IS NOT NULL

ASP.NET page life cycle explanation

There are 10 events in ASP.NET page life cycle, and the sequence is:

  1. Init
  2. Load view state
  3. Post back data
  4. Load
  5. Validate
  6. Events
  7. Pre-render
  8. Save view state
  9. Render
  10. Unload

Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.

ASP.NET life cycle

Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010

What is the difference between .NET Core and .NET Standard Class Library project types?

.NET Framework

Windows Forms, ASP.NET and WPF application must be developed using .NET Framework library.

.NET Standard

Xamarin, iOS and Mac OS X application must be developed using .NET Standard library

.NET Core

Universal Windows Platform (UWP) and Linux application must be developed using .NET Core library. The API is implemented in C++ and you can using the C++, VB.NET, C#, F# and JavaScript languages.NET

ng-model for `<input type="file"/>` (with directive DEMO)

This is a slightly modified version that lets you specify the name of the attribute in the scope, just as you would do with ng-model, usage:

    <myUpload key="file"></myUpload>

Directive:

.directive('myUpload', function() {
    return {
        link: function postLink(scope, element, attrs) {
            element.find("input").bind("change", function(changeEvent) {                        
                var reader = new FileReader();
                reader.onload = function(loadEvent) {
                    scope.$apply(function() {
                        scope[attrs.key] = loadEvent.target.result;                                
                    });
                }
                if (typeof(changeEvent.target.files[0]) === 'object') {
                    reader.readAsDataURL(changeEvent.target.files[0]);
                };
            });

        },
        controller: 'FileUploadCtrl',
        template:
                '<span class="btn btn-success fileinput-button">' +
                '<i class="glyphicon glyphicon-plus"></i>' +
                '<span>Replace Image</span>' +
                '<input type="file" accept="image/*" name="files[]" multiple="">' +
                '</span>',
        restrict: 'E'

    };
});

Remove substring from the string

You can use the slice method:

a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"

there is a non '!' version as well. More info can be seen in the documentation about other versions as well: http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21

How to pass ArrayList of Objects from one to another activity using Intent in android?

Simple as that !! worked for me

From activity

        Intent intent = new Intent(Viewhirings.this, Informaall.class);
        intent.putStringArrayListExtra("list",nselectedfromadapter);

        startActivity(intent);

TO activity

Bundle bundle = getIntent().getExtras();
    nselectedfromadapter= bundle.getStringArrayList("list");

Insert/Update/Delete with function in SQL Server

No, you cannot.

From SQL Server Books Online:

User-defined functions cannot be used to perform actions that modify the database state.

Ref.

HTML 5: Is it <br>, <br/>, or <br />?

<br> works just fine in HTML5. HTML5 allows a little more leeway than XHTML.

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

Check element CSS display with JavaScript

yes.

var displayValue = document.getElementById('yourid').style.display;

Simulate user input in bash script

Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:

echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"

Convert timestamp to date in Oracle SQL

You can use:

select to_date(to_char(date_field,'dd/mm/yyyy')) from table

How do I simulate a hover with a touch in touch enabled browsers?

Add this code and then set class "tapHover" to elements which you would like to work this way. First time you tap an element it will gain pseudoclass ":hover" and class "tapped". Click event will be prevented. Second time you tap the same element - click event will be fired.

_x000D_
_x000D_
// Activate only in devices with touch screen_x000D_
if('ontouchstart' in window)_x000D_
{_x000D_
    // this will make touch event add hover pseudoclass_x000D_
    document.addEventListener('touchstart', function(e) {}, true);_x000D_
_x000D_
    // modify click event_x000D_
    document.addEventListener('click', function(e) {_x000D_
        // get .tapHover element under cursor_x000D_
        var el = jQuery(e.target).hasClass('tapHover')_x000D_
            ? jQuery(e.target)_x000D_
            : jQuery(e.target).closest('.tapHover');_x000D_
_x000D_
        if(!el.length)_x000D_
            return;_x000D_
_x000D_
        // remove tapped class from old ones_x000D_
        jQuery('.tapHover.tapped').each(function() {_x000D_
            if(this != el.get(0))_x000D_
                jQuery(this).removeClass('tapped');_x000D_
        });_x000D_
_x000D_
        if(!el.hasClass('tapped'))_x000D_
        {_x000D_
            // this is the first tap_x000D_
            el.addClass('tapped');_x000D_
            e.preventDefault();_x000D_
            return false;_x000D_
        }_x000D_
        else_x000D_
        {_x000D_
            // second tap_x000D_
            return true;_x000D_
        }_x000D_
    }, true);_x000D_
}
_x000D_
.box {_x000D_
 float:  left;_x000D_
 _x000D_
 display: inline-block;_x000D_
 margin:  50px 0 0 50px;_x000D_
 width:  100px;_x000D_
 height:  100px;_x000D_
 overflow: hidden;_x000D_
 _x000D_
 font-size: 20px;_x000D_
 _x000D_
 border:  solid 1px black;_x000D_
}_x000D_
.box.tapHover {_x000D_
 background: yellow;_x000D_
}_x000D_
.box.tapped {_x000D_
 border:  solid 3px red;_x000D_
}_x000D_
.box:hover {_x000D_
 background: red;_x000D_
}
_x000D_
<div class="box" onclick="this.innerHTML = Math.random().toFixed(5)"></div>_x000D_
<div class="box tapHover" onclick="this.innerHTML = Math.random().toFixed(5)"></div>_x000D_
<div class="box tapHover" onclick="this.innerHTML = Math.random().toFixed(5)"></div>
_x000D_
_x000D_
_x000D_

How do I create a new column from the output of pandas groupby().sum()?

You want to use transform this will return a Series with the index aligned to the df so you can then add it as a new column:

In [74]:

df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
   Data2  Data3        Date   Sym  Data4
0     11      5  2015-05-08  aapl     55
1      8      8  2015-05-07  aapl    108
2     10      6  2015-05-06  aapl     66
3     15      1  2015-05-05  aapl    121
4    110     50  2015-05-08  aaww     55
5     60    100  2015-05-07  aaww    108
6    100     60  2015-05-06  aaww     66
7     40    120  2015-05-05  aaww    121

Managing SSH keys within Jenkins for Git

Have you tried logging in as the jenkins user?

Try this:

sudo -i -u jenkins #For RedHat you might have to do 'su' instead.
git clone [email protected]:your/repo.git

Often times you see failure if the host has not been added or authorized (hence I always manually login as hudson/jenkins for the first connection to github/bitbucket) but that link you included supposedly fixes that.

If the above doesn't work try recopying the key. Make sure its the pub key (ie id_rsa.pub). Maybe you missed some characters?

Maximum value of maxRequestLength?

2,147,483,647 bytes, since the value is a signed integer (Int32). That's probably more than you'll need.

Inserting Data into Hive Table

to insert ad-hoc value like (12,"xyz), do this:

insert into table foo select * from (select 12,"xyz")a;

Android Get Application's 'Home' Data Directory

Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:

ContextWrapper.getFilesDir()

Found here.

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

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

Text in Border CSS HTML

Text in Border with transparent text background

_x000D_
_x000D_
.box{
    background-image: url("https://i.stack.imgur.com/N39wV.jpg");
    width: 350px;
    padding: 10px;
}

/*begin first box*/
.first{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 0 2px 0 2px;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.first span {
    position: absolute;
    display: flex;
    right: 0;
    left: 0;
    align-items: center;
}
.first .foo{
    top: -8px;
}
.first .bar{
    bottom: -8.5px;
}
.first span:before{
    margin-right: 15px;
}
.first span:after {
    margin-left: 15px;
}
.first span:before , .first span:after {
    content: ' ';
    height: 2px;
    background: #333;
    display: block;
    width: 50%;
}


/*begin second box*/
.second{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 2px 0 2px 0;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.second span {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.second .foo{
    left: -15px;
}
.second .bar{
    right: -15.5px;
}
.second span:before{
    margin-bottom: 15px;
}
.second span:after {
    margin-top: 15px;
}
.second span:before , .second span:after {
    content: ' ';
    width: 2px;
    background: #333;
    display: block;
    height: 50%;
}
_x000D_
<div class="box">
    <div class="first">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>

   <br>

    <div class="second">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>
</div>
_x000D_
_x000D_
_x000D_

How can I force clients to refresh JavaScript files?

location.reload(true);

see https://www.w3schools.com/jsref/met_loc_reload.asp

I dynamically call this line of code in order to ensure that javascript has been re-retrieved from the web server instead of from the browser's cache in order to escape this problem.

Passing Objects By Reference or Value in C#

I guess its clearer when you do it like this. I recommend downloading LinqPad to test things like this.

void Main()
{
    var Person = new Person(){FirstName = "Egli", LastName = "Becerra"};

    //Will update egli
    WontUpdate(Person);
    Console.WriteLine("WontUpdate");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateImplicitly(Person);
    Console.WriteLine("UpdateImplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateExplicitly(ref Person);
    Console.WriteLine("UpdateExplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");
}

//Class to test
public class Person{
    public string FirstName {get; set;}
    public string LastName {get; set;}

    public string printName(){
        return $"First name: {FirstName} Last name:{LastName}";
    }
}

public static void WontUpdate(Person p)
{
    //New instance does jack...
    var newP = new Person(){FirstName = p.FirstName, LastName = p.LastName};
    newP.FirstName = "Favio";
    newP.LastName = "Becerra";
}

public static void UpdateImplicitly(Person p)
{
    //Passing by reference implicitly
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

public static void UpdateExplicitly(ref Person p)
{
    //Again passing by reference explicitly (reduntant)
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

And that should output

WontUpdate

First name: Egli, Last name: Becerra

UpdateImplicitly

First name: Favio, Last name: Becerra

UpdateExplicitly

First name: Favio, Last name: Becerra

docker run <IMAGE> <MULTIPLE COMMANDS>

For anyone else who came here looking to do the same with docker-compose you just need to prepend bash -c and enclose multiple commands in quotes, joined together with &&.

So in the OPs example docker-compose run image bash -c "cd /path/to/somewhere && python a.py"

How can I get a user's media from Instagram without authenticating as a user?

Well, as /?__a=1 stopped working by now, it's better to use curl and parse the instagram page as written at this answer: Generate access token Instagram API, without having to log in?

Remove duplicates from a List<T> in C#

If you're using .Net 3+, you can use Linq.

List<T> withDupes = LoadSomeData();
List<T> noDupes = withDupes.Distinct().ToList();

Transparent ARGB hex value

BE AWARE

In HTML/CSS (browser code) the format is #RRGGBBAA with the alpha channel as last two hexadecimal digits.

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

the below piece of code should do what yoiu are looking for:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String s = scan.nextLine();
    System.out.println(s);
    scan.close();
}

Java: Finding the highest value in an array

A shorter solution to have the max value of array:

double max = Arrays.stream(decMax).max(Double::compareTo).get();

CMAKE_MAKE_PROGRAM not found

Previous answers suggested (re)installing or configuring CMake, they all did not help.

Previously MinGW's compilation of Make used the filename mingw32-make.exe and now it is make.exe. Most suggested ways to configure CMake to use the other file dont work.

Just copy make.exe and rename the copy mingw32-make.exe.

How can I get an HTTP response body as a string?

Here is a vanilla Java answer:

import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;

...
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
  .uri(targetUrl)
  .header("Content-Type", "application/json")
  .POST(BodyPublishers.ofString(requestBody))
  .build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
String responseString = (String) response.body();

T-SQL: Selecting rows to delete via joins

In SQLite, the only thing that work is something similar to beauXjames' answer.

It seems to come down to this DELETE FROM table1 WHERE table1.col1 IN (SOME TEMPORARY TABLE); and that some temporary table can be crated by SELECT and JOIN your two table which you can filter this temporary table based on the condition that you want to delete the records in Table1.

How to check if Receiver is registered in Android?

There is no API function to check if a receiver is registered. The workaround is to put your code in a try catch block as done below.

try {

 //Register or UnRegister your broadcast receiver here

} catch(IllegalArgumentException e) {

    e.printStackTrace();
}

Node.js check if path is file or directory

The answers above check if a filesystem contains a path that is a file or directory. But it doesn't identify if a given path alone is a file or directory.

The answer is to identify directory-based paths using "/." like --> "/c/dos/run/." <-- trailing period.

Like a path of a directory or file that has not been written yet. Or a path from a different computer. Or a path where both a file and directory of the same name exists.

// /tmp/
// |- dozen.path
// |- dozen.path/.
//    |- eggs.txt
//
// "/tmp/dozen.path" !== "/tmp/dozen.path/"
//
// Very few fs allow this. But still. Don't trust the filesystem alone!

// Converts the non-standard "path-ends-in-slash" to the standard "path-is-identified-by current "." or previous ".." directory symbol.
function tryGetPath(pathItem) {
    const isPosix = pathItem.includes("/");
    if ((isPosix && pathItem.endsWith("/")) ||
        (!isPosix && pathItem.endsWith("\\"))) {
        pathItem = pathItem + ".";
    }
    return pathItem;
}
// If a path ends with a current directory identifier, it is a path! /c/dos/run/. and c:\dos\run\.
function isDirectory(pathItem) {
    const isPosix = pathItem.includes("/");
    if (pathItem === "." || pathItem ==- "..") {
        pathItem = (isPosix ? "./" : ".\\") + pathItem;
    }
    return (isPosix ? pathItem.endsWith("/.") || pathItem.endsWith("/..") : pathItem.endsWith("\\.") || pathItem.endsWith("\\.."));
} 
// If a path is not a directory, and it isn't empty, it must be a file
function isFile(pathItem) {
    if (pathItem === "") {
        return false;
    }
    return !isDirectory(pathItem);
}

Node version: v11.10.0 - Feb 2019

Last thought: Why even hit the filesystem?

QByteArray to QString

You can use:

QString::fromStdString(byteArray.toStdString())

Ruby class instance variable vs. class variable

Instance variable on a class:

class Parent
  @things = []
  def self.things
    @things
  end
  def things
    self.class.things
  end
end

class Child < Parent
  @things = []
end

Parent.things << :car
Child.things  << :doll
mom = Parent.new
dad = Parent.new

p Parent.things #=> [:car]
p Child.things  #=> [:doll]
p mom.things    #=> [:car]
p dad.things    #=> [:car]

Class variable:

class Parent
  @@things = []
  def self.things
    @@things
  end
  def things
    @@things
  end
end

class Child < Parent
end

Parent.things << :car
Child.things  << :doll

p Parent.things #=> [:car,:doll]
p Child.things  #=> [:car,:doll]

mom = Parent.new
dad = Parent.new
son1 = Child.new
son2 = Child.new
daughter = Child.new

[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]

With an instance variable on a class (not on an instance of that class) you can store something common to that class without having sub-classes automatically also get them (and vice-versa). With class variables, you have the convenience of not having to write self.class from an instance object, and (when desirable) you also get automatic sharing throughout the class hierarchy.


Merging these together into a single example that also covers instance variables on instances:

class Parent
  @@family_things = []    # Shared between class and subclasses
  @shared_things  = []    # Specific to this class

  def self.family_things
    @@family_things
  end
  def self.shared_things
    @shared_things
  end

  attr_accessor :my_things
  def initialize
    @my_things = []       # Just for me
  end
  def family_things
    self.class.family_things
  end
  def shared_things
    self.class.shared_things
  end
end

class Child < Parent
  @shared_things = []
end

And then in action:

mama = Parent.new
papa = Parent.new
joey = Child.new
suzy = Child.new

Parent.family_things << :house
papa.family_things   << :vacuum
mama.shared_things   << :car
papa.shared_things   << :blender
papa.my_things       << :quadcopter
joey.my_things       << :bike
suzy.my_things       << :doll
joey.shared_things   << :puzzle
suzy.shared_things   << :blocks

p Parent.family_things #=> [:house, :vacuum]
p Child.family_things  #=> [:house, :vacuum]
p papa.family_things   #=> [:house, :vacuum]
p mama.family_things   #=> [:house, :vacuum]
p joey.family_things   #=> [:house, :vacuum]
p suzy.family_things   #=> [:house, :vacuum]

p Parent.shared_things #=> [:car, :blender]
p papa.shared_things   #=> [:car, :blender]
p mama.shared_things   #=> [:car, :blender]
p Child.shared_things  #=> [:puzzle, :blocks]  
p joey.shared_things   #=> [:puzzle, :blocks]
p suzy.shared_things   #=> [:puzzle, :blocks]

p papa.my_things       #=> [:quadcopter]
p mama.my_things       #=> []
p joey.my_things       #=> [:bike]
p suzy.my_things       #=> [:doll] 

Difference between $(this) and event.target?

There is a significant different in how jQuery handles the this variable with a "on" method

$("outer DOM element").on('click',"inner DOM element",function(){
  $(this) // refers to the "inner DOM element"
})

If you compare this with :-

$("outer DOM element").click(function(){
  $(this) // refers to the "outer DOM element"
})

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

Maven2: Best practice for Enterprise Project (EAR file)

This is a good example of the maven-ear-plugin part.

You can also check the maven archetypes that are available as an example. If you just runt mvn archetype:generate you'll get a list of available archetypes. One of them is

maven-archetype-j2ee-simple

Where does Android emulator store SQLite database?

Since the question is not restricted to Android Studio, So I am giving the path for Visual Studio 2015 (worked for Xamarin).

Tools-Android-Android Device Monitor

enter image description here

  • Locate the database file mentioned in above image, and click on Pull button as it shown in image 2.
  • Save the file in your desired location.
  • You can open that file using SQLite Studio or DB Browser for SQLite.

Special Thanks to other answerers of this question.

How does DISTINCT work when using JPA and Hibernate

You are close.

select DISTINCT(c.name) from Customer c

How long will my session last?

If session.cookie_lifetime is 0, the session cookie lives until the browser is quit.

EDIT: Others have mentioned the session.gc_maxlifetime setting. When session garbage collection occurs, the garbage collector will delete any session data that has not been accessed in longer than session.gc_maxlifetime seconds. To set the time-to-live for the session cookie, call session_set_cookie_params() or define the session.cookie_lifetime PHP setting. If this setting is greater than session.gc_maxlifetime, you should increase session.gc_maxlifetime to a value greater than or equal to the cookie lifetime to ensure that your sessions won't expire.

How to check whether mod_rewrite is enable on server?

This works on CentOS:

$ sudo httpd -M |grep rewrite_module

Should output rewrite_module (shared)

Prime numbers between 1 to 100 in C Programming Language

#include <stdio.h>
#include <conio.h>
int main()
{
    int i,j;
    int b=0;
    for (i=2;i<=100;i++){
        for (j=2;j<=i;j++){
            if (i%j==0){
                break;
            }
        }
        if (i==j)
            print f("\n%d",j);
    }
    getch ();
}

What's default HTML/CSS link color?

For me, on Chrome (updated June 2018) the color for an unvisited link is #2779F6. You can always get this by zooming in really close, taking a screenshot, and visiting a website like html-color-codes.info that will convert a screenshot to a color code.

Windows Application has stopped working :: Event Name CLR20r3

Some times this problem arise when Application is build in one PC and try to run another PC. And also build the application with Visual Studio 2010.I have the following problem

Problem Description
    Stop Working
Problem Signature
  Problem Event Name:   CLR20r3
  Problem Signature 01: diagnosticcentermngr.exe
  Problem Signature 02: 1.0.0.0
  Problem Signature 03: 4f8c1772
  Problem Signature 04: System.Drawing
  Problem Signature 05: 2.0.0.0
  Problem Signature 06: 4a275e83
  Problem Signature 07: 7af
  Problem Signature 08: 6c
  Problem Signature 09: System.ArgumentException
  OS Version:   6.1.7600.2.0.0.256.1
  Locale ID:    1033

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

Dont worry, Please check out following link and install .net framework 4.Although my application .net properties was .net framework 2.

http://www.microsoft.com/download/en/details.aspx?id=17718

restart your PC and try again.

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

You shouldn't use CascadeType.ALL on @ManyToOne since entity state transitions should propagate from parent entities to child ones, not the other way around.

The @ManyToOne side is always the Child association since it maps the underlying Foreign Key column.

Therefore, you should move the CascadeType.ALL from the @ManyToOne association to the @OneToMany side, which should also use the mappedBy attribute since it's the most efficient one-to-many table relationship mapping.

Get the difference between dates in terms of weeks, months, quarters, and years

try this for a months solution

StartDate <- strptime("14 January 2013", "%d %B %Y") 
EventDates <- strptime(c("26 March 2014"), "%d %B %Y") 
difftime(EventDates, StartDate) 

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />

I'm targeting API 22, so don't need to explicitly ask for permissions.

Django Rest Framework -- no module named rest_framework

On Windows, with PowerShell, I had to close and reopen the console and then reactive the virtual environment.

SQL Server table creation date query

For SQL Server 2005 upwards:

SELECT [name] AS [TableName], [create_date] AS [CreatedDate] FROM sys.tables

For SQL Server 2000 upwards:

SELECT so.[name] AS [TableName], so.[crdate] AS [CreatedDate]
FROM INFORMATION_SCHEMA.TABLES AS it, sysobjects AS so 
WHERE it.[TABLE_NAME] = so.[name]

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:

#!/bin/bash

sudo -u username command1
command2
sudo -u username command3
command4

When running as root, sudo doesn't ask for a password.

Delete all records in a table of MYSQL in phpMyAdmin

'Truncate tableName' will fail on a table with key constraint defined. It will also not reindex the table AUTO_INCREMENT value. Instead, Delete all table entries and reset indexing back to 1 using this sql syntax:

DELETE FROM tableName;
ALTER TABLE tableName AUTO_INCREMENT = 1

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

As per my comment on @neves post, I slightly improved this by adding the xlPasteFormats as well as values part so dates go across as dates - I mostly save as CSV for bank statements, so needed dates.

Sub ExportAsCSV()

    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook

    Set CurrentWB = ActiveWorkbook
    ActiveWorkbook.ActiveSheet.UsedRange.Copy

    Set TempWB = Application.Workbooks.Add(1)
    With TempWB.Sheets(1).Range("A1")
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
    End With

    'Dim Change below to "- 4"  to become compatible with .xls files
    MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"

    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True
End Sub

Waiting for HOME ('android.process.acore') to be launched

Options:

  • Click on the HOME Button on the Emulator. Wait for may be 2 seconds.... This always works for me!!!

or

  • Go with Shreya's suggestion (one with most suggestions and edited by Gray).

Running Composer returns: "Could not open input file: composer.phar"

I've reach to this problem when trying to install composer on a Window 7 machine from http://getcomposer.org/download page. As there was an existing compose version (provided by acquia Dev Desktop tool) the installation fails and the only chance was to fix this issue manually. (or to remove Dev Desktop tool composer).

Anyway the error message is quite straightforward (Could not open input file: composer.phar), we should then tell the system where the file is located.

Edit composer.bat file and should look like:

@SET PATH=C:\Program Files (x86)\DevDesktop\php5_4;%PATH%
php.exe composer.phar %*

See that composer.phar doesn´t have a file path. When standing in a different folder than the one where composer.phar is located the system won´t be able to find it. So, just complete the composer.phar file path:

@SET PATH=C:\Program Files (x86)\DevDesktop\php5_4;;%PATH%
SET composerScript=composer.phar
php.exe "%~dp0%composerScript%" %*

Reopen your window console and that should do the trick.

EDIT: this has an issue because it always uses %~dp0%composerScript% folder as composer execution. Then all configurations are done in that folder (besides standing on your current project folder) and not in your project folder.

So far I haven't found a was to make a manual composer installation to work globally on Windows. Perhaps you should go ahead with composer for windows installation mentioned above.

python capitalize first letter only

Here is a one-liner that will uppercase the first letter and leave the case of all subsequent letters:

import re

key = 'wordsWithOtherUppercaseLetters'
key = re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), key, 1)
print key

This will result in WordsWithOtherUppercaseLetters

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

If you're using EF and Publish Profiles, you could have a blank connection string entry in your publish profile. Annoying but entirely possible.

How to join entries in a set into one string?

I think you just have it backwards.

print ", ".join(set_3)

How can you integrate a custom file browser/uploader with CKEditor?

I spent a while trying to figure this one out and here is what I did. I've broken it down very simply as that is what I needed.

Directly below your ckeditor text area, enter the upload file like this >>>>

<form action="welcomeeditupload.asp" method="post" name="deletechecked">
    <div align="center">
        <br />
        <br />
        <label></label>
        <textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"><%=(rslegschedule.Fields.Item("welcomevar").Value)%></textarea>
        <script type="text/javascript">
        //<![CDATA[
            CKEDITOR.replace( 'editor1',
            {
                filebrowserUploadUrl : 'updateimagedone.asp'
            });
        //]]>
        </script>
        <br />
        <br />
        <br />
        <input type="submit" value="Update">
    </div>
</form>

'and then add your upload file, here is mine which is written in ASP. If you're using PHP, etc. simply replace the ASP with your upload script but make sure the page outputs the same thing.

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
    if Request("CKEditorFuncNum")=1 then
        Set Upload = Server.CreateObject("Persits.Upload")
        Upload.OverwriteFiles = False
        Upload.SetMaxSize 5000000, True
        Upload.CodePage = 65001

        On Error Resume Next
        Upload.Save "d:\hosting\belaullach\senate\legislation"

        Dim picture
        For Each File in Upload.Files
            Ext = UCase(Right(File.Path, 3))
            If Ext <> "JPG" Then
                    If Ext <> "BMP" Then
                    Response.Write "File " & File.Path & " is not a .jpg or .bmp file." & "<BR>"
                    Response.write "You can only upload .jpg or .bmp files." & "<BR>" & "<BR>"
                    End if
            Else
                File.SaveAs Server.MapPath(("/senate/legislation") & "/" & File.fileName)
                f1=File.fileName
            End If
        Next
    End if

    fnm="/senate/legislation/"&f1
    imgop = "<html><body><script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction('1','"&fnm&"');</script></body></html>;"
    'imgop="callFunction('1','"&fnm&"',"");"
    Response.write imgop
%>

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Using LINQ to group a list of objects

var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>{
                                                        u.Name = "User" + u.Name;
                                                        return u;
                                                     }, (key,g)=>g.ToList())
                         .ToList();

If you don't want to change the original data, you should add some method (kind of clone and modify) to your class like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public Customer CloneWithNamePrepend(string prepend){
    return new Customer(){
          ID = this.ID,
          Name = prepend + this.Name,
          GroupID = this.GroupID
     };
  }
}    
//Then
var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>u.CloneWithNamePrepend("User"), (key,g)=>g.ToList())
                         .ToList();

I think you may want to display the Customer differently without modifying the original data. If so you should design your class Customer differently, like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public string Prefix {get;set;}
  public string FullName {
    get { return Prefix + Name;}
  }            
}
//then to display the fullname, just get the customer.FullName; 
//You can also try adding some override of ToString() to your class

var groupedCustomerList = CustomerList
                         .GroupBy(u => {u.Prefix="User", return u.GroupID;} , (key,g)=>g.ToList())
                         .ToList();

No @XmlRootElement generated by JAXB

To tie together what others have already stated or hinted at, the rules by which JAXB XJC decides whether or not to put the @XmlRootElement annotation on a generated class are non trivial (see this article).

@XmlRootElement exists because the JAXB runtime requires certain information in order to marshal/unmarshal a given object, specifically the XML element name and namespace. You can't just pass any old object to the Marshaller. @XmlRootElement provides this information.

The annotation is just a convenience, however - JAXB does not require it. The alternative to is to use JAXBElement wrapper objects, which provide the same information as @XmlRootElement, but in the form of an object, rather than an annotation.

However, JAXBElement objects are awkward to construct, since you need to know the XML element name and namespace, which business logic usually doesn't.

Thankfully, when XJC generates a class model, it also generates a class called ObjectFactory. This is partly there for backwards compatibility with JAXB v1, but it's also there as a place for XJC to put generated factory methods which create JAXBElement wrappers around your own objects. It handles the XML name and namespace for you, so you don't need to worry about it. You just need to look through the ObjectFactory methods (and for large schema, there can be hundreds of them) to find the one you need.

GitHub: How to make a fork of public repository private?

The answers are correct but don't mention how to sync code between the public repo and the fork.

Here is the full workflow (we've done this before open sourcing React Native):


First, duplicate the repo as others said (details here):

Create a new repo (let's call it private-repo) via the Github UI. Then:

git clone --bare https://github.com/exampleuser/public-repo.git
cd public-repo.git
git push --mirror https://github.com/yourname/private-repo.git
cd ..
rm -rf public-repo.git

Clone the private repo so you can work on it:

git clone https://github.com/yourname/private-repo.git
cd private-repo
make some changes
git commit
git push origin master

To pull new hotness from the public repo:

cd private-repo
git remote add public https://github.com/exampleuser/public-repo.git
git pull public master # Creates a merge commit
git push origin master

Awesome, your private repo now has the latest code from the public repo plus your changes.


Finally, to create a pull request private repo -> public repo:

Use the GitHub UI to create a fork of the public repo (the small "Fork" button at the top right of the public repo page). Then:

git clone https://github.com/yourname/the-fork.git
cd the-fork
git remote add private_repo_yourname https://github.com/yourname/private-repo.git
git checkout -b pull_request_yourname
git pull private_repo_yourname master
git push origin pull_request_yourname

Now you can create a pull request via the Github UI for public-repo, as described here.

Once project owners review your pull request, they can merge it.

Of course the whole process can be repeated (just leave out the steps where you add remotes).

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

You could also do the following:

// untested
Calendar cal = GregorianCalendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 23);// I might have the wrong Calendar constant...
cal.set(Calendar.MONTH, 8);// -1 as month is zero-based
cal.set(Calendar.YEAR, 2009);
Timestamp tstamp = new Timestamp(cal.getTimeInMillis());

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

 <uses-permission android:name="android.permission.INTERNET" />

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Plotting time in Python with Matplotlib

You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format.

Plot the dates and values using plot_date:

dates = matplotlib.dates.date2num(list_of_datetimes)
matplotlib.pyplot.plot_date(dates, values)

Removing special characters VBA Excel

This is what I use, based on this link

Function StripAccentb(RA As Range)

Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
'Const AccChars = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
'Const RegChars = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
S = RA.Cells.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = Replace(S, A, B)
'Debug.Print (S)
Next


StripAccentb = S

Exit Function
End Function

Usage:

=StripAccentb(B2) ' cell address

Sub version for all cells in a sheet:

Sub replacesub()
Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
Range("A1").Resize(Cells.Find(what:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
Cells.Find(what:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column).Select '
For Each cell In Selection
If cell <> "" Then
S = cell.Text
    For i = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    S = replace(S, A, B)
    Next
cell.Value = S
Debug.Print "celltext "; (cell.Text)
End If
Next cell
End Sub

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

The problem occurs because you set the foreign key in child table after you insert some data in the child table.

Try removing all the data from child table, then set the foreign key and afterwards add/insert the data in table, it will work.

ByRef argument type mismatch in Excel VBA

It looks like ByRef needs to know the size of the parameter. A declaration of Dim last_name as string doesn't specify the size of the string so it takes it as an error. Before using Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name) The last_name has to be declared as Dim last_name as string *10 ' size of string is up to you but must be a fix length

No need to change the function. Function doesn't take a fix length declaration.

Merge 2 DataTables and store in a new one

Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can start with an empty DataTable and merge one-by-one iteratively:

dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...

and so on.

This technique is useful in a loop where you want to iteratively merge data tables:

DataTable dtAllCountries = new DataTable();

foreach(String strCountry in listCountries)
{
    DataTable dtCountry = getData(strCountry); //Some function that returns a data table
    dtAllCountries.Merge(dtCountry);
}

How can I insert new line/carriage returns into an element.textContent?

Change the h1.textContent to h1.innerHTML and use <br> to go to the new line.

How to scanf only integer and repeat reading if the user enters non-numeric characters?

#include <stdio.h>
main()
{
    char str[100];
    int num;
    while(1) {
        printf("Enter a number: ");
        scanf("%[^0-9]%d",str,&num);
        printf("You entered the number %d\n",num);
    }
    return 0;
}

%[^0-9] in scanf() gobbles up all that is not between 0 and 9. Basically it cleans the input stream of non-digits and puts it in str. Well, the length of non-digit sequence is limited to 100. The following %d selects only integers in the input stream and places it in num.

round up to 2 decimal places in java?

String roundOffTo2DecPlaces(float val)
{
    return String.format("%.2f", val);
}

Create a mocked list by mockito

OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.

Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.

But the real cause of your problem is that you are using when on two different objects, before you complete the stubbing. When you call when, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn part. Each call to when must be followed by one and only one call to thenReturn, before you do any more calls to when. You made two calls to when without calling thenReturn - that's your error.

Calculating Time Difference

Here is a piece of code to do so:

def(StringChallenge(str1)):

#str1 = str1[1:-1]
h1 = 0
h2 = 0
m1 = 0
m2 = 0

def time_dif(h1,m1,h2,m2):
    if(h1 == h2):
        return m2-m1
    else:
        return ((h2-h1-1)*60 + (60-m1) + m2)
count_min = 0

if str1[1] == ':':
    h1=int(str1[:1])
    m1=int(str1[2:4])
else:
    h1=int(str1[:2])
    m1=int(str1[3:5])

if str1[-7] == '-':
    h2=int(str1[-6])
    m2=int(str1[-4:-2])
else:
    h2=int(str1[-7:-5])
    m2=int(str1[-4:-2])

if h1 == 12:
    h1 = 0
if h2 == 12:
    h2 = 0

if "am" in str1[:8]:
    flag1 = 0
else:
    flag1= 1

if "am" in str1[7:]:
    flag2 = 0
else:
    flag2 = 1

if flag1 == flag2:
    if h2 > h1 or (h2 == h1 and m2 >= m1):
        count_min += time_dif(h1,m1,h2,m2)
    else:
        count_min += 1440 - time_dif(h2,m2,h1,m1)
else:
    count_min += (12-h1-1)*60
    count_min += (60 - m1)
    count_min += (h2*60)+m2


return count_min

Clearing content of text file using C#

Simply write to file string.Empty, when append is set to false in StreamWriter. I think this one is easiest to understand for beginner.

private void ClearFile()
{
    if (!File.Exists("TextFile.txt"))
        File.Create("TextFile.txt");

    TextWriter tw = new StreamWriter("TextFile.txt", false);
    tw.Write(string.Empty);
    tw.Close();
}

LINQ select in C# dictionary

One way would be to first flatten the list with a SelectMany:

subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));

IF-THEN-ELSE statements in postgresql

In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). For example,

select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from (     (select 'abc' as x, '' as y)
 union all (select 'def' as x, 'ghi' as y)
 union all (select '' as x, 'jkl' as y)
 union all (select null as x, 'mno' as y)
 union all (select 'pqr' as x, null as y)
) q

gives:

 coalesce | coalesce |  x  |  y  
----------+----------+-----+-----
 abc      | abc      | abc | 
 ghi      | def      | def | ghi
 jkl      | jkl      |     | jkl
 mno      | mno      |     | mno
 pqr      | pqr      | pqr | 
(5 rows)

How to sort an ArrayList in Java

Implement Comparable interface to Fruit.

public class Fruit implements Comparable<Fruit> {

It implements the method

@Override
    public int compareTo(Fruit fruit) {
        //write code here for compare name
    }

Then do call sort method

Collections.sort(fruitList);

sed with literal string--not input file

Works like you want:

echo "A,B,C" | sed s/,/\',\'/g

libxml/tree.h no such file or directory

i tought i added wrongly, then i realize the problem is it not support arc, so check the support one here, life saver -> http://www.michaelbabiy.com/arc-compliant-gdataxml-library/

Phone number validation Android

val UserMobile = findViewById<edittext>(R.id.UserMobile)
val msgUserMobile: String = UserMobile.text.toString()
fun String.isMobileValid(): Boolean {
    // 11 digit number start with 011 or 010 or 015 or 012
    // then [0-9]{8} any numbers from 0 to 9 with length 8 numbers
    if(Pattern.matches("(011|012|010|015)[0-9]{8}", msgUserMobile)) {
        return true
    }
    return false
}

if(msgUserMobile.trim().length==11&& msgUserMobile.isMobileValid())
    {//pass}
else 
    {//not valid} 

Xcode Product -> Archive disabled

You've changed your scheme destination to a simulator instead of Generic iOS Device.

That's why it is greyed out.

Change from a simulator to Generic iOS Device

Center-align a HTML table

<table align="center"></table>

This works for me.

formGroup expects a FormGroup instance

I had a the same error and solved it after moving initialization of formBuilder from ngOnInit to constructor.

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

How do I rename all folders and files to lowercase on Linux?

None of the solutions here worked for me because I was on a system that didn't have access to the perl rename script, plus some of the files included spaces. However, I found a variant that works:

find . -depth -exec sh -c '
    t=${0%/*}/$(printf %s "${0##*/}" | tr "[:upper:]" "[:lower:]");
    [ "$t" = "$0" ] || mv -i "$0" "$t"
' {} \;

Credit goes to "Gilles 'SO- stop being evil'", see this answer on the similar question "change entire directory tree to lower-case names" on the Unix & Linux StackExchange.

List(of String) or Array or ArrayList

Neither collection will let you add items that way.

You can make an extension to make for examle List(Of String) have an Add method that can do that:

Imports System.Runtime.CompilerServices
Module StringExtensions

  <Extension()>
  Public Sub Add(ByVal list As List(Of String), ParamArray values As String())
    For Each s As String In values
      list.Add(s)
    Next
  End Sub

End Module

Now you can add multiple value in one call:

Dim lstOfStrings as New List(Of String)
lstOfStrings.Add(String1, String2, String3, String4)

You are trying to add a non-nullable field 'new_field' to userprofile without a default

I was early in my development cycle, so this may not work for everyone (but I don't see why it wouldn't).

I added blank=True, null=True to the columns where I was getting the error. Then I ran the python manage.py makemigrations command.

Immediately after running this command (and before running python manage.py migrate), I removed the blank=True, null=True from all the columns. Then I ran python manage.py makemigrations again. I was given an option to just change the columns myself, which I selected.

Then I ran python manage.py migrate and everything worked well!

What is the difference between document.location.href and document.location?

The document.location is an object that contains properties for the current location.

The href property is one of these properties, containing the complete URL, i.e. all the other properties put together.

Some browsers allow you to assign an URL to the location object and acts as if you assigned it to the href property. Some other browsers are more picky, and requires you to use the href property. Thus, to make the code work in all browsers, you have to use the href property.

Both the window and document objects has a location object. You can set the URL using either window.location.href or document.location.href. However, logically the document.location object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href when you want to set the URL.

Good PHP ORM Library?

I just started with Kohana, and it seems the closest to Ruby on Rails without invoking all the complexity of multiple configuration files like with Propel.

Press TAB and then ENTER key in Selenium WebDriver

Be sure to include the Key in the imports...

const {Builder, By, logging, until, Key} = require('selenium-webdriver');

searchInput.sendKeys(Key.ENTER) worked great for me

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

Try using cURL.

<?php

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'http://###.##.##.##/mp/get?mpsrc=http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert format=flv');
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
$query = curl_exec($curl_handle);
curl_close($curl_handle);

?>

Xcode 5 and iOS 7: Architecture and Valid architectures

You do not need to limit your compiler to only armv7 and armv7s by removing arm64 setting from supported architectures. You just need to set Deployment target setting to 5.1.1

Important note: you cannot set Deployment target to 5.1.1 in Build Settings section because it is drop-down only with fixed values. But you can easily set it to 5.1.1 in General section of application settings by just typing the value in text field.

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

Java Enum Methods - return opposite direction enum

Yes we do it all the time. You return a static instance rather than a new Object

 static Direction getOppositeDirection(Direction d){
       Direction result = null;
       if (d != null){
           int newCode = -d.getCode();
           for (Direction direction : Direction.values()){
               if (d.getCode() == newCode){
                   result = direction;
               }
           }
       }
       return result;
 }

How to set DateTime to null

This should work:

if (!string.IsNullOrWhiteSpace(dateTimeEnd))
    eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
    eventCustom.DateTimeEnd = null;

Note that this will throw an exception if the string is not in the correct format.

Installing python module within code

You define the dependent module inside the setup.py of your own package with the "install_requires" option.

If your package needs to have some console script generated then you can use the "console_scripts" entry point in order to generate a wrapper script that will be placed within the 'bin' folder (e.g. of your virtualenv environment).

ASP.Net MVC: Calling a method from a view

Controller not supposed to be called from view. That's the whole idea of MVC - clear separation of concerns.

If you need to call controller from View - you are doing something wrong. Time for refactoring.

"A lambda expression with a statement body cannot be converted to an expression tree"

Use this overload of select:

Obj[] myArray = objects.Select(new Func<Obj,Obj>( o =>
{
    var someLocalVar = o.someVar;

    return new Obj() 
    { 
       Var1 = someLocalVar,
       Var2 = o.var2 
    };
})).ToArray();

How can I view the Git history in Visual Studio Code?

You will find the right icon to click, when you open a file or the welcome page, in the upper right corner.

Enter image description here

And you can add a keyboard shortcut:

Enter image description here

How to tell Maven to disregard SSL errors (and trusting all certs)?

Create a folder ${USER_HOME}/.mvn and put a file called maven.config in it.

The content should be:

-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true

Hope this helps.

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

  1. Simple solution to find index for any string value in the List.

Here is code for List Of String:

int indexOfValue = myList.FindIndex(a => a.Contains("insert value from list"));
  1. Simple solution to find index for any Integer value in the List.

Here is Code for List Of Integer:

    int indexOfNumber = myList.IndexOf(/*insert number from list*/);

How to edit the size of the submit button on a form?

<input type="button" value="submit" style="height: 100px; width: 100px; left: 250; top: 250;">

Use this with your requirements.

Navigate to another page with a button in angular 2

It is important that you decorate the router link and link with square brackets as follows:

<a [routerLink]="['/service']"> <button class="btn btn-info"> link to other page </button></a>

Where "/service" in this case is the path url specified in the routing component.

Can an int be null in Java?

Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so

public int getHeight(String name){
    if(map.containsKey(name)){
        return map.get(name);
    }else{
        return -1;
    }
}

JavaScript: Passing parameters to a callback function

If you are not sure how many parameters are you going to be passed into callback functions, use apply function.

function tryMe (param1, param2) {
  alert (param1 + " and " + param2);
}

function callbackTester(callback,params){
    callback.apply(this,params);
}

callbackTester(tryMe,['hello','goodbye']);

How do I determine whether an array contains a particular value in Java?

Instead of using the quick array initialisation syntax too, you could just initialise it as a List straight away in a similar manner using the Arrays.asList method, e.g.:

public static final List<String> STRINGS = Arrays.asList("firstString", "secondString" ...., "lastString");

Then you can do (like above):

STRINGS.contains("the string you want to find");

Twitter bootstrap 3 two columns full height

So it seems your best option is going with the padding-bottom countered by negative margin-bottom strategy.

I made two examples. One with <header> inside .container, and another with it outside.

Both versions should work properly. Note the use of the following @media query so that it removes the extra padding on smaller screens...

@media screen and (max-width:991px) {
    .content { padding-top:0; }
}

Other than that, those examples should fix your problem.

Decode HTML entities in Python string?

This probably isnt relevant here. But to eliminate these html entites from an entire document, you can do something like this: (Assume document = page and please forgive the sloppy code, but if you have ideas as to how to make it better, Im all ears - Im new to this).

import re
import HTMLParser

regexp = "&.+?;" 
list_of_html = re.findall(regexp, page) #finds all html entites in page
for e in list_of_html:
    h = HTMLParser.HTMLParser()
    unescaped = h.unescape(e) #finds the unescaped value of the html entity
    page = page.replace(e, unescaped) #replaces html entity with unescaped value

Please initialize the log4j system properly. While running web service

You have to create your own log4j.properties in the classpath folder.

How to index into a dictionary?

Dictionaries are unordered in Python versions up to and including Python 3.6. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can use d.keys()[i] and d.values()[i] or d.items()[i]. (Note that these methods create a list of all keys, values or items in Python 2.x. So if you need them more then once, store the list in a variable to improve performance.)

If you do care about the order of the entries, starting with Python 2.7 you can use collections.OrderedDict. Or use a list of pairs

l = [("blue", "5"), ("red", "6"), ("yellow", "8")]

if you don't need access by key. (Why are your numbers strings by the way?)

In Python 3.7, normal dictionaries are ordered, so you don't need to use OrderedDict anymore (but you still can – it's basically the same type). The CPython implementation of Python 3.6 already included that change, but since it's not part of the language specification, you can't rely on it in Python 3.6.

How can I replace every occurrence of a String in a file with PowerShell?

You could try something like this:

$path = "C:\testFile.txt"
$word = "searchword"
$replacement = "ReplacementText"
$text = get-content $path 
$newText = $text -replace $word,$replacement
$newText > $path

Pass array to ajax request in $.ajax()

Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:

$.ajax({
    type: "POST",
    url: "index.php",
    dataType: "json",
    data: JSON.stringify({ paramName: info }),
    success: function(msg){
        $('.answer').html(msg);
    }
});

You just need to make sure you include the JSON2.js file in your page...

MySql sum elements of a column

 select sum(A),sum(B),sum(C) from mytable where id in (1,2,3);

How to calculate the difference between two dates using PHP?

Here is the runnable code

$date1 = date_create('2007-03-24');
$date2 = date_create('2009-06-26');
$diff1 = date_diff($date1,$date2);
$daysdiff = $diff1->format("%R%a");
$daysdiff = abs($daysdiff);

How to compare two dates in php

I know this is late, but for future reference, put the date format into a recognised format by using str_replace then your function will work. (replace the underscore with a dash)

//change the format to dashes instead of underscores, then get the timestamp
$date1 = strtotime(str_replace("_", "-",$date1));
$date2 = strtotime(str_replace("_", "-",$date2));

//compare the dates
if($date1 < $date2){
   //convert the date back to underscore format if needed when printing it out.
   echo '1 is small='.$date1.','.date('d_m_y',$date1);
}else{
   echo '2 is small='.$date2.','.date('d_m_y',$date2);
}

Redeploy alternatives to JRebel

By the Spring guys, used for Grails reloading but works with Java too:

https://github.com/SpringSource/spring-loaded

Matplotlib - How to plot a high resolution graph?

For saving the graph:

matplotlib.rcParams['savefig.dpi'] = 300

For displaying the graph when you use plt.show():

matplotlib.rcParams["figure.dpi"] = 100

Just add them at the top

Android: How can I get the current foreground activity (from a service)?

I could not find a solution that our team would be happy with so we rolled our own. We use ActivityLifecycleCallbacks to keep track of current activity and then expose it through a service:

public interface ContextProvider {
    Context getActivityContext();
}

public class MyApplication extends Application implements ContextProvider {
    private Activity currentActivity;

    @Override
    public Context getActivityContext() {
         return currentActivity;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                MyApplication.this.currentActivity = activity;
            }

            @Override
            public void onActivityStarted(Activity activity) {
                MyApplication.this.currentActivity = activity;
            }

            @Override
            public void onActivityResumed(Activity activity) {
                MyApplication.this.currentActivity = activity;
            }

            @Override
            public void onActivityPaused(Activity activity) {
                MyApplication.this.currentActivity = null;
            }

            @Override
            public void onActivityStopped(Activity activity) {
                // don't clear current activity because activity may get stopped after
                // the new activity is resumed
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                // don't clear current activity because activity may get destroyed after
                // the new activity is resumed
            }
        });
    }
}

Then configure your DI container to return instance of MyApplication for ContextProvider, e.g.

public class ApplicationModule extends AbstractModule {    
    @Provides
    ContextProvider provideMainActivity() {
        return MyApplication.getCurrent();
    }
}

(Note that implementation of getCurrent() is omitted from the code above. It's just a static variable that's set from the application constructor)

What does the "On Error Resume Next" statement do?

It enables error handling. The following is partly from https://msdn.microsoft.com/en-us/library/5hsw66as.aspx

' Enable error handling. When a run-time error occurs, control goes to the statement 
' immediately following the statement where the error occurred, and execution
' continues from that point.
On Error Resume Next

SomeCodeHere

If Err.Number = 0 Then
    WScript.Echo "No Error in SomeCodeHere."
Else
  WScript.Echo "Error in SomeCodeHere: " & Err.Number & ", " & Err.Source & ", " & Err.Description
  ' Clear the error or you'll see it again when you test Err.Number
  Err.Clear
End If

SomeMoreCodeHere

If Err.Number <> 0 Then
  WScript.Echo "Error in SomeMoreCodeHere:" & Err.Number & ", " & Err.Source & ", " & Err.Description
  ' Clear the error or you'll see it again when you test Err.Number
  Err.Clear
End If

' Disables enabled error handler in the current procedure and resets it to Nothing.
On Error Goto 0

' There are also `On Error Goto -1`, which disables the enabled exception in the current 
' procedure and resets it to Nothing, and `On Error Goto line`, 
' which enables the error-handling routine that starts at the line specified in the 
' required line argument. The line argument is any line label or line number. If a run-time 
' error occurs, control branches to the specified line, making the error handler active. 
' The specified line must be in the same procedure as the On Error statement, 
' or a compile-time error will occur.

Bootstrap fullscreen layout with 100% height

All you have to do is have a height of 100vh on your main container/wrapper, and then set height 100% or 50% for child elements.. depending on what you're trying to achieve. I tried to copy your mock up in a basic sense.

In case you want to center stuff within, look into flexbox. I put in an example for you.

You can view it on full screen, and resize the browser and see how it works. The layout stays the same.

_x000D_
_x000D_
.left {_x000D_
  background: grey;  _x000D_
}_x000D_
_x000D_
.right {_x000D_
  background: black;  _x000D_
}_x000D_
_x000D_
.main-wrapper {_x000D_
  height: 100vh;  _x000D_
}_x000D_
_x000D_
.section {_x000D_
  height: 100%;  _x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.half {_x000D_
  background: #f9f9f9;_x000D_
  height: 50%;  _x000D_
  width: 100%;_x000D_
  margin: 15px 0;_x000D_
}_x000D_
_x000D_
h4 {_x000D_
  color: white;  _x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<div class="main-wrapper">_x000D_
  <div class="section left col-xs-3">_x000D_
    <div class="half"><h4>Top left</h4></div>_x000D_
    <div class="half"><h4>Bottom left</h4></div>_x000D_
  </div>_x000D_
  <div class="section right col-xs-9">_x000D_
    <h4>Extra step: center stuff here</h4>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cache an HTTP 'Get' service response in AngularJS?

In Angular 8 we can do like this:

import { Injectable } from '@angular/core';
import { YourModel} from '../models/<yourModel>.model';
import { UserService } from './user.service';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class GlobalDataService {

  private me: <YourModel>;

  private meObservable: Observable<User>;

  constructor(private yourModalService: <yourModalService>, private http: HttpClient) {

  }

  ngOnInit() {

  }


  getYourModel(): Observable<YourModel> {

    if (this.me) {
      return of(this.me);
    } else if (this.meObservable) {
      return this.meObservable;
    }
    else {
      this.meObservable = this.yourModalService.getCall<yourModel>() // Your http call
      .pipe(
        map(data => {
          this.me = data;
          return data;
        })
      );
      return this.meObservable;
    }
  }
}

You can call it like this:

this.globalDataService.getYourModel().subscribe(yourModel => {


});

The above code will cache the result of remote API at first call so that it can be used on further requests to that method.

Nexus 5 USB driver

Well @sonida's answer helped me but Here I am posting complete step How I did it.

Change Mobile Device Settings:

  1. Unplug the device from the computer
  2. Go to Mobile Settings -> Storage.
  3. In the ActionBar, click the option menu and choose "USB computer connection".
  4. Check "Camera (PTP)" connection.

enter image description here

enter image description here

Download Google USB Driver:

5 .Now go to http://developer.android.com/sdk/win-usb.html#top and download USB Drivers --> unzip folder.

enter image description here

Install USB Drivers and Get Connected Device:

6.Then Right click on My computer -->Manage --> Device Manager.

enter image description here

7.You should seed Nexus 5 in the list.

8.Right click on Nexus 5 --> Update Driver Software... --> Browse my computer for driver software

enter image description here

9.select the folder we downloaded/unzipped "latest_usb_driver_windows" and Next ...Ok.

enter image description here

10.Now you will see pop-up dialogue asking for Allow device --> Ok.

11 .That's it!! device is connected now, you can see in DDMS.

enter image description here

Hope this will help someone.

Break string into list of characters in Python

In python many things are iterable including files and strings. Iterating over a filehandler gives you a list of all the lines in that file. Iterating over a string gives you a list of all the characters in that string.

charsFromFile = []
filePath = r'path\to\your\file.txt' #the r before the string lets us use backslashes

for line in open(filePath):
    for char in line:
        charsFromFile.append(char) 
        #apply code on each character here

or if you want a one liner

#the [0] at the end is the line you want to grab.
#the [0] can be removed to grab all lines
[list(a) for a in list(open('test.py'))][0]  

.

.

Edit: as agf mentions you can use itertools.chain.from_iterable

His method is better, unless you want the ability to specify which lines to grab list(itertools.chain.from_iterable(open(filename, 'rU)))

This does however require one to be familiar with itertools, and as a result looses some readablity

If you only want to iterate over the chars, and don't care about storing a list, then I would use the nested for loops. This method is also the most readable.

Java: Convert a String (representing an IP) to InetAddress

Simply call InetAddress.getByName(String host) passing in your textual IP address.

From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.

InetAddress javadoc

Ping all addresses in network, windows

aping can provide a list of hosts and whether each has responded to pings.

 aping -show all 192.168.1.*

Byte array to image conversion

First Install This Package:

Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007

[SixLabors.ImageSharp][1] [1]: https://www.nuget.org/packages/SixLabors.ImageSharp

Then use Below Code For Cast Byte Array To Image :

Image<Rgba32> image = Image.Load(byteArray); 

For Get ImageFormat Use Below Code:

IImageFormat format = Image.DetectFormat(byteArray);

For Mutate Image Use Below Code:

image.Mutate(x => x.Resize(new Size(1280, 960)));

How to split and modify a string in NodeJS?

var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
    arr[i] = ++arr[i];
}

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

Is it better to return null or empty collection?

Empty is much more consumer friendly.

There is a clear method of making up an empty enumerable:

Enumerable.Empty<Element>()

Returning an array using C

Your method will return a local stack variable that will fail badly. To return an array, create one outside the function, pass it by address into the function, then modify it, or create an array on the heap and return that variable. Both will work, but the first doesn't require any dynamic memory allocation to get it working correctly.

void returnArray(int size, char *retArray)
{
  // work directly with retArray or memcpy into it from elsewhere like
  // memcpy(retArray, localArray, size); 
}

#define ARRAY_SIZE 20

int main(void)
{
  char foo[ARRAY_SIZE];
  returnArray(ARRAY_SIZE, foo);
}

What is best tool to compare two SQL Server databases (schema and data)?

I like Open DBDiff.

While not the most complete tool, it works great, it's free, and it's very easy to use.

How do I configure PyCharm to run py.test tests?

find this thread when I hit the same question and found the solution pycharm version:2017.1.2 go to "Preferences" -> "Tools" -> "Python Integrated Tools" and set the default test runner from right side panel as py.test solve my problem

How to Install gcc 5.3 with yum on CentOS 7.2?

Command to install GCC and Development Tools on a CentOS / RHEL 7 server

Type the following yum command as root user:

yum group install "Development Tools"

OR

sudo yum group install "Development Tools"

If above command failed, try:

yum groupinstall "Development Tools"

Do conditional INSERT with SQL?

It is possible with EXISTS condition. WHERE EXISTS tests for the existence of any records in a subquery. EXISTS returns true if the subquery returns one or more records. Here is an example

UPDATE  TABLE_NAME 
SET val1=arg1 , val2=arg2
WHERE NOT EXISTS
    (SELECT FROM TABLE_NAME WHERE val1=arg1 AND val2=arg2)

How is a non-breaking space represented in a JavaScript string?

Remember that .text() strips out markup, thus I don't believe you're going to find &nbsp; in a non-markup result.

Made in to an answer....

var p = $('<p>').html('&nbsp;');
if (p.text() == String.fromCharCode(160) && p.text() == '\xA0')
    alert('Character 160');

Shows an alert, as the ASCII equivalent of the markup is returned instead.

How to convert date to timestamp?

Your string isn't in a format that the Date object is specified to handle. You'll have to parse it yourself, use a date parsing library like MomentJS or the older (and not currently maintained, as far as I can tell) DateJS, or massage it into the correct format (e.g., 2012-02-29) before asking Date to parse it.

Why you're getting NaN: When you ask new Date(...) to handle an invalid string, it returns a Date object which is set to an invalid date (new Date("29-02-2012").toString() returns "Invalid date"). Calling getTime() on a date object in this state returns NaN.

Get file size before uploading

Please do not use ActiveX as chances are that it will display a scary warning message in Internet Explorer and scare your users away.

ActiveX warning

If anyone wants to implement this check, they should only rely on the FileList object available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).

function getFileSize(fileInputElement){
    if (!fileInputElement.value ||
        typeof fileInputElement.files === 'undefined' ||
        typeof fileInputElement.files[0] === 'undefined' ||
        typeof fileInputElement.files[0].size !== 'number'
    ) {
        // File size is undefined.
        return undefined;
    }

    return fileInputElement.files[0].size;
}

Add views in UIStackView programmatically

It is really not recommended to set a height constraint... If you can, never, never, never set a height! You need to check all the constraints of the views inside your UIStackView and be sure that there is constraints for bottom, top, leading and trailing. Someone said to me: it is like a guy pushing on walls. If he don't push on 4 sides, one of the wall will fall on him.

How to declare a Fixed length Array in TypeScript

The Tuple approach :

This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.

Syntax example :

// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]> 

This is the safest approach, considering it prevents accessing indexes out of the boundaries.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
  Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
  & { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }

Tests :

var myFixedLengthArray: FixedLengthArray< [string, string, string]>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? INVALID INDEX ERROR

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR

(*) This solution requires the noImplicitAny typescript configuration directive to be enabled in order to work (commonly recommended practice)


The Array(ish) approach :

This solution behaves as an augmentation of the Array type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.

Syntax example :

let foo: FixedLengthArray<string, 3> 

Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' |  'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
  Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
  & {
    readonly length: L 
    [ I : number ] : T
    [Symbol.iterator]: () => IterableIterator<T>   
  }

Tests :

var myFixedLengthArray: FixedLengthArray<string,3>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? SHOULD FAIL

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL

Auto increment in phpmyadmin

There are possible steps to enable auto increment for a column. I guess the phpMyAdmin version is 3.5.5 but not sure.

Click on Table > Structure tab > Under Action Click Primary (set as primary), click on Change on the pop-up window, scroll left and check A_I. Also make sure you have selected None for Defaultenter image description here

Python - Using regex to find multiple matches and print them out

Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.

How to check if element exists using a lambda expression?

While the accepted answer is correct, I'll add a more elegant version (in my opinion):

boolean idExists = tabPane.getTabs().stream()
    .map(Tab::getId)
    .anyMatch(idToCheck::equals);

Don't neglect using Stream#map() which allows to flatten the data structure before applying the Predicate.

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

Eclipse interface icons very small on high resolution screen in Windows 8.1

Jae's above solution worked for me. The manifest solution didn't work for me. Thanks Jae.

Setup:On my windows 8.1 64 bit non tablet laptop I downloaded eclipse 64 bit with jdk 64 bit.

  1. Right mouse click on desktop to access screen resolution and lowered the screen resolution display from 3000 level to 2048 x 1152.
  2. Click on make text and other items larger or smaller link and changed it to large 150% instead of extra extra large - 250%.
  3. Logged out and Logged back in.
  4. Restart Eclipse and the icons are now visible even if it is a bit smaller, but much more legible now.

What exactly is RESTful programming?

This is amazingly long "discussion" and yet quite confusing to say the least.

IMO:

1) There is no such a thing as restful programing, without a big joint and lots of beer :)

2) Representational State Transfer (REST) is an architectural style specified in the dissertation of Roy Fielding. It has a number of constraints. If your Service/Client respect those then it is RESTful. This is it.

You can summarize(significantly) the constraints to :

  • stateless communication
  • respect HTTP specs (if HTTP is used)
  • clearly communicates the content formats transmitted
  • use hypermedia as the engine of application state

There is another very good post which explains things nicely.

A lot of answers copy/pasted valid information mixing it and adding some confusion. People talk here about levels, about RESTFul URIs(there is not such a thing!), apply HTTP methods GET,POST,PUT ... REST is not about that or not only about that.

For example links - it is nice to have a beautifully looking API but at the end the client/server does not really care of the links you get/send it is the content that matters.

In the end any RESTful client should be able to consume to any RESTful service as long as the content format is known.

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

Replacing localhost with 10.0.2.2 is correct, but you can alsor replace localhost with your physical machine's ip(it is better for debug purposes). Ofc, if ip is provided by dhcp you would have to change it each time...

Good luck!

Correctly ignore all files recursively under a specific folder except for a specific file type

The best answer is to add a Resources/.gitignore file under Resources containing:

# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo

If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:

# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo

You will need to edit that pattern if you add directories deeper than specified.

API Gateway CORS: no 'Access-Control-Allow-Origin' header

In my case, I was simply writing the fetch request URL wrong. On serverless.yml, you set cors to true:

register-downloadable-client:
    handler: fetch-downloadable-client-data/register.register
    events:
      - http:
          path: register-downloadable-client
          method: post
          integration: lambda
          cors: true
          stage: ${self:custom.stage}

and then on the lambda handler you send the headers, but if you make the fetch request wrong on the frontend, you're not going to get that header on the response and you're going to get this error. So, double check your request URL on the front.

How can I declare and use Boolean variables in a shell script?

How can I declare and use Boolean variables in a shell script?

Unlike many other programming languages, Bash does not segregate its variables by "type." [1]

So the answer is pretty clear. There isn't any Boolean variable in Bash.

However:

Using a declare statement, we can limit the value assignment to variables.[2]

#!/bin/bash
declare -ir BOOL=(0 1) # Remember BOOL can't be unset till this shell terminates
readonly false=${BOOL[0]}
readonly true=${BOOL[1]}

# Same as declare -ir false=0 true=1
((true)) && echo "True"
((false)) && echo "False"
((!true)) && echo "Not True"
((!false)) && echo "Not false"

The r option in declare and readonly is used to state explicitly that the variables are readonly. I hope the purpose is clear.

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

To call a sub inside another sub you only need to do:

Call Subname()

So where you have CalculateA(Nc,kij, xi, a1, a) you need to have call CalculateA(Nc,kij, xi, a1, a)

As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...) cause this way it does not appear in the macro list and it's easier to work

Hope it helps, Bruno

PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."

React Native android build failed. SDK location not found

If you are using Ubuntu, just go to android directory of your react-native project and create a file called local.properties and add android sdk path to it as follow:

sdk.dir = /home/[YOUR_USERNAME]/Android/Sdk

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

You need BEGIN ... END to create a block spanning more than one statement. So, if you wanted to do 2 things in one 'leg' of an IF statement, or if you wanted to do more than one thing in the body of a WHILE loop, you'd need to bracket those statements with BEGIN...END.

The GO keyword is not part of SQL. It's only used by Query Analyzer to divide scripts into "batches" that are executed independently.

Check if PHP session has already started

PHP 5.4 introduced session_status(), which is more reliable than relying on session_id().

Consider the following snippet:

session_id('test');
var_export(session_id() != ''); // true, but session is still not started!
var_export(session_status() == PHP_SESSION_ACTIVE); // false

So, to check whether a session is started, the recommended way in PHP 5.4 is now:

session_status() == PHP_SESSION_ACTIVE

Selecting last element in JavaScript array

In case you are using ES6 you can do:

const arr = [ 1, 2, 3 ];
[ ...arr ].pop(); // 3
arr; // [ 1, 2, 3 ] (wasn't changed)

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

Command /usr/bin/codesign failed with exit code 1

This issue happened for me when I had multiple targets in one project, and I changed the CFBundleExecutable plist property to something other than the target's name.

So, for example, I had the following targets in one project:

  • SomeApp
  • SomeApp WatchKit Extension
  • SomeApp WatchKit App
  • SomeApp Today Widget
  • SomeApp for OS X (this is the target where the codesign error happens)

SomeApp for OS X had its CFBundleExecutable property set to just SomeApp, which not only conflicted with the first target called SomeApp but was different from the target it was meant for. Changing SomeApp for OS X to SomeApp and then renaming the first target worked fine for me.

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

You should use ImageView if you don't want it to stretch. Background images will always stretch to fit the view. You need to set it as a Drawable to force the image aspect to the object.

Otherwise, if you are sticking with the Button idea, then you will need to force the scaling in the button to prevent the image from stretching.

Code:

onCreate(Bundle bundle) {
  // Set content layout, etc up here

  // Now adjust button sizes
  Button b = (Button) findViewById(R.id.somebutton);
  int someDimension = 50; //50pixels
  b.setWidth(someDimension);
  b.setHeight(someDimension);
}

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

This is a right answer. you need to import FormsMoudle

first in app.module.ts

**

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule  } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    FormsModule,
    ReactiveFormsModule ,
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

** second in app.component.spec.ts

import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FormsModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

Best regards and hope will be helpfull

How to change the color of a button?

The RIGHT way...

The following methods actually work.

if you wish - using a theme
By default a buttons color is android:colorAccent. So, if you create a style like this...

<style name="Button.White" parent="ThemeOverlay.AppCompat">
    <item name="colorAccent">@android:color/white</item>
</style>

You can use it like this...

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/Button.White"
    />

alternatively - using a tint
You can simply add android:backgroundTint for API Level 21 and higher, or app:backgroundTint for API Level 7 and higher.

For more information, see this blog.

The problem with the accepted answer...

If you replace the background with a color you will loose the effect of the button, and the color will be applied to the entire area of the button. It will not respect the padding, shadow, and corner radius.

The preferred way of creating a new element with jQuery

According to the documentation for 3.4, It is preferred to use attributes with attr() method.

$('<div></div>').attr(
  {
    id: 'some dynanmic|static id',
    "class": 'some dynanmic|static class'
  }
).click(function() {
  $( "span", this ).addClass( "bar" ); // example from the docs
});

SQL Server stored procedure parameters

I'm going on a bit of an assumption here, but I'm assuming the logic inside the procedure gets split up via task. And you cant have nullable parameters as @Yuck suggested because of the dynamics of the parameters?

So going by my assumption

If TaskName = "Path1" Then Something

If TaskName = "Path2" Then Something Else

My initial thought is, if you have separate functions with business-logic you need to create, and you can determine that you have say 5-10 different scenarios, rather write individual stored procedures as needed, instead of trying one huge one solution fits all approach. Might get a bit messy to maintain.

But if you must...

Why not try dynamic SQL, as suggested by @E.J Brennan (Forgive me, i haven't touched SQL in a while so my syntax might be rusty) That being said i don't know if its the best approach, but could this could possibly meet your needs?

CREATE PROCEDURE GetTaskEvents
    @TaskName varchar(50)
    @Values varchar(200)
AS
BEGIN
  DECLARE @SQL VARCHAR(MAX)

  IF @TaskName = 'Something'
  BEGIN
    @SQL = 'INSERT INTO.....' + CHAR(13)
    @SQL += @Values + CHAR(13) 
  END

  IF @TaskName = 'Something Else'
  BEGIN
    @SQL = 'DELETE SOMETHING WHERE' + CHAR(13)
    @SQL += @Values + CHAR(13) 
  END

  PRINT(@SQL)
  EXEC(@SQL)    
END

(The CHAR(13) adds a new line.. an old habbit i picked up somewhere, used to help debugging/reading dynamic procedures when running SQL profiler.)

how to overlap two div in css?

check this fiddle , and if you want to move the overlapped div you set its position to absolute then change it's top and left values

How To: Best way to draw table in console app (C#)

Use MarkDownLog library (you can find it on NuGet)

you can simply use the extension ToMarkdownTable() to any collection, it does all the formatting for you.

 Console.WriteLine(
    yourCollection.Select(s => new
                    {
                        column1 = s.col1,
                        column2 = s.col2,
                        column3 = s.col3,
                        StaticColumn = "X"
                    })
                    .ToMarkdownTable());

Output looks something like this:

Column1  | Column2   | Column3   | StaticColumn   
--------:| ---------:| ---------:| --------------
         |           |           | X              

Min width in window resizing

You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:

body{
   min-width:1000px;        /* Suppose you want minimum width of 1000px */
   width: auto !important;  /* Firefox will set width as auto */
   width:1000px;            /* As IE6 ignores !important it will set width as 1000px; */
}

Or:

body{
   min-width:1000px; // Suppose you want minimum width of 1000px
   _width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

krosenvold's answer inspired the following script which does the following:

  • get the dd dump via ssh from a remote server (as gz file)
  • unzip the dump
  • convert it to vmware

the script is restartable and checks the existence of the intermediate files. It also uses pv and qemu-img -p to show the progress of each step.

In my environment 2 x Ubuntu 12.04 LTS the steps took:

  • 3 hours to get a 47 GByte disk dump of a 60 GByte partition
  • 20 minutes to unpack to a 60 GByte dd file
  • 45 minutes to create the vmware file
#!/bin/bash
# get a dd disk dump and convert it to vmware
#  see http://stackoverflow.com/questions/454899/how-to-convert-flat-raw-disk-image-to-vmdk-for-virtualbox-or-vmplayer
#  Author: wf  2014-10-1919

#
# get a dd dump from the given host's given disk and create a compressed
#   image at the given target 
#
#  1: host e.g. somehost.somedomain
#  2: disk e.g. sda
#  3: target e.g. image.gz
#
# http://unix.stackexchange.com/questions/132797/how-to-use-ssh-to-make-a-dd-copy-of-disk-a-from-host-b-and-save-on-disk-b
getdump() {
  local l_host="$1"
  local l_disk="$2"
  local l_target="$3"
  echo "getting disk dump of $l_disk from $l_host"
  ssh $l_host sudo fdisk -l  | egrep "^/dev/$l_disk"
  if [ $? -ne 0 ]
  then
    echo "device $l_disk does not exist on host $l_host" 1>&2
    exit 1
  else
    if [ ! -f $l_target ]
    then
      ssh $l_host "sudo dd if=/dev/$disk bs=1M | gzip -1 -" | pv | dd of=$l_target
    else
      echo "$l_target already exists"
    fi
  fi
}

#
# optionally install command from package if it is not available yet
# 1: command
# 2: package
#
opt_install() {
  l_command="$1"
  l_package="$2"
  echo "checking that $l_command from package $l_package  is installed ..."
  which $l_command
  if [ $? -ne 0 ]
  then
    echo "installing $l_package to make $l_command available ..."
    sudo apt-get install $l_package 
  fi
}

#
# convert the given image to vmware
#  1: the dd dump image
#  2: the vmware image file to convert to
#
vmware_convert() {
  local l_ddimage="$1"
  local l_vmwareimage="$2"
  echo "converting dd image $l_image to vmware $l_vmwareimage"
  #  convert to VMware disk format showing progess
  # see http://manpages.ubuntu.com/manpages/precise/man1/qemu-img.1.html
  qemu-img convert -p -O vmdk "$l_ddimage" "$l_vmwareimage"
}

#
# show usage
#
usage() {
  echo "usage: $0 host device"
  echo "      host: the host to get the disk dump from e.g. frodo.lotr.org"  
  echo "            you need ssh and sudo privileges on that host"
  echo "
  echo "    device: the disk to dump from e.g. sda"
  echo ""
  echo "  examples:
  echo "       $0 frodo.lotr.org sda"
  echo "       $0 gandalf.lotr.org sdb"
  echo ""
  echo "  the needed packages pv and qemu-utils will be installed if not available"
  echo "  you need local sudo rights for this to work"
  exit 1
}

# check arguments
if [ $# -lt 2 ]
then
  usage
fi

# get the command line parameters
host="$1"
disk="$2"

# calculate the names of the image files
ts=`date "+%Y-%m-%d"`
# prefix of all images
#   .gz the zipped dd
#   .dd the disk dump file
#   .vmware - the vmware disk file
image="${host}_${disk}_image_$ts"

echo "$0 $host/$disk ->  $image"

# first check/install necessary packages
opt_install qemu-img qemu-utils
opt_install pv pv

# check if dd files was already loaded
#  we don't want to start this tedious process twice if avoidable
if [ ! -f $image.gz ]
then
  getdump $host $disk $image.gz
else
  echo "$image.gz already downloaded"
fi

# check if the dd file was already uncompressed
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.dd ]
then
  echo "uncompressing $image.gz"
  zcat $image.gz | pv -cN zcat > $image.dd
else
  echo "image $image.dd already uncompressed"
fi
# check if the vmdk file was already converted
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.vmdk ]
then
  vmware_convert $image.dd $image.vmdk
else
  echo "vmware image $image.vmdk already converted"
fi

Logging best practices

There are lots of great recommendations in the answers.

A general best practice is to consider who will be reading the log. In my case it will be an administrator at the client site. So I log messages that gives them something they can act on. For Example, "Unable to initialize application. This is usually caused by ......"

Pandas: rolling mean by time interval

user2689410's code was exactly what I needed. Providing my version (credits to user2689410), which is faster due to calculating mean at once for whole rows in the DataFrame.

Hope my suffix conventions are readable: _s: string, _i: int, _b: bool, _ser: Series and _df: DataFrame. Where you find multiple suffixes, type can be both.

import pandas as pd
from datetime import datetime, timedelta
import numpy as np

def time_offset_rolling_mean_df_ser(data_df_ser, window_i_s, min_periods_i=1, center_b=False):
    """ Function that computes a rolling mean

    Credit goes to user2689410 at http://stackoverflow.com/questions/15771472/pandas-rolling-mean-by-time-interval

    Parameters
    ----------
    data_df_ser : DataFrame or Series
         If a DataFrame is passed, the time_offset_rolling_mean_df_ser is computed for all columns.
    window_i_s : int or string
         If int is passed, window_i_s is the number of observations used for calculating
         the statistic, as defined by the function pd.time_offset_rolling_mean_df_ser()
         If a string is passed, it must be a frequency string, e.g. '90S'. This is
         internally converted into a DateOffset object, representing the window_i_s size.
    min_periods_i : int
         Minimum number of observations in window_i_s required to have a value.

    Returns
    -------
    Series or DataFrame, if more than one column

    >>> idx = [
    ...     datetime(2011, 2, 7, 0, 0),
    ...     datetime(2011, 2, 7, 0, 1),
    ...     datetime(2011, 2, 7, 0, 1, 30),
    ...     datetime(2011, 2, 7, 0, 2),
    ...     datetime(2011, 2, 7, 0, 4),
    ...     datetime(2011, 2, 7, 0, 5),
    ...     datetime(2011, 2, 7, 0, 5, 10),
    ...     datetime(2011, 2, 7, 0, 6),
    ...     datetime(2011, 2, 7, 0, 8),
    ...     datetime(2011, 2, 7, 0, 9)]
    >>> idx = pd.Index(idx)
    >>> vals = np.arange(len(idx)).astype(float)
    >>> ser = pd.Series(vals, index=idx)
    >>> df = pd.DataFrame({'s1':ser, 's2':ser+1})
    >>> time_offset_rolling_mean_df_ser(df, window_i_s='2min')
                          s1   s2
    2011-02-07 00:00:00  0.0  1.0
    2011-02-07 00:01:00  0.5  1.5
    2011-02-07 00:01:30  1.0  2.0
    2011-02-07 00:02:00  2.0  3.0
    2011-02-07 00:04:00  4.0  5.0
    2011-02-07 00:05:00  4.5  5.5
    2011-02-07 00:05:10  5.0  6.0
    2011-02-07 00:06:00  6.0  7.0
    2011-02-07 00:08:00  8.0  9.0
    2011-02-07 00:09:00  8.5  9.5
    """

    def calculate_mean_at_ts(ts):
        """Function (closure) to apply that actually computes the rolling mean"""
        if center_b == False:
            dslice_df_ser = data_df_ser[
                ts-pd.datetools.to_offset(window_i_s).delta+timedelta(0,0,1):
                ts
            ]
            # adding a microsecond because when slicing with labels start and endpoint
            # are inclusive
        else:
            dslice_df_ser = data_df_ser[
                ts-pd.datetools.to_offset(window_i_s).delta/2+timedelta(0,0,1):
                ts+pd.datetools.to_offset(window_i_s).delta/2
            ]
        if  (isinstance(dslice_df_ser, pd.DataFrame) and dslice_df_ser.shape[0] < min_periods_i) or \
            (isinstance(dslice_df_ser, pd.Series) and dslice_df_ser.size < min_periods_i):
            return dslice_df_ser.mean()*np.nan   # keeps number format and whether Series or DataFrame
        else:
            return dslice_df_ser.mean()

    if isinstance(window_i_s, int):
        mean_df_ser = pd.rolling_mean(data_df_ser, window=window_i_s, min_periods=min_periods_i, center=center_b)
    elif isinstance(window_i_s, basestring):
        idx_ser = pd.Series(data_df_ser.index.to_pydatetime(), index=data_df_ser.index)
        mean_df_ser = idx_ser.apply(calculate_mean_at_ts)

    return mean_df_ser

Append Char To String in C?

The Original poster didn't mean to write:

  char* str = "blablabla";

but

  char str[128] = "blablabla";

Now, adding a single character would seem more efficient than adding a whole string with strcat. Going the strcat way, you could:

  char tmpstr[2];
  tmpstr[0] = c;
  tmpstr[1] = 0;
  strcat (str, tmpstr);

but you can also easily write your own function (as several have done before me):

  void strcat_c (char *str, char c)
  {
    for (;*str;str++); // note the terminating semicolon here. 
    *str++ = c; 
    *str++ = 0;
  }

How to use BufferedReader in Java

Try this to read a file:

BufferedReader reader = null;

try {
    File file = new File("sample-file.dat");
    reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

How do I properly escape quotes inside HTML attributes?

Per HTML syntax, and even HTML5, the following are all valid options:

<option value="&quot;asd">test</option>
<option value="&#34;asd">test</option>
<option value='"asd'>test</option>
<option value='&quot;asd'>test</option>
<option value='&#34;asd'>test</option>
<option value=&quot;asd>test</option>
<option value=&#34;asd>test</option>

Note that if you are using XML syntax the quotes (single or double) are required.

Here's a jsfiddle showing all of the above working.

Will using 'var' affect performance?

It's depends of situation, if you try use, this code bellow.

The expression is converted to "OBJECT" and decrease so much the performance, but it's a isolated problem.

CODE:

public class Fruta
{
    dynamic _instance;

    public Fruta(dynamic obj)
    {
        _instance = obj;
    }

    public dynamic GetInstance()
    {
        return _instance;
    }
}

public class Manga
{
    public int MyProperty { get; set; }
    public int MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }
    public int MyProperty3 { get; set; }
}

public class Pera
{
    public int MyProperty { get; set; }
    public int MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }
}

public class Executa
{
    public string Exec(int count, int value)
    {
        int x = 0;
        Random random = new Random();
        Stopwatch time = new Stopwatch();
        time.Start();

        while (x < count)
        {
            if (value == 0)
            {
                var obj = new Pera();
            }
            else if (value == 1)
            {
                Pera obj = new Pera();
            }
            else if (value == 2)
            {
                var obj = new Banana();
            }
            else if (value == 3)
            {
                var obj = (0 == random.Next(0, 1) ? new Fruta(new Manga()).GetInstance() : new Fruta(new Pera()).GetInstance());
            }
            else
            {
                Banana obj = new Banana();
            }

            x++;
        }

        time.Stop();
        return time.Elapsed.ToString();
    }

    public void ExecManga()
    {
        var obj = new Fruta(new Manga()).GetInstance();
        Manga obj2 = obj;
    }

    public void ExecPera()
    {
        var obj = new Fruta(new Pera()).GetInstance();
        Pera obj2 = obj;
    }
}

Above results with ILSPY.

public string Exec(int count, int value)
{
    int x = 0;
    Random random = new Random();
    Stopwatch time = new Stopwatch();
    time.Start();

    for (; x < count; x++)
    {
        switch (value)
        {
            case 0:
                {
                    Pera obj5 = new Pera();
                    break;
                }
            case 1:
                {
                    Pera obj4 = new Pera();
                    break;
                }
            case 2:
                {
                    Banana obj3 = default(Banana);
                    break;
                }
            case 3:
                {
                    object obj2 = (random.Next(0, 1) == 0) ? new Fruta(new Manga()).GetInstance() : new Fruta(new Pera()).GetInstance();
                    break;
                }
            default:
                {
                    Banana obj = default(Banana);
                    break;
                }
        }
    }
time.Stop();
return time.Elapsed.ToString();
}

If you wish execute this code use the code bellow, and get the difference of times.

        static void Main(string[] args)
    {
        Executa exec = new Executa();            
        int x = 0;
        int times = 4;
        int count = 100000000;
        int[] intanceType = new int[4] { 0, 1, 2, 3 };

        while(x < times)
        {                
            Parallel.For(0, intanceType.Length, (i) => {
                Console.WriteLine($"Tentativa:{x} Tipo de Instancia: {intanceType[i]} Tempo Execução: {exec.Exec(count, intanceType[i])}");
            });
            x++;
        }

        Console.ReadLine();
    }

Regards

Nested jQuery.each() - continue/break

Labeled Break

outerloop:
$(sentences).each(function() 
{
    $(words).each(function(i) 
    {
        break; /* breaks inner loop */
    } 
    $(words).each(function(i)  
    {
        break outerloop; /* breaks outer loop */
    }
}

How do I use a custom Serializer with Jackson?

These are behavior patterns I have noticed while trying to understand Jackson serialization.

1) Assume there is an object Classroom and a class Student. I've made everything public and final for ease.

public class Classroom {
    public final double double1 = 1234.5678;
    public final Double Double1 = 91011.1213;
    public final Student student1 = new Student();
}

public class Student {
    public final double double2 = 1920.2122;
    public final Double Double2 = 2324.2526;
}

2) Assume that these are the serializers we use for serializing the objects into JSON. The writeObjectField uses the object's own serializer if it is registered with the object mapper; if not, then it serializes it as a POJO. The writeNumberField exclusively only accepts primitives as arguments.

public class ClassroomSerializer extends StdSerializer<Classroom> {
    public ClassroomSerializer(Class<Classroom> t) {
        super(t);
    }

    @Override
    public void serialize(Classroom value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
        jgen.writeStartObject();
        jgen.writeObjectField("double1-Object", value.double1);
        jgen.writeNumberField("double1-Number", value.double1);
        jgen.writeObjectField("Double1-Object", value.Double1);
        jgen.writeNumberField("Double1-Number", value.Double1);
        jgen.writeObjectField("student1", value.student1);
        jgen.writeEndObject();
    }
}

public class StudentSerializer extends StdSerializer<Student> {
    public StudentSerializer(Class<Student> t) {
        super(t);
    }

    @Override
    public void serialize(Student value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
        jgen.writeStartObject();
        jgen.writeObjectField("double2-Object", value.double2);
        jgen.writeNumberField("double2-Number", value.double2);
        jgen.writeObjectField("Double2-Object", value.Double2);
        jgen.writeNumberField("Double2-Number", value.Double2);
        jgen.writeEndObject();
    }
}

3) Register only a DoubleSerializer with DecimalFormat output pattern ###,##0.000, in SimpleModule and the output is:

{
  "double1" : 1234.5678,
  "Double1" : {
    "value" : "91,011.121"
  },
  "student1" : {
    "double2" : 1920.2122,
    "Double2" : {
      "value" : "2,324.253"
    }
  }
}

You can see that the POJO serialization differentiates between double and Double, using the DoubleSerialzer for Doubles and using a regular String format for doubles.

4) Register DoubleSerializer and ClassroomSerializer, without the StudentSerializer. We expect that the output is such that if we write a double as an object, it behaves like a Double, and if we write a Double as a number, it behaves like a double. The Student instance variable should be written as a POJO and follow the pattern above since it does not register.

{
  "double1-Object" : {
    "value" : "1,234.568"
  },
  "double1-Number" : 1234.5678,
  "Double1-Object" : {
    "value" : "91,011.121"
  },
  "Double1-Number" : 91011.1213,
  "student1" : {
    "double2" : 1920.2122,
    "Double2" : {
      "value" : "2,324.253"
    }
  }
}

5) Register all serializers. The output is:

{
  "double1-Object" : {
    "value" : "1,234.568"
  },
  "double1-Number" : 1234.5678,
  "Double1-Object" : {
    "value" : "91,011.121"
  },
  "Double1-Number" : 91011.1213,
  "student1" : {
    "double2-Object" : {
      "value" : "1,920.212"
    },
    "double2-Number" : 1920.2122,
    "Double2-Object" : {
      "value" : "2,324.253"
    },
    "Double2-Number" : 2324.2526
  }
}

exactly as expected.

Another important note: If you have multiple serializers for the same class registered with the same Module, then the Module will select the serializer for that class that is most recently added to the list. This should not be used - it's confusing and I am not sure how consistent this is

Moral: if you want to customize serialization of primitives in your object, you must write your own serializer for the object. You cannot rely on the POJO Jackson serialization.

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

You can change the property categorie of the class Article like this:

categorie = models.ForeignKey(
    'Categorie',
    on_delete=models.CASCADE,
)

and the error should disappear.

Eventually you might need another option for on_delete, check the documentation for more details:

https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey

EDIT:

As you stated in your comment, that you don't have any special requirements for on_delete, you could use the option DO_NOTHING:

# ...
on_delete=models.DO_NOTHING,
# ...

How to unpack pkl file?

In case you want to work with the original MNIST files, here is how you can deserialize them.

If you haven't downloaded the files yet, do that first by running the following in the terminal:

wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz

Then save the following as deserialize.py and run it.

import numpy as np
import gzip

IMG_DIM = 28

def decode_image_file(fname):
    result = []
    n_bytes_per_img = IMG_DIM*IMG_DIM

    with gzip.open(fname, 'rb') as f:
        bytes_ = f.read()
        data = bytes_[16:]

        if len(data) % n_bytes_per_img != 0:
            raise Exception('Something wrong with the file')

        result = np.frombuffer(data, dtype=np.uint8).reshape(
            len(bytes_)//n_bytes_per_img, n_bytes_per_img)

    return result

def decode_label_file(fname):
    result = []

    with gzip.open(fname, 'rb') as f:
        bytes_ = f.read()
        data = bytes_[8:]

        result = np.frombuffer(data, dtype=np.uint8)

    return result

train_images = decode_image_file('train-images-idx3-ubyte.gz')
train_labels = decode_label_file('train-labels-idx1-ubyte.gz')

test_images = decode_image_file('t10k-images-idx3-ubyte.gz')
test_labels = decode_label_file('t10k-labels-idx1-ubyte.gz')

The script doesn't normalize the pixel values like in the pickled file. To do that, all you have to do is

train_images = train_images/255
test_images = test_images/255

What's the difference between ".equals" and "=="?

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. EX:

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1 == obj2)
   System.out.println("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

Even though the strings have the same exact characters (“xyz”), The code above will actually output: obj1==obj2 is FALSE

Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1.equals(obj2))
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

This code will output the following:

obj1==obj2 is TRUE

Get index of array element faster than O(n)

Why not use index or rindex?

array = %w( a b c d e)
# get FIRST index of element searched
puts array.index('a')
# get LAST index of element searched
puts array.rindex('a')

index: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index

rindex: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-rindex

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

Java Class.cast() vs. cast operator

C++ and Java are different languages.

The Java C-style cast operator is much more restricted than the C/C++ version. Effectively the Java cast is like the C++ dynamic_cast if the object you have cannot be cast to the new class you will get a run time (or if there is enough information in the code a compile time) exception. Thus the C++ idea of not using C type casts is not a good idea in Java

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

How can I add an item to a SelectList in ASP.net MVC

This is possible.

//Create the select list item you want to add
SelectListItem selListItem = new SelectListItem() { Value = "null", Text = "Select One" };

//Create a list of select list items - this will be returned as your select list
List<SelectListItem> newList = new List<SelectListItem>();

//Add select list item to list of selectlistitems
newList.Add(selListItem);

//Return the list of selectlistitems as a selectlist
return new SelectList(newList, "Value", "Text", null);

Converting Integer to Long

new Long(Integer.longValue());

or

new Long(Integer.toString());

Undefined index with $_POST

In PHP, a variable or array element which has never been set is different from one whose value is null; attempting to access such an unset value is a runtime error.

That's what you're running into: the array $_POST does not have any element at the key "username", so the interpreter aborts your program before it ever gets to the nullity test.

Fortunately, you can test for the existence of a variable or array element without actually trying to access it; that's what the special operator isset does:

if (isset($_POST["username"]))
{
  $user = $_POST["username"];
  echo $user;
  echo " is your username";
} 
else 
{
  $user = null;
  echo "no username supplied";
}

This looks like it will blow up in exactly the same way as your code, when PHP tries to get the value of $_POST["username"] to pass as an argument to the function isset(). However, isset() is not really a function at all, but special syntax recognized before the evaluation stage, so the PHP interpreter checks for the existence of the value without actually trying to retrieve it.

It's also worth mentioning that as runtime errors go, a missing array element is considered a minor one (assigned the E_NOTICE level). If you change the error_reporting level so that notices are ignored, your original code will actually work as written, with the attempted array access returning null. But that's considered bad practice, especially for production code.

Side note: PHP does string interpolation, so the echo statements in the if block can be combined into one:

echo "$user is your username";

HTML Input Type Date, Open Calendar by default

This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.

<input type="date" data-date-inline-picker="true" />

Here is a small demo

How can I read and manipulate CSV file data in C++?

Here is some code you can use. The data from the csv is stored inside an array of rows. Each row is an array of strings. Hope this helps.

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
typedef std::string String;
typedef std::vector<String> CSVRow;
typedef CSVRow::const_iterator CSVRowCI;
typedef std::vector<CSVRow> CSVDatabase;
typedef CSVDatabase::const_iterator CSVDatabaseCI;
void readCSV(std::istream &input, CSVDatabase &db);
void display(const CSVRow&);
void display(const CSVDatabase&);
int main(){
  std::fstream file("file.csv", std::ios::in);
  if(!file.is_open()){
    std::cout << "File not found!\n";
    return 1;
  }
  CSVDatabase db;
  readCSV(file, db);
  display(db);
}
void readCSV(std::istream &input, CSVDatabase &db){
  String csvLine;
  // read every line from the stream
  while( std::getline(input, csvLine) ){
    std::istringstream csvStream(csvLine);
    CSVRow csvRow;
    String csvCol;
    // read every element from the line that is seperated by commas
    // and put it into the vector or strings
    while( std::getline(csvStream, csvCol, ',') )
      csvRow.push_back(csvCol);
    db.push_back(csvRow);
  }
}
void display(const CSVRow& row){
  if(!row.size())
    return;
  CSVRowCI i=row.begin();
  std::cout<<*(i++);
  for(;i != row.end();++i)
    std::cout<<','<<*i;
}
void display(const CSVDatabase& db){
  if(!db.size())
    return;
  CSVDatabaseCI i=db.begin();
  for(; i != db.end(); ++i){
    display(*i);
    std::cout<<std::endl;
  }
}

Can't load AMD 64-bit .dll on a IA 32-bit platform

If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.

Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)

Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.

If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...

How to embed fonts in CSS?

One of the best source of information on this topic is Paul Irish's Bulletproof @font-face syntax article.

Read it and you will end with something like:

/* definition */
@font-face {
  font-family: EntezareZohoor2;
  src: url('fonts/EntezareZohoor2.eot');
  src: url('fonts/EntezareZohoor2.eot?') format('?'),
       url('fonts/EntezareZohoor2.woff') format('woff'),
       url('fonts/EntezareZohoor2.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

/* use */
body {
    font-family: EntezareZohoor2, Tahoma, serif;
}

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

Explode PHP string by new line

Try "\n\r" (double quotes) or just "\n".

If you're not sure which type of EOL you have, run a str_replace before your explode, replacing "\n\r" with "\n".

In Swift how to call method with parameters on GCD main thread?

Here's the nicer (IMO) Swifty/Cocoa style syntax to achieve the same result as the other answers:

NSOperationQueue.mainQueue().addOperationWithBlock({
    // Your code here
})

Or you could grab the popular Async Swift library for even less code and more functionality:

Async.main {
    // Your code here
}