Programs & Examples On #System.array

Serves as the base class for arrays. Provides methods for creating, copying, manipulating, searching, and sorting arrays.

C# Iterating through an enum? (Indexing a System.Array)

You can cast that Array to different types of Arrays:

myEnum[] values = (myEnum[])Enum.GetValues(typeof(myEnum));

or if you want the integer values:

int[] values = (int[])Enum.GetValues(typeof(myEnum));

You can iterate those casted arrays of course :)

using stored procedure in entity framework

After importing stored procedure, you can create object of stored procedure pass the parameter like function

using (var entity = new FunctionsContext())
{
   var DBdata = entity.GetFunctionByID(5).ToList<Functions>();
}

or you can also use SqlQuery

using (var entity = new FunctionsContext())
{
    var Parameter = new SqlParameter {
                     ParameterName = "FunctionId",
                     Value = 5
            };

    var DBdata = entity.Database.SqlQuery<Course>("exec GetFunctionByID @FunctionId ", Parameter).ToList<Functions>();
}

Java 8: How do I work with exception throwing methods in streams?

You need to wrap your method call into another one, where you do not throw checked exceptions. You can still throw anything that is a subclass of RuntimeException.

A normal wrapping idiom is something like:

private void safeFoo(final A a) {
    try {
        a.foo();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

(Supertype exception Exception is only used as example, never try to catch it yourself)

Then you can call it with: as.forEach(this::safeFoo).

How to add a line break in an Android TextView?

Also you can add "&lt;br&#47;&gt;" instead of \n.

It's HTML escaped code for <br/>

And then you can add text to TexView:

articleTextView.setText(Html.fromHtml(textForTextView));

Use jQuery to hide a DIV when the user clicks outside of it

Here's a jsfiddle I found on another thread, works with esc key also: http://jsfiddle.net/S5ftb/404

    var button = $('#open')[0]
    var el     = $('#test')[0]

    $(button).on('click', function(e) {
      $(el).show()
      e.stopPropagation()
    })

    $(document).on('click', function(e) {
      if ($(e.target).closest(el).length === 0) {
        $(el).hide()
      }
    })

    $(document).on('keydown', function(e) {
      if (e.keyCode === 27) {
        $(el).hide()
      }
    })

Detect if PHP session exists

The original code is from Sabry Suleiman.

Made it a bit prettier:

function is_session_started() {

    if ( php_sapi_name() === 'cli' )
        return false;

    return version_compare( phpversion(), '5.4.0', '>=' )
        ? session_status() === PHP_SESSION_ACTIVE
        : session_id() !== '';
}

First condition checks the Server API in use. If Command Line Interface is used, the function returns false.

Then we return the boolean result depending on the PHP version in use.

In ancient history you simply needed to check session_id(). If it's an empty string, then session is not started. Otherwise it is.

Since 5.4 to at least the current 8.0 the norm is to check session_status(). If it's not PHP_SESSION_ACTIVE, then either the session isn't started yet (PHP_SESSION_NONE) or sessions are not available altogether (PHP_SESSION_DISABLED).

Ruby objects and JSON serialization (without Rails)

require 'json'
{"foo" => "bar"}.to_json
# => "{\"foo\":\"bar\"}"

How to select label for="XYZ" in CSS?

The selector would be label[for=email], so in CSS:

label[for=email]
{
    /* ...definitions here... */
}

...or in JavaScript using the DOM:

var element = document.querySelector("label[for=email]");

...or in JavaScript using jQuery:

var element = $("label[for=email]");

It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.

(I'm assuming that the template {t _your_email} will fill in a field with id="email". If not, use a class instead.)

Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:

label[for="field[]"]
{
    /* ...definitions here... */
}

They can be single or double quotes.

Regex to match string containing two names in any order

You can do checks using lookarounds:

^(?=.*\bjack\b)(?=.*\bjames\b).*$

Test it.

This approach has the advantage that you can easily specify multiple conditions.

^(?=.*\bjack\b)(?=.*\bjames\b)(?=.*\bjason\b)(?=.*\bjules\b).*$

Bootstrap button - remove outline on Chrome OS X

Search and replace

outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;

Replace to

outline: 0;

How do I get the information from a meta tag with JavaScript?

You can use this:

function getMeta(metaName) {
  const metas = document.getElementsByTagName('meta');

  for (let i = 0; i < metas.length; i++) {
    if (metas[i].getAttribute('name') === metaName) {
      return metas[i].getAttribute('content');
    }
  }

  return '';
}

console.log(getMeta('video'));

How do I assert an Iterable contains elements with a certain property?

Alternatively to hasProperty you can try hamcrest-more-matchers where matcher with extracting function. In your case it will look like:

import static com.github.seregamorph.hamcrest.MoreMatchers.where;

assertThat(myClass.getMyItems(), contains(
    where(MyItem::getName, is("foo")), 
    where(MyItem::getName, is("bar"))
));

The advantages of this approach are:

  • It is not always possible to verify by field if the value is computed in get-method
  • In case of mismatch there should be a failure message with diagnostics (pay attention to resolved method reference MyItem.getName:
Expected: iterable containing [Object that matches is "foo" after call
MyItem.getName, Object that matches is "bar" after call MyItem.getName]
     but: item 0: was "wrong-name"
  • It works in Java 8, Java 11 and Java 14

Get hours difference between two dates in Moment Js

            var timecompare = {
            tstr: "",
            get: function (current_time, startTime, endTime) {
                this.tstr = "";
                var s = current_time.split(":"), t1 = tm1.split(":"), t2 = tm2.split(":"), t1s = Number(t1[0]), t1d = Number(t1[1]), t2s = Number(t2[0]), t2d = Number(t2[1]);

                if (t1s < t2s) {
                    this.t(t1s, t2s);
                }

                if (t1s > t2s) {
                    this.t(t1s, 23);
                    this.t(0, t2s);
                }

                var saat_dk = Number(s[1]);

                if (s[0] == tm1.substring(0, 2) && saat_dk >= t1d)
                    return true;
                if (s[0] == tm2.substring(0, 2) && saat_dk <= t2d)
                    return true;
                if (this.tstr.indexOf(s[0]) != 1 && this.tstr.indexOf(s[0]) != -1 && !(this.tstr.indexOf(s[0]) == this.tstr.length - 2))
                    return true;

                return false;

            },
            t: function (ii, brk) {
                for (var i = 0; i <= 23; i++) {
                    if (i < ii)
                        continue;
                    var s = (i < 10) ? "0" + i : i + "";
                    this.tstr += "," + s;
                    if (brk == i)
                        break;
                }
            }};

Using SimpleXML to create an XML object from scratch

Please see my answer here. As dreamwerx.myopenid.com points out, it is possible to do this with SimpleXML, but the DOM extension would be the better and more flexible way. Additionally there is a third way: using XMLWriter. It's much more simple to use than the DOM and therefore it's my preferred way of writing XML documents from scratch.

$w=new XMLWriter();
$w->openMemory();
$w->startDocument('1.0','UTF-8');
$w->startElement("root");
    $w->writeAttribute("ah", "OK");
    $w->text('Wow, it works!');
$w->endElement();
echo htmlentities($w->outputMemory(true));

By the way: DOM stands for Document Object Model; this is the standardized API into XML documents.

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

Array.push() if does not exist?

This is working func for an objects comparison. In some cases you might have lot of fields to compare. Simply loop the array and call this function with a existing items and new item.

 var objectsEqual = function (object1, object2) {
        if(!object1 || !object2)
            return false;
        var result = true;
        var arrayObj1 = _.keys(object1);
        var currentKey = "";
        for (var i = 0; i < arrayObj1.length; i++) {
            currentKey = arrayObj1[i];
            if (object1[currentKey] !== null && object2[currentKey] !== null)
                if (!_.has(object2, currentKey) ||
                    !_.isEqual(object1[currentKey].toUpperCase(), object2[currentKey].toUpperCase()))
                    return false;
        }
        return result;
    };

NodeJs : TypeError: require(...) is not a function

For me, this was an issue with cyclic dependencies.

IOW, module A required module B, and module B required module A.

So in module B, require('./A') is an empty object rather than a function.

How to deal with cyclic dependencies in Node.js

Git in Visual Studio - add existing project?

I always forget this so this is more for myself but maybe might help someone else using VS.

Visual Studio has the concept of Solutions. In git however, it has the concept of a git repository tracked by local and remote branches. All the files and folders that get added to git are local.

Now going back to Visual Studio Solutions when you create a standard template project it creates all projects locally to that solution.

So the problem happens when you add a project that is not local to the solution or to git for that matter. What happens is that the solution file .sln is updated with the project location but the actual contents of the project, project files and folders can not be added to git because they are on a separate directory or a separate network drive or one some ftp server etc.... This might be preferable if you only want a reference to a project file that gets compiled in the .sln file only or you want to source them to separate git or github repositories. But you don't want the actual files to be tracked by git locally.

To remedy this (i.e. you want to add them to your git repository) you just move the remote files of interest within the purview of the solution and its projects files so that they are local.

No space left on device

Such difference between the output of du -sh and df -h may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.

how to create Socket connection in Android?

Simple socket server app example

I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.

This example app runs a server that returns a ROT-1 cypher of the input.

You would then need to add an Exit button + some sleep delays, but this should get you started.

To play with it:

Android sockets are the same as Java's, except we have to deal with some permission issues.

src/com/cirosantilli/android_cheat/socket/Main.java

package com.cirosantilli.android_cheat.socket;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Main extends Activity {
    static final String TAG = "AndroidCheatSocket";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(Main.TAG, "onCreate");
        Main.this.startService(new Intent(Main.this, MyService.class));
    }

    public static class MyService extends IntentService {
        public MyService() {
            super("MyService");
        }
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(Main.TAG, "onHandleIntent");
            final int port = 12345;
            ServerSocket listener = null;
            try {
                listener = new ServerSocket(port);
                Log.d(Main.TAG, String.format("listening on port = %d", port));
                while (true) {
                    Log.d(Main.TAG, "waiting for client");
                    Socket socket = listener.accept();
                    Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    PrintStream out = new PrintStream(socket.getOutputStream());
                    for (String inputLine; (inputLine = in.readLine()) != null;) {
                        Log.d(Main.TAG, "received");
                        Log.d(Main.TAG, inputLine);
                        StringBuilder outputStringBuilder = new StringBuilder("");
                        char inputLineChars[] = inputLine.toCharArray();
                        for (char c : inputLineChars)
                            outputStringBuilder.append(Character.toChars(c + 1));
                        out.println(outputStringBuilder);
                    }
                }
            } catch(IOException e) {
                Log.d(Main.TAG, e.toString());
            }
        }
    }
}

We need a Service or other background method or else: How do I fix android.os.NetworkOnMainThreadException?

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cirosantilli.android_cheat.socket"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="22" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:label="AndroidCheatsocket">
        <activity android:name="Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".Main$MyService" />
    </application>
</manifest>

We must add: <uses-permission android:name="android.permission.INTERNET" /> or else: Java socket IOException - permission denied

On GitHub with a build.xml: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket

Array slices in C#

If you want IEnumerable<byte>, then just

IEnumerable<byte> data = foo.Take(x);

Fill formula down till last row in column

Alternatively, you may use FillDown

Range("M3") = "=G3&"",""&L3": Range("M3:M" & LastRow).FillDown

How to compare two NSDates: Which is more recent?

Use this simple function for date comparison

-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{

BOOL isTokonValid;

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
    isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
    isTokonValid = NO;
} else {
    isTokonValid = NO;
    NSLog(@"dates are the same");
}

return isTokonValid;}

How to validate IP address in Python?

Don't parse it. Just ask.

import socket

try:
    socket.inet_aton(addr)
    # legal
except socket.error:
    # Not legal

What is the HTML tabindex attribute?

the values you set determine the order that your keyboard focus will move between elements on the website.

In the following example, the first time you press tab, your cursor will move to #foo, then #awesome, then #bar

<input id="foo" tabindex="1"  />
<input id="bar" tabindex="3"  />
<input id="awesome" tabindex="2"  />

If you have not defined tab indexes anywhere, the keyboard focus will follow the HTML tags of you page in the order in which they are defined in the HTML document.

If you tab more times than you have specified tabindexes for, the focus will move as if there were no tabindexes, i.e. in the order of appearance of the HTML tags

Best practices for SQL varchar column length

VARCHAR(255) and VARCHAR(2) take exactly the same amount of space on disk! So the only reason to limit it is if you have a specific need for it to be smaller. Otherwise make them all 255.

Specifically, when doing sorting, larger column do take up more space, so if that hurts performance, then you need to worry about it and make them smaller. But if you only ever select 1 row from that table, then you can just make them all 255 and it won't matter.

See: What are the optimum varchar sizes for MySQL?

What is the IntelliJ shortcut key to create a javadoc comment?

You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else. By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment in order to find the action.

How to sum all column values in multi-dimensional array?

example array here

Code here:

        $temp_arr = [];
        foreach ($a as $k => $v) {
            if(!is_null($v)) {
                $sum = isset($temp_arr[$v[0]]) ? ((int)$v[5] + $sum) : (int)$v[5];
                $temp_arr[$v[0]] = $sum;
            }
        }
        return $temp_arr;

Result:

{SEQ_OK: 1328,SEQ_ERROR: 561}

Creating a file name as a timestamp in a batch job

This worked for me and was a filename-safe solution (though it generates a MM-dd-YYYY format):

C:\ set SAVESTAMP=%DATE:/=-%@%TIME::=-%
C:\ set SAVESTAMP=%SAVESTAMP: =%
C:\ set SAVESTAMP=%SAVESTAMP:,=.%.jpg
C:\ echo %SAVESTAMP%
[email protected]

The first command takes a DATE and replaces / with -, takes the TIME and replaces : with -, and combines them into DATE@TIME format. The second set statement removes any spaces, and the third set replaces , with . and appends the .jpg extension.

The above code is used in a little script that pulls images from a security IP Camera for further processing:

:while
set SAVESTAMP=%DATE:/=-%@%TIME::=-%
set SAVESTAMP=%SAVESTAMP: =%
set SAVESTAMP=%SAVESTAMP:,=.%.jpg
wget-1.10.2.exe --tries=0 -O %SAVESTAMP% http://admin:<password>@<ip address>:<port>/snapshot.cgi
timeout 1
GOTO while

Difference between window.location.href=window.location.href and window.location.reload()

If you add the boolean true to the reload window.location.reload(true) it will load from server.

It is not clear how supported this boolean is, W3Org mentions that NS used to support it

There MIGHT be a difference between the content of window.location.href and document.URL - there at least used to be a difference between location.href and the non-standard and deprecated document.location that had to do with redirection, but that is really last millennium.

For documentation purposes I would use window.location.reload() because that is what you want to do.

Bootstrap 3: How do you align column content to bottom of row

Vertical align bottom and remove the float seems to work. I then had a margin issue, but the -2px keeps them from getting pushed down (and they still don't overlap)

.profile-header > div {
  display: inline-block;
  vertical-align: bottom;
  float: none;
  margin: -2px;
}
.profile-header {
  margin-bottom:20px;
  border:2px solid green;
  display: table-cell;
}
.profile-pic {
  height:300px;
  border:2px solid red;
}
.profile-about {
  border:2px solid blue;
}
.profile-about2 {
  border:2px solid pink;
}

Example here: http://www.bootply.com/125740#

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

do not forget to do it with parse html. like:

$.ajax({
    url: url, 
    cache: false,
    success: function(response) {
        var parsed = $.parseHTML(response);
        result = $(parsed).find("#result");
    }
});

has to work :)

Executing Javascript code "on the spot" in Chrome?

If you mean you want to execute the function inputted, yes, that is simple:

Use this JS code:

eval(document.getElementById( -- el ID -- ).value);

How to get whole and decimal part of a number?

val = -3.1234

fraction = abs(val - as.integer(val) ) 

Python subprocess/Popen with a modified environment

The env parameter accepts a dictionary. You can simply take os.environ, add a key (your desired variable) (to a copy of the dict if you must) to that and use it as a parameter to Popen.

jQuery UI DatePicker - Change Date Format

If you setup a datepicker on an input[type="text"] element you may not get a consistently formatted date, particularly when the user doesn't follow the date format for data entry.

For example, when you set the dateFormat as dd-mm-yy and the user types 1-1-1. The datepicker will convert this to Jan 01, 2001 internally but calling val() on the datepicker object will return the string "1-1-1" -- exactly what is in the text field.

This implies you should either be validating the user input to ensure the date entered is in the format you expect or not allowing the user to enter dates freeform (preferring instead the calendar picker). Even so it is possible to force the datepicker code to give you a string formatted like you expect:

var picker = $('#datepicker');

picker.datepicker({ dateFormat: 'dd-mm-yy' });

picker.val( '1-1-1' );  // simulate user input

alert( picker.val() );  // "1-1-1"

var d = picker.datepicker( 'getDate' );
var f = picker.datepicker( 'option', 'dateFormat' );
var v = $.datepicker.formatDate( f, d );

alert( v );             // "01-01-2001"

Be aware however that while the datepicker's getDate() method will return a date, it can only do so much with user input that doesn't exactly match the date format. This means in the absence of validation it is possible to get a date back that is different from what the user expects. Caveat emptor.

jquery to change style attribute of a div class

this helpful for you..

$('.handle').css('left', '300px');

SQL Server - Return value after INSERT

There are many ways to exit after insert

When you insert data into a table, you can use the OUTPUT clause to return a copy of the data that’s been inserted into the table. The OUTPUT clause takes two basic forms: OUTPUT and OUTPUT INTO. Use the OUTPUT form if you want to return the data to the calling application. Use the OUTPUT INTO form if you want to return the data to a table or a table variable.

DECLARE @MyTableVar TABLE (id INT,NAME NVARCHAR(50));

INSERT INTO tableName
(
  NAME,....
)OUTPUT INSERTED.id,INSERTED.Name INTO @MyTableVar
VALUES
(
   'test',...
)

IDENT_CURRENT: It returns the last identity created for a particular table or view in any session.

SELECT IDENT_CURRENT('tableName') AS [IDENT_CURRENT]

SCOPE_IDENTITY: It returns the last identity from a same session and the same scope. A scope is a stored procedure/trigger etc.

SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];  

@@IDENTITY: It returns the last identity from the same session.

SELECT @@IDENTITY AS [@@IDENTITY];

How to write trycatch in R

Here goes a straightforward example:

# Do something, or tell me why it failed
my_update_function <- function(x){
    tryCatch(
        # This is what I want to do...
        {
        y = x * 2
        return(y)
        },
        # ... but if an error occurs, tell me what happened: 
        error=function(error_message) {
            message("This is my custom message.")
            message("And below is the error message from R:")
            message(error_message)
            return(NA)
        }
    )
}

If you also want to capture a "warning", just add warning= similar to the error= part.

Convert a secure string to plain text

The easiest way to convert back it in PowerShell

[System.Net.NetworkCredential]::new("", $SecurePassword).Password

Use a cell value in VBA function with a variable

VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.

Dim val1 As Integer, val2 As Integer, i As Integer

For i = 1 To 333

  Sheets("Feuil2").Activate
  ActiveSheet.Cells(i, 1).Select

    val1 = Cells(i, 1).Value
    val2 = Cells(i, 2).Value

Sheets("Classeur2.csv").Select
Cells(val1, val2).Select

ActiveCell.FormulaR1C1 = "1"

Next i

jQuery.ajax handling continue responses: "success:" vs ".done"?

If you need async: false in your ajax, you should use success instead of .done. Else you better to use .done. This is from jQuery official site:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

What's the difference between utf8_general_ci and utf8_unicode_ci?

In brief words:

If you need better sorting order - use utf8_unicode_ci (this is the preferred method),

but if you utterly interested in performance - use utf8_general_ci, but know that it is a little outdated.

The differences in terms of performance are very slight.

Compiling php with curl, where is curl installed?

If you're going to compile a 64bit version(x86_64) of php use: /usr/lib64/

For architectures (i386 ... i686) use /usr/lib/

I recommend compiling php to the same architecture as apache. As you're using a 64bit linux i asume your apache is also compiled for x86_64.

What does 'super' do in Python?

When calling super() to resolve to a parent's version of a classmethod, instance method, or staticmethod, we want to pass the current class whose scope we are in as the first argument, to indicate which parent's scope we're trying to resolve to, and as a second argument the object of interest to indicate which object we're trying to apply that scope to.

Consider a class hierarchy A, B, and C where each class is the parent of the one following it, and a, b, and c respective instances of each.

super(B, b) 
# resolves to the scope of B's parent i.e. A 
# and applies that scope to b, as if b was an instance of A

super(C, c) 
# resolves to the scope of C's parent i.e. B
# and applies that scope to c

super(B, c) 
# resolves to the scope of B's parent i.e. A 
# and applies that scope to c

Using super with a staticmethod

e.g. using super() from within the __new__() method

class A(object):
    def __new__(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        return super(A, cls).__new__(cls, *a, **kw)

Explanation:

1- even though it's usual for __new__() to take as its first param a reference to the calling class, it is not implemented in Python as a classmethod, but rather a staticmethod. That is, a reference to a class has to be passed explicitly as the first argument when calling __new__() directly:

# if you defined this
class A(object):
    def __new__(cls):
        pass

# calling this would raise a TypeError due to the missing argument
A.__new__()

# whereas this would be fine
A.__new__(A)

2- when calling super() to get to the parent class we pass the child class A as its first argument, then we pass a reference to the object of interest, in this case it's the class reference that was passed when A.__new__(cls) was called. In most cases it also happens to be a reference to the child class. In some situations it might not be, for instance in the case of multiple generation inheritances.

super(A, cls)

3- since as a general rule __new__() is a staticmethod, super(A, cls).__new__ will also return a staticmethod and needs to be supplied all arguments explicitly, including the reference to the object of insterest, in this case cls.

super(A, cls).__new__(cls, *a, **kw)

4- doing the same thing without super

class A(object):
    def __new__(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        return object.__new__(cls, *a, **kw)

Using super with an instance method

e.g. using super() from within __init__()

class A(object): 
    def __init__(self, *a, **kw):
        # ...
        # you make some changes here
        # ...

        super(A, self).__init__(*a, **kw)

Explanation:

1- __init__ is an instance method, meaning that it takes as its first argument a reference to an instance. When called directly from the instance, the reference is passed implicitly, that is you don't need to specify it:

# you try calling `__init__()` from the class without specifying an instance
# and a TypeError is raised due to the expected but missing reference
A.__init__() # TypeError ...

# you create an instance
a = A()

# you call `__init__()` from that instance and it works
a.__init__()

# you can also call `__init__()` with the class and explicitly pass the instance 
A.__init__(a)

2- when calling super() within __init__() we pass the child class as the first argument and the object of interest as a second argument, which in general is a reference to an instance of the child class.

super(A, self)

3- The call super(A, self) returns a proxy that will resolve the scope and apply it to self as if it's now an instance of the parent class. Let's call that proxy s. Since __init__() is an instance method the call s.__init__(...) will implicitly pass a reference of self as the first argument to the parent's __init__().

4- to do the same without super we need to pass a reference to an instance explicitly to the parent's version of __init__().

class A(object): 
    def __init__(self, *a, **kw):
        # ...
        # you make some changes here
        # ...

        object.__init__(self, *a, **kw)

Using super with a classmethod

class A(object):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        print "A.alternate_constructor called"
        return cls(*a, **kw)

class B(A):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        print "B.alternate_constructor called"
        return super(B, cls).alternate_constructor(*a, **kw)

Explanation:

1- A classmethod can be called from the class directly and takes as its first parameter a reference to the class.

# calling directly from the class is fine,
# a reference to the class is passed implicitly
a = A.alternate_constructor()
b = B.alternate_constructor()

2- when calling super() within a classmethod to resolve to its parent's version of it, we want to pass the current child class as the first argument to indicate which parent's scope we're trying to resolve to, and the object of interest as the second argument to indicate which object we want to apply that scope to, which in general is a reference to the child class itself or one of its subclasses.

super(B, cls_or_subcls)

3- The call super(B, cls) resolves to the scope of A and applies it to cls. Since alternate_constructor() is a classmethod the call super(B, cls).alternate_constructor(...) will implicitly pass a reference of cls as the first argument to A's version of alternate_constructor()

super(B, cls).alternate_constructor()

4- to do the same without using super() you would need to get a reference to the unbound version of A.alternate_constructor() (i.e. the explicit version of the function). Simply doing this would not work:

class B(A):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        print "B.alternate_constructor called"
        return A.alternate_constructor(cls, *a, **kw)

The above would not work because the A.alternate_constructor() method takes an implicit reference to A as its first argument. The cls being passed here would be its second argument.

class B(A):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        print "B.alternate_constructor called"
        # first we get a reference to the unbound 
        # `A.alternate_constructor` function 
        unbound_func = A.alternate_constructor.im_func
        # now we call it and pass our own `cls` as its first argument
        return unbound_func(cls, *a, **kw)

Execute stored procedure with an Output parameter?

I'm using output parameter in SQL Proc and later I used this values in resultset.

enter image description here

What does "publicPath" in Webpack do?

the publicPath is just used for dev purpose, I was confused at first time I saw this config property, but it makes sense now that I've used webpack for a while

suppose you put all your js source file under src folder, and you config your webpack to build the source file to dist folder with output.path.

But you want to serve your static assets under a more meaningful location like webroot/public/assets, this time you can use out.publicPath='/webroot/public/assets', so that in your html, you can reference your js with <script src="/webroot/public/assets/bundle.js"></script>.

when you request webroot/public/assets/bundle.js the webpack-dev-server will find the js under the dist folder

Update:

thanks for Charlie Martin to correct my answer

original: the publicPath is just used for dev purpose, this is not just for dev purpose

No, this option is useful in the dev server, but its intention is for asynchronously loading script bundles in production. Say you have a very large single page application (for example Facebook). Facebook wouldn't want to serve all of its javascript every time you load the homepage, so it serves only whats needed on the homepage. Then, when you go to your profile, it loads some more javascript for that page with ajax. This option tells it where on your server to load that bundle from

Adding n hours to a date in Java?

Date argDate = new Date(); //set your date.
String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
String dateTime = sdf.format(argDate) + " " + argTime;
Date requiredDate = dateFormat.parse(dateTime);

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

How to compare dates in c#

If you have your dates in DateTime variables, they don't have a format.

You can use the Date property to return a DateTime value with the time portion set to midnight. So, if you have:

DateTime dt1 = DateTime.Parse("07/12/2011");
DateTime dt2 = DateTime.Now;

if(dt1.Date > dt2.Date)
{
     //It's a later date
}
else
{
     //It's an earlier or equal date
}

if (boolean == false) vs. if (!boolean)

Apart from "readability", no. They're functionally equivalent.

("Readability" is in quotes because I hate == false and find ! much more readable. But others don't.)

Use Font Awesome icon as CSS content

Update for Font Awesome 5 using SCSS

.icon {
  @extend %fa-icon;
  @extend .fas;

  &:before {
    content: fa-content($fa-var-user);
  }
}

How to remove the URL from the printing page?

I have a trick to remove it from the print page in Firefox. Use this:

<html moznomarginboxes mozdisallowselectionprint>

In the html tag you have to use moznomarginboxes mozdisallowselectionprint. I am sure it will help you a lot.

Has anyone gotten HTML emails working with Twitter Bootstrap?

Emails require tables in order to work properly.

Inky (by foundation for emails) is a templating language that converts simple HTML tags into the complex table HTML required for emails.

Example

<html>

<head></head>

<body>
  <table align="center" class="container">
    <tbody>
      <tr>
        <td>
          <table class="row">
            <tbody>
              <tr>
                <th class="small-12 large-12 columns first last">
                  <table>
                    <tbody>
                      <tr>
                        <th>Put content in me!</th>
                        <th class="expander"></th>
                      </tr>
                    </tbody>
                  </table>
                </th>
              </tr>
            </tbody>
          </table>&zwj;
        </td>
      </tr>
    </tbody>
  </table>
</body>

</html>

Will produce this:

enter image description here

Is the ternary operator faster than an "if" condition in Java

Ternary operators are just shorthand. They compile into the equivalent if-else statement, meaning they will be exactly the same.

How to place two forms on the same page?

You could make two forms with 2 different actions

<form action="login.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="submit" value="Login">
</form>

<br />

<form action="register.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="submit" value="Register">
</form>

Or do this

<form action="doStuff.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="hidden" name="action" value="login">
    <input type="submit" value="Login">
</form>

<br />

<form action="doStuff.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="hidden" name="action" value="register">
    <input type="submit" value="Register">
</form>

Then you PHP file would work as a switch($_POST['action']) ... furthermore, they can't click on both links at the same time or make a simultaneous request, each submit is a separate request.

Your PHP would then go on with the switch logic or have different php files doing a login procedure then a registration procedure

Install / upgrade gradle on Mac OS X

As mentioned in this tutorial, it's as simple as:

To install

brew install gradle

To upgrade

brew upgrade gradle

(using Homebrew of course)

Also see (finally) updated docs.

Cheers :)!

How to set auto increment primary key in PostgreSQL?

Try this command:

ALTER TABLE your_table ADD COLUMN key_column BIGSERIAL PRIMARY KEY;

Try it with the same DB-user as the one you have created the table.

How to increase heap size of an android application?

Use second process. Declare at AndroidManifest new Service with

android:process=":second"

Exchange between first and second process over BroadcastReceiver

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

this is my case

startActivityForResult(intent, PICK_IMAGE_REQUEST);

I defined two request code PICK_IMAGE_REQUESTand SCAN_BARCODE_REQUEST with the same value, eg.

static final int BARCODE_SCAN_REQUEST = 1;

static final int PICK_IMAGE_REQUEST = 1;

this could also causes the problem

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

yield from basically chains iterators in a efficient way:

# chain from itertools:
def chain(*iters):
    for it in iters:
        for item in it:
            yield item

# with the new keyword
def chain(*iters):
    for it in iters:
        yield from it

As you can see it removes one pure Python loop. That's pretty much all it does, but chaining iterators is a pretty common pattern in Python.

Threads are basically a feature that allow you to jump out of functions at completely random points and jump back into the state of another function. The thread supervisor does this very often, so the program appears to run all these functions at the same time. The problem is that the points are random, so you need to use locking to prevent the supervisor from stopping the function at a problematic point.

Generators are pretty similar to threads in this sense: They allow you to specify specific points (whenever they yield) where you can jump in and out. When used this way, generators are called coroutines.

Read this excellent tutorials about coroutines in Python for more details

How to link an image and target a new window

<a href="http://www.google.com" target="_blank"> //gives blank window
<img width="220" height="250" border="0" align="center"  src=""/> // show image into new window
</a>

See the code

How do I perform a Perl substitution on a string while keeping the original?

If you write Perl with use strict;, then you'll find that the one line syntax isn't valid, even when declared.

With:

my ($newstring = $oldstring) =~ s/foo/bar/;

You get:

Can't declare scalar assignment in "my" at script.pl line 7, near ") =~"
Execution of script.pl aborted due to compilation errors.

Instead, the syntax that you have been using, while a line longer, is the syntactically correct way to do it with use strict;. For me, using use strict; is just a habit now. I do it automatically. Everyone should.

#!/usr/bin/env perl -wT

use strict;

my $oldstring = "foo one foo two foo three";
my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;

print "$oldstring","\n";
print "$newstring","\n";

Free Rest API to retrieve current datetime as string (timezone irrelevant)

This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:

{
  "time": {
    "daysInMonth": 31,
    "millisecond": 283,
    "second": 42,
    "minute": 55,
    "hour": 1,
    "date": 6,
    "day": 3,
    "week": 10,
    "month": 2,
    "year": 2013,
    "zone": "+0000"
  },
  "formatted": {
    "weekday": "Wednesday",
    "month": "March",
    "ago": "a few seconds",
    "calendar": "Today at 1:55 AM",
    "generic": "2013-03-06T01:55:42+00:00",
    "time": "1:55 AM",
    "short": "03/06/2013",
    "slim": "3/6/2013",
    "hand": "Mar 6 2013",
    "handTime": "Mar 6 2013 1:55 AM",
    "longhand": "March 6 2013",
    "longhandTime": "March 6 2013 1:55 AM",
    "full": "Wednesday, March 6 2013 1:55 AM",
    "fullSlim": "Wed, Mar 6 2013 1:55 AM"
  },
  "array": [
    2013,
    2,
    6,
    1,
    55,
    42,
    283
  ],
  "offset": 1362534942283,
  "unix": 1362534942,
  "utc": "2013-03-06T01:55:42.283Z",
  "valid": true,
  "integer": false,
  "zone": 0
}

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

Your most elegant solution must be:

var left: Node? = null

fun show() {
    left?.also {
        queue.add( it )
    }
}

Then you don't have to define a new and unnecessary local variable, and you don't have any new assertions or casts (which are not DRY). Other scope functions could also work so choose your favourite.

How to change the current URL in javascript?

This is more robust:

mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');

When the URL has multiple numbers, it will change the last one:

http://mywebsite.com/8815/1.html

It supports numbers with leading zeros:

http://mywebsite.com/0001.html

Example

What's the function like sum() but for multiplication? product()?

Use this

def prod(iterable):
    p = 1
    for n in iterable:
        p *= n
    return p

Since there's no built-in prod function.

Java Enum return Int

Simply call the ordinal() method on an enum value, to retrieve its corresponding number. There's no need to declare an addition attribute with its value, each enumerated value gets its own number by default, assigned starting from zero, incrementing by one for each value in the same order they were declared.

You shouldn't depend on the int value of an enum, only on its actual value. Enums in Java are a different kind of monster and are not like enums in C, where you depend on their integer code.

Regarding the example you provided in the question, Font.PLAIN works because that's just an integer constant of the Font class. If you absolutely need a (possibly changing) numeric code, then an enum is not the right tool for the job, better stick to numeric constants.

how to use json file in html code

You can use JavaScript like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
        <script type="text/javascript" >
            function load() {
                var mydata = JSON.parse(data);
                alert(mydata.length);

                var div = document.getElementById('data');

                for(var i = 0;i < mydata.length; i++)
                {
                    div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                }
            }
        </script>
    </head>
    <body onload="load()">
        <div id="data">

        </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';

Converting time stamps in excel to dates

i got result from this in LibreOffice Calc :

=DATE(1970,1,1)+Column_id_here/60/60/24

How to find if div with specific id exists in jQuery?

Try to check the length of the selector, if it returns you something then the element must exists else not.

if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}


if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

Use the first if condition for id and the 2nd one for class.

Quickly create a large file on a Linux system

I don't know a whole lot about Linux, but here's the C Code I wrote to fake huge files on DC Share many years ago.

#include < stdio.h >
#include < stdlib.h >

int main() {
    int i;
    FILE *fp;

    fp=fopen("bigfakefile.txt","w");

    for(i=0;i<(1024*1024);i++) {
        fseek(fp,(1024*1024),SEEK_CUR);
        fprintf(fp,"C");
    }
}

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

Fragments onResume from back stack

If a fragment is put on backstack, Android simply destroys its view. The fragment instance itself is not killed. A simple way to start should to to listen to the onViewCreated event, an put you "onResume()" logic there.

boolean fragmentAlreadyLoaded = false;
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onViewCreated(view, savedInstanceState);

        if (savedInstanceState == null && !fragmentAlreadyLoaded) {
            fragmentAlreadyLoaded = true;

            // Code placed here will be executed once
        }

        //Code placed here will be executed even when the fragment comes from backstack
    }

How can I run PowerShell with the .NET 4 runtime?

Just as another option, the latest PoshConsole release includes binaries targeted to .NET 4 RC (which work fine against the RTM release) without any configuration.

Absolute and Flexbox in React Native

Ok, solved my problem, if anyone is passing by here is the answer:

Just had to add left: 0, and top: 0, to the styles, and yes, I'm tired.

position: 'absolute',
left:     0,
top:      0,

Test if a vector contains a given element

Both the match() (returns the first appearance) and %in% (returns a Boolean) functions are designed for this.

v <- c('a','b','c','e')

'b' %in% v
## returns TRUE

match('b',v)
## returns the first location of 'b', in this case: 2

How to check if a column exists before adding it to an existing table in PL/SQL?

All the metadata about the columns in Oracle Database is accessible using one of the following views.

user_tab_cols; -- For all tables owned by the user

all_tab_cols ; -- For all tables accessible to the user

dba_tab_cols; -- For all tables in the Database.

So, if you are looking for a column like ADD_TMS in SCOTT.EMP Table and add the column only if it does not exist, the PL/SQL Code would be along these lines..

DECLARE
  v_column_exists number := 0;  
BEGIN
  Select count(*) into v_column_exists
    from user_tab_cols
    where upper(column_name) = 'ADD_TMS'
      and upper(table_name) = 'EMP';
      --and owner = 'SCOTT --*might be required if you are using all/dba views

  if (v_column_exists = 0) then
      execute immediate 'alter table emp add (ADD_TMS date)';
  end if;
end;
/

If you are planning to run this as a script (not part of a procedure), the easiest way would be to include the alter command in the script and see the errors at the end of the script, assuming you have no Begin-End for the script..

If you have file1.sql

alter table t1 add col1 date;
alter table t1 add col2 date;
alter table t1 add col3 date;

And col2 is present,when the script is run, the other two columns would be added to the table and the log would show the error saying "col2" already exists, so you should be ok.

Count number of rows matching a criteria

to get the number of observations the number of rows from your Dataset would be more valid:

nrow(dat[dat$sCode == "CA",])

Where's my JSON data in my incoming Django request?

Using Angular you should add header to request or add it to module config headers: {'Content-Type': 'application/x-www-form-urlencoded'}

$http({
    url: url,
    method: method,
    timeout: timeout,
    data: data,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

remove objects from array by object property

You can remove an item by one of its properties without using any 3rd party libs like this:

var removeIndex = array.map(item => item.id)
                       .indexOf("abc");

~removeIndex && array.splice(removeIndex, 1);

Accessing nested JavaScript objects and arrays by string path

If you want a solution that can properly detect and report details of any issue with the path parsing, I wrote my own solution to this - library path-value.

const {resolveValue} = require('path-value');

resolveValue(someObject, 'part1.name'); //=> Part 1
resolveValue(someObject, 'part2.qty'); //=> 50
resolveValue(someObject, 'part3.0.name'); //=> Part 3A

Note that for indexes we use .0, and not [0], because parsing the latter adds a performance penalty, while .0 works directly in JavaScript, and is thus very fast.

However, there is support for full ES5 JavaScript syntax too. It just needs to be tokenized:

const {resolveValue, tokenizePath} = require('path-value');

const path = tokenizePath('part3[0].name');
//=> ['part3', '0', 'name']

resolveValue(someObject, path); //=> Part 3A

How to play a local video with Swift?

U can setup AVPlayer in another way, that open for u full customization of your video Player screen

Swift 2.3

  1. Create UIView subclass for playing video (basically u can use any UIView object and only needed is AVPlayerLayer. I setup in this way because it much clearer for me)

    import AVFoundation
    import UIKit
    
    class PlayerView: UIView {
    
    override class func layerClass() -> AnyClass {
        return AVPlayerLayer.self
    }
    
    var player:AVPlayer? {
        set {
            if let layer = layer as? AVPlayerLayer {
                layer.player = player
            }
        }
        get {
            if let layer = layer as? AVPlayerLayer {
                return layer.player
            } else {
                return nil
            }
        }
    }
    }
    
  2. Setup your player

    import AVFoundation
    import Foundation
    
    protocol VideoPlayerDelegate {
        func downloadedProgress(progress:Double)
        func readyToPlay()
        func didUpdateProgress(progress:Double)
        func didFinishPlayItem()
        func didFailPlayToEnd()
    }
    
    let videoContext:UnsafeMutablePointer<Void> = nil
    
    class VideoPlayer : NSObject {
    
        private var assetPlayer:AVPlayer?
        private var playerItem:AVPlayerItem?
        private var urlAsset:AVURLAsset?
        private var videoOutput:AVPlayerItemVideoOutput?
    
        private var assetDuration:Double = 0
        private var playerView:PlayerView?
    
        private var autoRepeatPlay:Bool = true
        private var autoPlay:Bool = true
    
        var delegate:VideoPlayerDelegate?
    
        var playerRate:Float = 1 {
            didSet {
                if let player = assetPlayer {
                    player.rate = playerRate > 0 ? playerRate : 0.0
                }
            }
        }
    
        var volume:Float = 1.0 {
            didSet {
                if let player = assetPlayer {
                    player.volume = volume > 0 ? volume : 0.0
                }
            }
        }
    
        // MARK: - Init
    
        convenience init(urlAsset:NSURL, view:PlayerView, startAutoPlay:Bool = true, repeatAfterEnd:Bool = true) {
            self.init()
    
            playerView = view
            autoPlay = startAutoPlay
            autoRepeatPlay = repeatAfterEnd
    
            if let playView = playerView, let playerLayer = playView.layer as? AVPlayerLayer {
                playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
            }
            initialSetupWithURL(urlAsset)
            prepareToPlay()
        }
    
        override init() {
            super.init()
        }
    
        // MARK: - Public
    
        func isPlaying() -> Bool {
            if let player = assetPlayer {
                return player.rate > 0
            } else {
                return false
            }
        }
    
        func seekToPosition(seconds:Float64) {
            if let player = assetPlayer {
                pause()
                if let timeScale = player.currentItem?.asset.duration.timescale {
                    player.seekToTime(CMTimeMakeWithSeconds(seconds, timeScale), completionHandler: { (complete) in
                        self.play()
                    })
                }
            }
        }
    
        func pause() {
            if let player = assetPlayer {
                player.pause()
            }
        }
    
        func play() {
            if let player = assetPlayer {
                if (player.currentItem?.status == .ReadyToPlay) {
                    player.play()
                    player.rate = playerRate
                }
            }
        }
    
        func cleanUp() {
            if let item = playerItem {
                item.removeObserver(self, forKeyPath: "status")
                item.removeObserver(self, forKeyPath: "loadedTimeRanges")
            }
            NSNotificationCenter.defaultCenter().removeObserver(self)
            assetPlayer = nil
            playerItem = nil
            urlAsset = nil
        }
    
        // MARK: - Private
    
        private func prepareToPlay() {
            let keys = ["tracks"]
            if let asset = urlAsset {
                asset.loadValuesAsynchronouslyForKeys(keys, completionHandler: {
                    dispatch_async(dispatch_get_main_queue(), {
                        self.startLoading()
                    })
                })
            }
        }
    
        private func startLoading(){
            var error:NSError?
            guard let asset = urlAsset else {return}
            let status:AVKeyValueStatus = asset.statusOfValueForKey("tracks", error: &error)
    
            if status == AVKeyValueStatus.Loaded {
                assetDuration = CMTimeGetSeconds(asset.duration)
    
                let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
                videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
                playerItem = AVPlayerItem(asset: asset)
    
                if let item = playerItem {
                    item.addObserver(self, forKeyPath: "status", options: .Initial, context: videoContext)
                    item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.New, .Old], context: videoContext)
    
                    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(playerItemDidReachEnd), name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
                    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didFailedToPlayToEnd), name: AVPlayerItemFailedToPlayToEndTimeNotification, object: nil)
    
                    if let output = videoOutput {
                        item.addOutput(output)
    
                        item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithmVarispeed
                        assetPlayer = AVPlayer(playerItem: item)
    
                        if let player = assetPlayer {
                            player.rate = playerRate
                        }
    
                        addPeriodicalObserver()
                        if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
                            layer.player = assetPlayer
                            print("player created")
                        }
                    }
                }
            }        
        }
    
        private func addPeriodicalObserver() {
            let timeInterval = CMTimeMake(1, 1)
    
            if let player = assetPlayer {
                player.addPeriodicTimeObserverForInterval(timeInterval, queue: dispatch_get_main_queue(), usingBlock: { (time) in
                    self.playerDidChangeTime(time)
                })
            }
        }
    
        private func playerDidChangeTime(time:CMTime) {
            if let player = assetPlayer {
                let timeNow = CMTimeGetSeconds(player.currentTime())
                let progress = timeNow / assetDuration
    
                delegate?.didUpdateProgress(progress)
            }
        }
    
        @objc private func playerItemDidReachEnd() {
            delegate?.didFinishPlayItem()
    
            if let player = assetPlayer {
                player.seekToTime(kCMTimeZero)
                if autoRepeatPlay == true {
                    play()
                }
            }
        }
    
        @objc private func didFailedToPlayToEnd() {
            delegate?.didFailPlayToEnd()
        }
    
        private func playerDidChangeStatus(status:AVPlayerStatus) {
            if status == .Failed {
                print("Failed to load video")
            } else if status == .ReadyToPlay, let player = assetPlayer {
                volume = player.volume
                delegate?.readyToPlay()
    
                if autoPlay == true && player.rate == 0.0 {
                    play()
                }
            }
        }
    
        private func moviewPlayerLoadedTimeRangeDidUpdated(ranges:Array<NSValue>) {
            var maximum:NSTimeInterval = 0
            for value in ranges {
                let range:CMTimeRange = value.CMTimeRangeValue
                let currentLoadedTimeRange = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration)
                if currentLoadedTimeRange > maximum {
                    maximum = currentLoadedTimeRange
                }
            }
            let progress:Double = assetDuration == 0 ? 0.0 : Double(maximum) / assetDuration
    
            delegate?.downloadedProgress(progress)
        }
    
        deinit {
            cleanUp()
        }
    
        private func initialSetupWithURL(url:NSURL) {
            let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
            urlAsset = AVURLAsset(URL: url, options: options)
        }
    
        // MARK: - Observations
    
        override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
            if context == videoContext {
                if let key = keyPath {
                    if key == "status", let player = assetPlayer {
                        playerDidChangeStatus(player.status)
                    } else if key == "loadedTimeRanges", let item = playerItem {
                        moviewPlayerLoadedTimeRangeDidUpdated(item.loadedTimeRanges)
                    }
                }
            }
        }
    
    }
    
  3. Usage:

assume u have view

@IBOutlet private weak var playerView: PlayerView!
private var videoPlayer:VideoPlayer?

and in viewDidLoad()

    private func preparePlayer() {
        if let filePath = NSBundle.mainBundle().pathForResource("intro", ofType: "m4v") {
            let fileURL = NSURL(fileURLWithPath: filePath)
            videoPlayer = VideoPlayer(urlAsset: fileURL, view: playerView)
            if let player = videoPlayer {
                player.playerRate = 0.67
            }
        }
    }

Objective-C

PlayerView.h

    #import <AVFoundation/AVFoundation.h>
    #import <UIKit/UIKit.h>

    /*!
     @class PlayerView
     @discussion Represent View for playinv video. Layer - PlayerLayer
     @availability iOS 7 and Up
     */
    @interface PlayerView : UIView

    /*!
     @var player
     @discussion Player object
     */
    @property (strong, nonatomic) AVPlayer *player;

    @end

PlayerView.m

    #import "PlayerView.h"

    @implementation PlayerView

    #pragma mark - LifeCycle

    + (Class)layerClass
    {
        return [AVPlayerLayer class];
    }

    #pragma mark - Setter/Getter

    - (AVPlayer*)player
    {
        return [(AVPlayerLayer *)[self layer] player];
    }

    - (void)setPlayer:(AVPlayer *)player
    {
        [(AVPlayerLayer *)[self layer] setPlayer:player];
    }

    @end

VideoPlayer.h

    #import <AVFoundation/AVFoundation.h>
    #import <UIKit/UIKit.h>
    #import "PlayerView.h"

    /*!
     @protocol VideoPlayerDelegate
     @discussion Events from VideoPlayer
     */
    @protocol VideoPlayerDelegate <NSObject>

    @optional

    /*!
     @brief Called whenever time when progress of played item changed
     @param progress
     Playing progress
     */
    - (void)progressDidUpdate:(CGFloat)progress;

    /*!
     @brief Called whenever downloaded item progress changed
     @param progress
     Playing progress
     */
    - (void)downloadingProgress:(CGFloat)progress;

    /*!
     @brief Called when playing time changed
     @param time
     Playing progress
     */
    - (void)progressTimeChanged:(CMTime)time;

    /*!
     @brief Called when player finish play item
    */
    - (void)playerDidPlayItem;

    /*!
     @brief Called when player ready to play item
     */
    - (void)isReadyToPlay;

    @end

    /*!
     @class VideoPlayer
     @discussion Video Player
     @code
         self.videoPlayer = [[VideoPlayer alloc] initVideoPlayerWithURL:someURL playerView:self.playerView];
         [self.videoPlayer prepareToPlay];
         self.videoPlayer.delegate = self; //optional

         //after when required play item
         [self.videoPlayer play];
     @endcode
     */
    @interface VideoPlayer : NSObject

    /*!
     @var delegate
     @abstract Delegate for VideoPlayer
     @discussion Set object to this property for getting response and notifications from this class
     */
    @property (weak, nonatomic) id <VideoPlayerDelegate> delegate;

    /*!
     @var volume
     @discussion volume of played asset
     */
    @property (assign, nonatomic) CGFloat volume;

    /*!
     @var autoRepeat
     @discussion indicate whenever player should repeat content on finish playing
     */
    @property (assign, nonatomic) BOOL autoRepeat;

    /*!
     @brief Create player with asset URL
     @param urlAsset
     Source URL
     @result
     instance of VideoPlayer
     */
    - (instancetype)initVideoPlayerWithURL:(NSURL *)urlAsset;

    /*!
     @brief Create player with asset URL and configure selected view for showing result
     @param urlAsset
     Source URL
     @param view
     View on wchich result will be showed
     @result
     instance of VideoPlayer
     */
    - (instancetype)initVideoPlayerWithURL:(NSURL *)urlAsset playerView:(PlayerView *)view;

    /*!
     @brief Call this method after creating player to prepare player to play
    */
    - (void)prepareToPlay;

    /*!
     @brief Play item
     */
    - (void)play;
    /*!
     @brief Pause item
     */
    - (void)pause;
    /*!
     @brief Stop item
     */
    - (void)stop;

    /*!
     @brief Seek required position in item and pla if rquired
     @param progressValue
     % of position to seek
     @param isPlaying
     YES if player should start to play item implicity
     */
    - (void)seekPositionAtProgress:(CGFloat)progressValue withPlayingStatus:(BOOL)isPlaying;

    /*!
     @brief Player state
     @result
     YES - if playing, NO if not playing
     */
    - (BOOL)isPlaying;

    /*!
     @brief Indicate whenever player can provide CVPixelBufferRef frame from item
     @result
     YES / NO
     */
    - (BOOL)canProvideFrame;

    /*!
     @brief CVPixelBufferRef frame from item
     @result
     CVPixelBufferRef frame
     */
    - (CVPixelBufferRef)getCurrentFramePicture;

    @end

VideoPlayer.m

    #import "VideoPlayer.h"

    typedef NS_ENUM(NSUInteger, InternalStatus) {
        InternalStatusPreparation,
        InternalStatusReadyToPlay,
    };

    static const NSString *ItemStatusContext;

    @interface VideoPlayer()

    @property (strong, nonatomic) AVPlayer *assetPlayer;
    @property (strong, nonatomic) AVPlayerItem *playerItem;
    @property (strong, nonatomic) AVURLAsset *urlAsset;
    @property (strong, atomic) AVPlayerItemVideoOutput *videoOutput;

    @property (assign, nonatomic) CGFloat assetDuration;
    @property (strong, nonatomic) PlayerView *playerView;

    @property (assign, nonatomic) InternalStatus status;

    @end

    @implementation VideoPlayer

    #pragma mark - LifeCycle

    - (instancetype)initVideoPlayerWithURL:(NSURL *)urlAsset
    {
        if (self = [super init]) {
            [self initialSetupWithURL:urlAsset];
        }
        return self;
    }

    - (instancetype)initVideoPlayerWithURL:(NSURL *)urlAsset playerView:(PlayerView *)view
    {
        if (self = [super init]) {
            ((AVPlayerLayer *)view.layer).videoGravity = AVLayerVideoGravityResizeAspectFill;
            [self initialSetupWithURL:urlAsset playerView:view];
        }
        return self;
    }

    #pragma mark - Public

    - (void)play
    {
        if ((self.assetPlayer.currentItem) && (self.assetPlayer.currentItem.status == AVPlayerItemStatusReadyToPlay)) {
            [self.assetPlayer play];
        }
    }

    - (void)pause
    {
        [self.assetPlayer pause];
    }

    - (void)seekPositionAtProgress:(CGFloat)progressValue withPlayingStatus:(BOOL)isPlaying
    {
        [self.assetPlayer pause];
        int32_t timeScale = self.assetPlayer.currentItem.asset.duration.timescale;

        __weak typeof(self) weakSelf = self;
        [self.assetPlayer seekToTime:CMTimeMakeWithSeconds(progressValue, timeScale) completionHandler:^(BOOL finished) {
            DLog(@"SEEK To time %f - success", progressValue);
            if (isPlaying && finished) {
                [weakSelf.assetPlayer play];
            }
        }];
    }

    - (void)setPlayerVolume:(CGFloat)volume
    {
        self.assetPlayer.volume = volume > .0 ? MAX(volume, 0.7) : 0.0f;
        [self.assetPlayer play];
    }

    - (void)setPlayerRate:(CGFloat)rate
    {
        self.assetPlayer.rate = rate > .0 ? rate : 0.0f;
    }

    - (void)stop
    {
        [self.assetPlayer seekToTime:kCMTimeZero];
        self.assetPlayer.rate =.0f;
    }

    - (BOOL)isPlaying
    {
        return self.assetPlayer.rate > 0 ? YES : NO;
    }

    #pragma mark - Private

    - (void)initialSetupWithURL:(NSURL *)url
    {
        self.status = InternalStatusPreparation;
        [self setupPlayerWithURL:url];
    }

    - (void)initialSetupWithURL:(NSURL *)url playerView:(PlayerView *)view
    {
        [self setupPlayerWithURL:url];
        self.playerView = view;
    }

    - (void)setupPlayerWithURL:(NSURL *)url
    {
        NSDictionary *assetOptions = @{ AVURLAssetPreferPreciseDurationAndTimingKey : @YES };
        self.urlAsset = [AVURLAsset URLAssetWithURL:url options:assetOptions];
    }

    - (void)prepareToPlay
    {
        NSArray *keys = @[@"tracks"];
        __weak VideoPlayer *weakSelf = self;
        [weakSelf.urlAsset loadValuesAsynchronouslyForKeys:keys completionHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf startLoading];
            });
        }];
    }

    - (void)startLoading
    {
        NSError *error;
        AVKeyValueStatus status = [self.urlAsset statusOfValueForKey:@"tracks" error:&error];
        if (status == AVKeyValueStatusLoaded) {
            self.assetDuration = CMTimeGetSeconds(self.urlAsset.duration);
            NSDictionary* videoOutputOptions = @{ (id)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)};
            self.videoOutput = [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:videoOutputOptions];
            self.playerItem = [AVPlayerItem playerItemWithAsset: self.urlAsset];

            [self.playerItem addObserver:self
                              forKeyPath:@"status"
                                 options:NSKeyValueObservingOptionInitial
                                 context:&ItemStatusContext];
            [self.playerItem addObserver:self
                              forKeyPath:@"loadedTimeRanges"
                                 options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
                                 context:&ItemStatusContext];
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(playerItemDidReachEnd:)
                                                         name:AVPlayerItemDidPlayToEndTimeNotification
                                                       object:self.playerItem];
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(didFailedToPlayToEnd)
                                                         name:AVPlayerItemFailedToPlayToEndTimeNotification
                                                       object:nil];

            [self.playerItem addOutput:self.videoOutput];
            self.assetPlayer = [AVPlayer playerWithPlayerItem:self.playerItem];
            [self addPeriodicalObserver];
            [((AVPlayerLayer *)self.playerView.layer) setPlayer:self.assetPlayer];
            DLog(@"Player created");
        } else {
            DLog(@"The asset's tracks were not loaded:\n%@", error.localizedDescription);
        }
    }

    #pragma mark - Observation

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        BOOL isOldKey = [change[NSKeyValueChangeNewKey] isEqual:change[NSKeyValueChangeOldKey]];

        if (!isOldKey) {
            if (context == &ItemStatusContext) {
                if ([keyPath isEqualToString:@"status"] && !self.status) {
                    if (self.assetPlayer.status == AVPlayerItemStatusReadyToPlay) {
                        self.status = InternalStatusReadyToPlay;
                    }
                    [self moviePlayerDidChangeStatus:self.assetPlayer.status];
                } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
                    [self moviewPlayerLoadedTimeRangeDidUpdated:self.playerItem.loadedTimeRanges];
                }
            }
        }
    }

    - (void)moviePlayerDidChangeStatus:(AVPlayerStatus)status
    {
        if (status == AVPlayerStatusFailed) {
            DLog(@"Failed to load video");
        } else if (status == AVPlayerItemStatusReadyToPlay) {
            DLog(@"Player ready to play");
            self.volume = self.assetPlayer.volume;

            if (self.delegate && [self.delegate respondsToSelector:@selector(isReadyToPlay)]) {
                [self.delegate isReadyToPlay];
            }
        }
    }

    - (void)moviewPlayerLoadedTimeRangeDidUpdated:(NSArray *)ranges
    {
        NSTimeInterval maximum = 0;

        for (NSValue *value in ranges) {
            CMTimeRange range;
            [value getValue:&range];
            NSTimeInterval currenLoadedRangeTime = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration);
            if (currenLoadedRangeTime > maximum) {
                maximum = currenLoadedRangeTime;
            }
        }
        CGFloat progress = (self.assetDuration == 0) ? 0 : maximum / self.assetDuration;
        if (self.delegate && [self.delegate respondsToSelector:@selector(downloadingProgress:)]) {
            [self.delegate downloadingProgress:progress];
        }
    }

    - (void)playerItemDidReachEnd:(NSNotification *)notification
    {
        if (self.delegate && [self.delegate respondsToSelector:@selector(playerDidPlayItem)]){
            [self.delegate playerDidPlayItem];
        }
        [self.assetPlayer seekToTime:kCMTimeZero];
        if (self.autoRepeat) {
            [self.assetPlayer play];
        }
    }

    - (void)didFailedToPlayToEnd
    {
        DLog(@"Failed play video to the end");
    }

    - (void)addPeriodicalObserver
    {
        CMTime interval = CMTimeMake(1, 1);
        __weak typeof(self) weakSelf = self;
        [self.assetPlayer addPeriodicTimeObserverForInterval:interval queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
            [weakSelf playerTimeDidChange:time];
        }];
    }

    - (void)playerTimeDidChange:(CMTime)time
    {
        double timeNow = CMTimeGetSeconds(self.assetPlayer.currentTime);
        if (self.delegate && [self.delegate respondsToSelector:@selector(progressDidUpdate:)]) {
            [self.delegate progressDidUpdate:(CGFloat) (timeNow / self.assetDuration)];
        }
    }

    #pragma mark - Notification

    - (void)setupAppNotification
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    }

    - (void)didEnterBackground
    {
        [self.assetPlayer pause];
    }

    - (void)willEnterForeground
    {
        [self.assetPlayer pause];
    }

    #pragma mark - GetImagesFromVideoPlayer

    - (BOOL)canProvideFrame
    {
        return self.assetPlayer.status == AVPlayerItemStatusReadyToPlay;
    }

    - (CVPixelBufferRef)getCurrentFramePicture
    {
        CMTime currentTime = [self.videoOutput itemTimeForHostTime:CACurrentMediaTime()];
        if (self.delegate && [self.delegate respondsToSelector:@selector(progressTimeChanged:)]) {
            [self.delegate progressTimeChanged:currentTime];
        }
        if (![self.videoOutput hasNewPixelBufferForItemTime:currentTime]) {
            return 0;
        }
        CVPixelBufferRef buffer = [self.videoOutput copyPixelBufferForItemTime:currentTime itemTimeForDisplay:NULL];

        return buffer;
    }

    #pragma mark - CleanUp

    - (void)removeObserversFromPlayer
    {
        @try {
            [self.playerItem removeObserver:self forKeyPath:@"status"];
            [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
            [[NSNotificationCenter defaultCenter] removeObserver:self];
            [[NSNotificationCenter defaultCenter] removeObserver:self.assetPlayer];        
        }
        @catch (NSException *ex) {
            DLog(@"Cant remove observer in Player - %@", ex.description);
        }
    }

    - (void)cleanUp
    {
        [self removeObserversFromPlayer];

        self.assetPlayer.rate = 0;
        self.assetPlayer = nil;
        self.playerItem = nil;
        self.urlAsset = nil;
    }

    - (void)dealloc
    {
        [self cleanUp];    
    }

    @end

Off cause resource (video file) should have target membership setted to your project

enter image description here

Additional - link to perfect Apple Developer guide

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

XML Carriage return encoding

xml:space="preserve" has to work for all compliant XML parsers.

However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br /> (X)HTML tag, maybe this is the problem which you are facing.

You can also add &#10; and/or &#13; to insert CR/LF characters.

How to validate phone number using PHP?

Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later

//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);

//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);

//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;

Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:

boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) { 
  //14: (###) ###-####
  //eliminate every char except 0-9
  str = str.replaceAll("[^0-9]", "");

  //remove leading 1 if it's there
  if (str.length() == 11) str = str.replaceAll("^1", "");

  isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));

Choice between vector::resize() and vector::reserve()

From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.

Take note that resize initialize the newly allocated vector where reserve just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'

You can refer to the documentation regarding the difference of resize and reserve

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

Android: Color To Int conversion

R.color.black or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454 which represents various primary colors

Merge DLL into EXE?

Download

ILMerge

Call

ilmerge /target:winexe /out:c:\output.exe c:\input.exe C:\input.dll

How to show Snackbar when Activity starts?

I have had trouble myself displaying Snackbar until now. Here is the simplest way to display a Snackbar. To display it as your Main Activity Starts, just put these two lines inside your OnCreate()

    Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Welcome To Main Activity", Snackbar.LENGTH_LONG);
    snackbar.show();

P.S. Just make sure you have imported the Android Design Support.(As mentioned in the question).

For Kotlin,

Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_SHORT).show()

HTML code for an apostrophe

Use &apos; for a straight apostrophe. This tends to be more readable than the numeric &#39; (if others are ever likely to read the HTML directly).

Edit: msanders points out that &apos; isn't valid HTML4, which I didn't know, so follow most other answers and use &#39;.

How do I measure separate CPU core usage for a process?

The ps solution was nearly what I needed and with some bash thrown in does exactly what the original question asked for: to see per-core usage of specific processes

This shows per-core usage of multi-threaded processes too.

Use like: cpustat `pgrep processname` `pgrep otherprocessname` ...

#!/bin/bash

pids=()
while [ $# != 0 ]; do
        pids=("${pids[@]}" "$1")
        shift
done

if [ -z "${pids[0]}" ]; then
        echo "Usage: $0 <pid1> [pid2] ..."
        exit 1
fi

for pid in "${pids[@]}"; do
        if [ ! -e /proc/$pid ]; then
                echo "Error: pid $pid doesn't exist"
                exit 1
        fi
done

while [ true ]; do
        echo -e "\033[H\033[J"
        for pid in "${pids[@]}"; do
                ps -p $pid -L -o pid,tid,psr,pcpu,comm=
        done
        sleep 1
done

Note: These stats are based on process lifetime, not the last X seconds, so you'll need to restart your process to reset the counter.

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

Stephen Nelsons' function converted to a prototype with lots of test examples.

I've also added whole strings to the function for completeness.

See code for additional comments.

_x000D_
_x000D_
/* Please note, there's no requirement to trim any leading or trailing white_x000D_
spaces. This will remove any digits in the whole string example returning the_x000D_
correct result. */_x000D_
_x000D_
String.prototype.isUpperCase = function(arg) {_x000D_
var re = new RegExp('\\s*\\d+\\s*', 'g');_x000D_
if (arg.wholeString) {return this.replace(re, '') == this.replace(re, '').toUpperCase()} else_x000D_
return !!this && this != this.toLocaleLowerCase();_x000D_
}_x000D_
_x000D_
console.log('\r\nString.prototype.isUpperCase, whole string examples');_x000D_
console.log(' DDD is ' + ' DDD'.isUpperCase( { wholeString:true } ));_x000D_
console.log('9 is ' + '9'.isUpperCase( { wholeString:true } ));_x000D_
console.log('Aa is ' + 'Aa'.isUpperCase( { wholeString:true } ));_x000D_
console.log('DDD 9 is ' + 'DDD 9'.isUpperCase( { wholeString:true } ));_x000D_
console.log('DDD is ' + 'DDD'.isUpperCase( { wholeString:true } ));_x000D_
console.log('Dll is ' + 'Dll'.isUpperCase( { wholeString:true } ));_x000D_
console.log('ll is ' + 'll'.isUpperCase( { wholeString:true } ));_x000D_
_x000D_
console.log('\r\nString.prototype.isUpperCase, non-whole string examples, will only string on a .charAt(n) basis. Defaults to the first character');_x000D_
console.log(' DDD is ' + ' DDD'.isUpperCase( { wholeString:false } ));_x000D_
console.log('9 is ' + '9'.isUpperCase( { wholeString:false } ));_x000D_
console.log('Aa is ' + 'Aa'.isUpperCase( { wholeString:false } ));_x000D_
console.log('DDD 9 is ' + 'DDD 9'.isUpperCase( { wholeString:false } ));_x000D_
console.log('DDD is ' + 'DDD'.isUpperCase( { wholeString:false } ));_x000D_
console.log('Dll is ' + 'Dll'.isUpperCase( { wholeString:false } ));_x000D_
console.log('ll is ' + 'll'.isUpperCase( { wholeString:false } ));_x000D_
_x000D_
console.log('\r\nString.prototype.isUpperCase, single character examples');_x000D_
console.log('BLUE CURAÇAO'.charAt(9) + ' is ' + 'BLUE CURAÇAO'.charAt(9).isUpperCase( { wholeString:false } ));_x000D_
console.log('9 is ' + '9'.isUpperCase( { wholeString:false } ));_x000D_
console.log('_ is ' + '_'.isUpperCase( { wholeString:false } ));_x000D_
console.log('A is ' + 'A'.isUpperCase( { wholeString:false } ));_x000D_
console.log('d is ' + 'd'.isUpperCase( { wholeString:false } ));_x000D_
console.log('E is ' + 'E'.isUpperCase( { wholeString:false } ));_x000D_
console.log('À is ' + 'À'.isUpperCase( { wholeString:false } ));_x000D_
console.log('É is ' + 'É'.isUpperCase( { wholeString:false } ));_x000D_
console.log('Ñ is ' + 'Ñ'.isUpperCase( { wholeString:false } ));_x000D_
console.log('ñ is ' + 'ñ'.isUpperCase( { wholeString:false } ));_x000D_
console.log('Þ is ' + 'Þ'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));
_x000D_
_x000D_
_x000D_

How do I check if there are duplicates in a flat list?

I thought it would be useful to compare the timings of the different solutions presented here. For this I used my own library simple_benchmark:

enter image description here

So indeed for this case the solution from Denis Otkidach is fastest.

Some of the approaches also exhibit a much steeper curve, these are the approaches that scale quadratic with the number of elements (Alex Martellis first solution, wjandrea and both of Xavier Decorets solutions). Also important to mention is that the pandas solution from Keiku has a very big constant factor. But for larger lists it almost catches up with the other solutions.

And in case the duplicate is at the first position. This is useful to see which solutions are short-circuiting:

enter image description here

Here several approaches don't short-circuit: Kaiku, Frank, Xavier_Decoret (first solution), Turn, Alex Martelli (first solution) and the approach presented by Denis Otkidach (which was fastest in the no-duplicate case).

I included a function from my own library here: iteration_utilities.all_distinct which can compete with the fastest solution in the no-duplicates case and performs in constant-time for the duplicate-at-begin case (although not as fastest).

The code for the benchmark:

from collections import Counter
from functools import reduce

import pandas as pd
from simple_benchmark import BenchmarkBuilder
from iteration_utilities import all_distinct

b = BenchmarkBuilder()

@b.add_function()
def Keiku(l):
    return pd.Series(l).duplicated().sum() > 0

@b.add_function()
def Frank(num_list):
    unique = []
    dupes = []
    for i in num_list:
        if i not in unique:
            unique.append(i)
        else:
            dupes.append(i)
    if len(dupes) != 0:
        return False
    else:
        return True

@b.add_function()
def wjandrea(iterable):
    seen = []
    for x in iterable:
        if x in seen:
            return True
        seen.append(x)
    return False

@b.add_function()
def user(iterable):
    clean_elements_set = set()
    clean_elements_set_add = clean_elements_set.add

    for possible_duplicate_element in iterable:

        if possible_duplicate_element in clean_elements_set:
            return True

        else:
            clean_elements_set_add( possible_duplicate_element )

    return False

@b.add_function()
def Turn(l):
    return Counter(l).most_common()[0][1] > 1

def getDupes(l):
    seen = set()
    seen_add = seen.add
    for x in l:
        if x in seen or seen_add(x):
            yield x

@b.add_function()          
def F1Rumors(l):
    try:
        if next(getDupes(l)): return True    # Found a dupe
    except StopIteration:
        pass
    return False

def decompose(a_list):
    return reduce(
        lambda u, o : (u[0].union([o]), u[1].union(u[0].intersection([o]))),
        a_list,
        (set(), set()))

@b.add_function()
def Xavier_Decoret_1(l):
    return not decompose(l)[1]

@b.add_function()
def Xavier_Decoret_2(l):
    try:
        def func(s, o):
            if o in s:
                raise Exception
            return s.union([o])
        reduce(func, l, set())
        return True
    except:
        return False

@b.add_function()
def pyrospade(xs):
    s = set()
    return any(x in s or s.add(x) for x in xs)

@b.add_function()
def Alex_Martelli_1(thelist):
    return any(thelist.count(x) > 1 for x in thelist)

@b.add_function()
def Alex_Martelli_2(thelist):
    seen = set()
    for x in thelist:
        if x in seen: return True
        seen.add(x)
    return False

@b.add_function()
def Denis_Otkidach(your_list):
    return len(your_list) != len(set(your_list))

@b.add_function()
def MSeifert04(l):
    return not all_distinct(l)

And for the arguments:


# No duplicate run
@b.add_arguments('list size')
def arguments():
    for exp in range(2, 14):
        size = 2**exp
        yield size, list(range(size))

# Duplicate at beginning run
@b.add_arguments('list size')
def arguments():
    for exp in range(2, 14):
        size = 2**exp
        yield size, [0, *list(range(size)]

# Running and plotting
r = b.run()
r.plot()

How can I create a simple message box in Python?

I had to add a message box to my existing program. Most of the answers are overly complicated in this instance. For Linux on Ubuntu 16.04 (Python 2.7.12) with future proofing for Ubuntu 20.04 here is my code:

Program top

from __future__ import print_function       # Must be first import

try:
    import tkinter as tk
    import tkinter.ttk as ttk
    import tkinter.font as font
    import tkinter.filedialog as filedialog
    import tkinter.messagebox as messagebox
    PYTHON_VER="3"
except ImportError: # Python 2
    import Tkinter as tk
    import ttk
    import tkFont as font
    import tkFileDialog as filedialog
    import tkMessageBox as messagebox
    PYTHON_VER="2"

Regardless of which Python version is being run, the code will always be messagebox. for future proofing or backwards compatibility. I only needed to insert two lines into my existing code above.

Message box using parent window geometry

''' At least one song must be selected '''
if self.play_song_count == 0:
    messagebox.showinfo(title="No Songs Selected", \
        message="You must select at least one song!", \
        parent=self.toplevel)
    return

I already had the code to return if song count was zero. So I only had to insert three lines in between existing code.

You can spare yourself complicated geometry code by using parent window reference instead:

parent=self.toplevel

Another advantage is if the parent window was moved after program startup your message box will still appear in the predictable place.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Another way

@Html.TextAreaFor(model => model.Comments[0].Comment)

And in your css do this

textarea
{
    font-family: inherit;
    width: 650px;
    height: 65px;
}

That DataType dealie allows carriage returns in the data, not everybody likes those.

deleting folder from java

If you use Apache Commons IO it's a one-liner:

FileUtils.deleteDirectory(dir);

See FileUtils.deleteDirectory()


Guava used to support similar functionality:

Files.deleteRecursively(dir);

This has been removed from Guava several releases ago.


While the above version is very simple, it is also pretty dangerous, as it makes a lot of assumptions without telling you. So while it may be safe in most cases, I prefer the "official way" to do it (since Java 7):

public static void deleteFileOrFolder(final Path path) throws IOException {
  Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
      throws IOException {
      Files.delete(file);
      return CONTINUE;
    }

    @Override public FileVisitResult visitFileFailed(final Path file, final IOException e) {
      return handleException(e);
    }

    private FileVisitResult handleException(final IOException e) {
      e.printStackTrace(); // replace with more robust error handling
      return TERMINATE;
    }

    @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException e)
      throws IOException {
      if(e!=null)return handleException(e);
      Files.delete(dir);
      return CONTINUE;
    }
  });
};

How to delete an SMS from the inbox in Android programmatically?

Also update the manifest file as to delete an sms you need write permissions.

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

How to get current domain name in ASP.NET

Try this:

@Request.Url.GetLeftPart(UriPartial.Authority)

What are the differences between Deferred, Promise and Future in JavaScript?

These answers, including the selected answer, are good for introducing promises conceptually, but lacking in specifics of what exactly the differences are in the terminology that arises when using libraries implementing them (and there are important differences).

Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):

  • Deferred: Never described in popular references, 1 2 3 4 but commonly used by implementations as the arbiter of promise resolution (implementing resolve and reject). 5 6 7

    Sometimes deferreds are also promises (implementing then), 5 6 other times it's seen as more pure to have the Deferred only capable of resolution, and forcing the user to access the promise for using then. 7

  • Promise: The most all-encompasing word for the strategy under discussion.

    A proxy object storing the result of a target function whose synchronicity we would like to abstract, plus exposing a then function accepting another target function and returning a new promise. 2

    Example from CommonJS:

    > asyncComputeTheAnswerToEverything()
        .then(addTwo)
        .then(printResult);
    44
    

     

    Always described in popular references, although never specified as to whose responsibility resolution falls to. 1 2 3 4

    Always present in popular implementations, and never given resolution abilites. 5 6 7

  • Future: a seemingly deprecated term found in some popular references 1 and at least one popular implementation, 8 but seemingly being phased out of discussion in preference for the term 'promise' 3 and not always mentioned in popular introductions to the topic. 9

    However, at least one library uses the term generically for abstracting synchronicity and error handling, while not providing then functionality. 10 It's unclear if avoiding the term 'promise' was intentional, but probably a good choice since promises are built around 'thenables.' 2

References

  1. Wikipedia on Promises & Futures
  2. Promises/A+ spec
  3. DOM Standard on Promises
  4. DOM Standard Promises Spec WIP
  5. DOJO Toolkit Deferreds
  6. jQuery Deferreds
  7. Q
  8. FutureJS
  9. Functional Javascript section on Promises
  10. Futures in AngularJS Integration Testing

Misc potentially confusing things

What is the `zero` value for time.Time in Go?

You should use the Time.IsZero() function instead:

func (Time) IsZero

func (t Time) IsZero() bool
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.

difference between @size(max = value ) and @min(value) @max(value)

From the documentation I get the impression that in your example it would be intended to use:

@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)

Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. Supported data types:

BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

Connection Java-MySql : Public Key Retrieval is not allowed

I solve this issue using below configuration on spring boot framework

spring.datasource.url=jdbc:mysql://localhost:3306/db-name?useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

Environment variable substitution in sed

You can use other characters besides "/" in substitution:

sed "s#$1#$2#g" -i FILE

Difference between Width:100% and width:100vw?

vw and vh stand for viewport width and viewport height respectively.

The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

Additional notes

Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.

You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

Recently I came across the same issue. I was able to ssh to my pi on my network, but not from outside my home network.

I had already:

  • installed and tested ssh on my home network.
  • Set a static IP for my pi.
  • Set up a Dynamic DNS service and installed the software on my pi. I referenced these instructions for setting up the static ip, and there are many more instructional resources out there.

Also, I set up port forward on my router for hosting a web site and I had even port forward port 22 to my pi's static IP for ssh, but I left the field blank where you specify the application you are performing the port forwarding for on the router. Anyway, I added 'ssh' into this field and, VOILA! A working ssh connection from anywhere to my pi.

I'll write out my router's port forwarding settings.

(ApplicationTextField)_ssh     (external port)_22     (Internal Port)_22     (Protocal)_Both     (To IP Address)_192.168.1.###     (Enabled)_checkBox

Port forwarding settings can be different for different routers though, so look up directions for your router.

Now, when I am outside of my home network I connect to my pi by typing:

ssh pi@[hostname]

Then I am able to input my password and connect.

Installing Apple's Network Link Conditioner Tool

Update on the answer December 2019 Xcode 11.1.2

Apple has moved Network Link Conditioner Tool to additional tools for Xcode

Go to the below link

https://developer.apple.com/download/more/?q=Additional%20Tools

enter image description here

Install the dmg file, select hardware from installer

enter image description here

select Network Link conditioner prefpane enter image description here

How to define two angular apps / modules in one page?

You can bootstrap multiple angular applications, but:

1) You need to manually bootstrap them

2) You should not use "document" as the root, but the node where the angular interface is contained to:

var todoRootNode = jQuery('[ng-controller=TodoController]');
angular.bootstrap(todoRootNode, ['TodoApp']);

This would be safe.

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

How to create JSON Object using String?

If you use the gson.JsonObject you can have something like that:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)

Bootstrap 3 truncate long text inside rows of a table in a responsive way

I did it this way (you need to add a class text to <td> and put the text between a <span>:

HTML

<td class="text"><span>looooooong teeeeeeeeext</span></td>

SASS

.table td.text {
    max-width: 177px;
    span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: inline-block;
        max-width: 100%;
    }
}

CSS equivalent

.table td.text {
    max-width: 177px;
}
.table td.text span {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
    max-width: 100%;
}

And it will still be mobile responsive (forget it with layout=fixed) and will keep the original behaviour.

PS: Of course 177px is a custom size (put whatever you need).

Wordpress plugin install: Could not create directory

The user that is running your web server does not have permissions to write to the directory that Wordpress is intending to create the plugin directory in. You should chown the directory in question to the user that is running Wordpress. It is most likely not root.

In short, this is a permissions issue. Your touch command is working because you're using it as root, and root has global permissions to write wherever it wants.

How to print binary number via printf

Although ANSI C does not have this mechanism, it is possible to use itoa() as a shortcut:

  char buffer [33];
  itoa (i,buffer,2);
  printf ("binary: %s\n",buffer);

Here's the origin:

itoa in cplusplus reference

It is non-standard C, but K&R mentioned the implementation in the C book, so it should be quite common. It should be in stdlib.h.

Saving ssh key fails

If you're using Windows, the unix-style default path of ssh-keygen is at fault.

In Line 2 it says Enter file in which to save the key (/c/Users/Eva/.ssh/id_rsa):. That full filename in the parantheses is the default, obviously Windows cannot access a file like that. If you type the Windows equivalent (c:\Users\Eva\.ssh\id_rsa), it should work.

Before running this, you also need to create the folder. You can do this by running mkdir c:\Users\Eva\.ssh, or by created the folder ".ssh." from File Explorer (note the second dot at the end, which will get removed automatically, and is required to create a folder that has a dot at the beginning).

c:\Users\Administrator\.ssh>ssh-keygen -t rsa -C "[email protected]"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/Administrator/.ssh/id_rsa): C:\Users\Administrator\.ssh\id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\Administrator\.ssh\id_rsa.
Your public key has been saved in C:\Users\Administrator\.ssh\id_rsa.pub.
The key fingerprint is:
... [email protected]
The key's randomart image is:...`

I know this is an old thread, but I thought the answer might help others.

How do I make an HTML text box show a hint when empty?

Use a background image to render the text:

 input.foo { }
 input.fooempty { background-image: url("blah.png"); }

Then all you have to do is detect value == 0 and apply the right class:

 <input class="foo fooempty" value="" type="text" name="bar" />

And the jQuery JavaScript code looks like this:

jQuery(function($)
{
    var target = $("input.foo");
    target.bind("change", function()
    {
        if( target.val().length > 1 )
        {
            target.addClass("fooempty");
        }
        else
        {
            target.removeClass("fooempty");
        }
    });
});

How to display tables on mobile using Bootstrap?

After researching for almost 1 month i found the below code which is working very beautifully and 100% perfectly on my website. To check the preview how it is working you can check from the link. https://www.jobsedit.in/state-government-jobs/

CSS CODE-----

@media only screen and (max-width: 500px)  {
    .resp table  { 
        display: block ; 
    }   
    .resp th  { 
        position: absolute;
        top: -9999px;
        left: -9999px;
        display:block ;
    }   
     .resp tr { 
    border: 1px solid #ccc;
    display:block;
    }   
    .resp td  { 
        /* Behave  like a "row" */
        border: none;
        border-bottom: 1px solid #eee; 
        position: relative;
        width:100%;
        background-color:White;
        text-indent: 50%; 
        text-align:left;
        padding-left: 0px;
        display:block;      
    }
    .resp  td:nth-child(1)  {
        border: none;
        border-bottom: 1px solid #eee; 
        position: relative;
        font-size:20px;
        text-indent: 0%;
        text-align:center;
}   
    .resp td:before  { 
        /* Now like a table header */
        position: absolute;
        /* Top/left values mimic padding */
        top: 6px;
        left: 6px;
        width: 45%; 
        text-indent: 0%;
        text-align:left;
        white-space: nowrap;
        background-color:White;
        font-weight:bold;
    }
    /*
    Label the data
    */
    .resp td:nth-of-type(2):before  { content: attr(data-th) }
    .resp td:nth-of-type(3):before  { content: attr(data-th) }
    .resp td:nth-of-type(4):before  { content: attr(data-th) }
    .resp td:nth-of-type(5):before  { content: attr(data-th) }
    .resp td:nth-of-type(6):before  { content: attr(data-th) }
    .resp td:nth-of-type(7):before  { content: attr(data-th) }
    .resp td:nth-of-type(8):before  { content: attr(data-th) }
    .resp td:nth-of-type(9):before  { content: attr(data-th) }
    .resp td:nth-of-type(10):before  { content: attr(data-th) }
}

HTML CODE --

<table>
<tr>
<td data-th="Heading 1"></td>
<td data-th="Heading 2"></td>
<td data-th="Heading 3"></td>
<td data-th="Heading 4"></td>
<td data-th="Heading 5"></td>
</tr>
</table>

How can I retrieve a table from stored procedure to a datatable?

string connString = "<your connection string>";
string sql = "name of your sp";

using(SqlConnection conn = new SqlConnection(connString)) 
{
    try 
    {
        using(SqlDataAdapter da = new SqlDataAdapter()) 
        {
            da.SelectCommand = new SqlCommand(sql, conn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            DataSet ds = new DataSet();   
            da.Fill(ds, "result_name");

            DataTable dt = ds.Tables["result_name"];

            foreach (DataRow row in dt.Rows) {
                //manipulate your data
            }
        }    
    } 
    catch(SQLException ex) 
    {
        Console.WriteLine("SQL Error: " + ex.Message);
    }
    catch(Exception e) 
    {
        Console.WriteLine("Error: " + e.Message);
    }
}

Modified from Java Schools Example

Run a single test method with maven

There is an issue with surefire 2.12. This is what happen to me changing maven-surefire-plugin from 2.12 to 2.11:

  1. mvn test -Dtest=DesignRulesTest

    Result:
    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project pmd: No tests were executed!

  2. mvn test -Dtest=DesignRulesTest

    Result: [INFO] --- maven-surefire-plugin:2.11:test (default-test) @ pmd --- ... Running net.sourceforge.pmd.lang.java.rule.design.DesignRulesTest Tests run: 5, Failures: 0, Errors: 0, Skipped: 4, Time elapsed: 4.009 sec

Understanding colors on Android (six characters)

On Android the color can be declared in the following format

#AARRGGBB

AA - is the bit that’s of most interest to us, it stands for alpha channel

RR GG BB - red, green & blue channels respectively

Now in order to add transparency to our color we need to prepend it with hexadecimal value representing the alpha (transparency).

For example if you want to set 80% transparency value to black color (#000000) you need to prepend it with CC, as a result we end up with the following color resource #CC000000.

You can read about it in more detail on my blog https://androidexplained.github.io/android/ui/2020/10/12/hex-color-code-transparency.html

Javascript Array.sort implementation?

There is no draft requirement for JS to use a specific sorting algorthim. As many have mentioned here, Mozilla uses merge sort.However, In Chrome's v8 source code, as of today, it uses QuickSort and InsertionSort, for smaller arrays.

V8 Engine Source

From Lines 807 - 891

  var QuickSort = function QuickSort(a, from, to) {
    var third_index = 0;
    while (true) {
      // Insertion sort is faster for short arrays.
      if (to - from <= 10) {
        InsertionSort(a, from, to);
        return;
      }
      if (to - from > 1000) {
        third_index = GetThirdIndex(a, from, to);
      } else {
        third_index = from + ((to - from) >> 1);
      }
      // Find a pivot as the median of first, last and middle element.
      var v0 = a[from];
      var v1 = a[to - 1];
      var v2 = a[third_index];
      var c01 = comparefn(v0, v1);
      if (c01 > 0) {
        // v1 < v0, so swap them.
        var tmp = v0;
        v0 = v1;
        v1 = tmp;
      } // v0 <= v1.
      var c02 = comparefn(v0, v2);
      if (c02 >= 0) {
        // v2 <= v0 <= v1.
        var tmp = v0;
        v0 = v2;
        v2 = v1;
        v1 = tmp;
      } else {
        // v0 <= v1 && v0 < v2
        var c12 = comparefn(v1, v2);
        if (c12 > 0) {
          // v0 <= v2 < v1
          var tmp = v1;
          v1 = v2;
          v2 = tmp;
        }
      }
      // v0 <= v1 <= v2
      a[from] = v0;
      a[to - 1] = v2;
      var pivot = v1;
      var low_end = from + 1;   // Upper bound of elements lower than pivot.
      var high_start = to - 1;  // Lower bound of elements greater than pivot.
      a[third_index] = a[low_end];
      a[low_end] = pivot;

      // From low_end to i are elements equal to pivot.
      // From i to high_start are elements that haven't been compared yet.
      partition: for (var i = low_end + 1; i < high_start; i++) {
        var element = a[i];
        var order = comparefn(element, pivot);
        if (order < 0) {
          a[i] = a[low_end];
          a[low_end] = element;
          low_end++;
        } else if (order > 0) {
          do {
            high_start--;
            if (high_start == i) break partition;
            var top_elem = a[high_start];
            order = comparefn(top_elem, pivot);
          } while (order > 0);
          a[i] = a[high_start];
          a[high_start] = element;
          if (order < 0) {
            element = a[i];
            a[i] = a[low_end];
            a[low_end] = element;
            low_end++;
          }
        }
      }
      if (to - high_start < low_end - from) {
        QuickSort(a, high_start, to);
        to = low_end;
      } else {
        QuickSort(a, from, low_end);
        from = high_start;
      }
    }
  };

Update As of 2018 V8 uses TimSort, thanks @celwell. Source

RegExp matching string not starting with my

Wouldn't it be significantly more readable to do a positive match and reject those strings - rather than match the negative to find strings to accept?

/^my/

Scroll Automatically to the Bottom of the Page

You can use this to go down the page in an animation format.

$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");

Python dictionary get multiple values

I think list comprehension is one of the cleanest ways that doesn't need any additional imports:

>>> d={"foo": 1, "bar": 2, "baz": 3}
>>> a = [d.get(k) for k in ["foo", "bar", "baz"]]
>>> a
[1, 2, 3]

Of if you want the values as individual variables then use multiple-assignment:

>>> a,b,c = [d.get(k) for k in ["foo", "bar", "baz"]]
>>> a,b,c
(1, 2, 3)

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

How do you write a migration to rename an ActiveRecord model and its table in Rails?

Here's an example:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

I had to go and rename the model declaration file manually.

Edit:

In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

(You still have to go through and manually rename your files.)

Split value from one field to two

It seems that existing responses are over complicated or not a strict answer to the particular question.

I think, the simple answer is the following query:

SELECT
    SUBSTRING_INDEX(`membername`, ' ', 1) AS `memberfirst`,
    SUBSTRING_INDEX(`membername`, ' ', -1) AS `memberlast`
;

I think it is not necessary to deal with more-than-two-word names in this particular situation. If you want to do it properly, splitting can be very hard or even impossible in some cases:

  • Johann Sebastian Bach
  • Johann Wolfgang von Goethe
  • Edgar Allan Poe
  • Jakob Ludwig Felix Mendelssohn-Bartholdy
  • Petofi Sándor
  • ?? ?

In a properly designed database, human names should be stored both in parts and in whole. This is not always possible, of course.

MySQL - Make an existing Field Unique

The easiest and fastest way would be with phpmyadmin structure table.

USE PHPMYADMIN ADMIN PANEL!

There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.

Good tool to visualise database schema?

Years ago, I used to use Data Architect. I don't know if it's still out there.

You could reverse engineer an existing schema into a relational table diagram.

Or you could go even further, and reverse engineer an Entity-Relationship model with an accompanying diagram. ER diagrams were really useful to me when discussing the data with people who were neither programmers nor database experts.

Sometimes a few manual fixups to the ER model and ER diagram were necessary before it was a useful communication tool with stakeholders.

Find all files in a directory with extension .txt in Python

Functional solution with sub-directories:

from fnmatch import filter
from functools import partial
from itertools import chain
from os import path, walk

print(*chain(*(map(partial(path.join, root), filter(filenames, "*.txt")) for root, _, filenames in walk("mydir"))))

Setting up and using Meld as your git difftool and mergetool

I prefer to setup meld as a separate command, like so:

git config --global alias.meld '!git difftool -t meld --dir-diff'

This makes it similar to the git-meld.pl script here: https://github.com/wmanley/git-meld

You can then just run

git meld

How do Python functions handle the types of the parameters that you pass in?

Python is not strongly typed in the sense of static or compile-time type checking.

Most Python code falls under so-called "Duck Typing" -- for example, you look for a method read on an object -- you don't care if the object is a file on disk or a socket, you just want to read N bytes from it.

What's the correct way to convert bytes to a hex string in Python 3?

Python has bytes-to-bytes standard codecs that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. In Python 2, you could do:

b'foo'.encode('hex')

In Python 3, str.encode / bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):

import codecs
codecs.getencoder('hex')(b'foo')[0]

Starting with Python 3.4, there is a less awkward option:

codecs.encode(b'foo', 'hex')

These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control.

Remove All Event Listeners of Specific Type

You must override EventTarget.prototype.addEventListener to build an trap function for logging all 'add listener' calls. Something like this:

var _listeners = [];

EventTarget.prototype.addEventListenerBase = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(type, listener)
{
    _listeners.push({target: this, type: type, listener: listener});
    this.addEventListenerBase(type, listener);
};

Then you can build an EventTarget.prototype.removeEventListeners:

EventTarget.prototype.removeEventListeners = function(targetType)
{
    for(var index = 0; index != _listeners.length; index++)
    {
        var item = _listeners[index];

        var target = item.target;
        var type = item.type;
        var listener = item.listener;

        if(target == this && type == targetType)
        {
            this.removeEventListener(type, listener);
        }
    }
}

In ES6 you can use a Symbol, to hide the original function and the list of all added listener directly in the instantiated object self.

(function()
{
    let target = EventTarget.prototype;
    let functionName = 'addEventListener';
    let func = target[functionName];

    let symbolHidden = Symbol('hidden');

    function hidden(instance)
    {
        if(instance[symbolHidden] === undefined)
        {
            let area = {};
            instance[symbolHidden] = area;
            return area;
        }

        return instance[symbolHidden];
    }

    function listenersFrom(instance)
    {
        let area = hidden(instance);
        if(!area.listeners) { area.listeners = []; }
        return area.listeners;
    }

    target[functionName] = function(type, listener)
    {
        let listeners = listenersFrom(this);

        listeners.push({ type, listener });

        func.apply(this, [type, listener]);
    };

    target['removeEventListeners'] = function(targetType)
    {
        let self = this;

        let listeners = listenersFrom(this);
        let removed = [];

        listeners.forEach(item =>
        {
            let type = item.type;
            let listener = item.listener;

            if(type == targetType)
            {
                self.removeEventListener(type, listener);
            }
        });
    };
})();

You can test this code with this little snipper:

document.addEventListener("DOMContentLoaded", event => { console.log('event 1'); });
document.addEventListener("DOMContentLoaded", event => { console.log('event 2'); });
document.addEventListener("click", event => { console.log('click event'); });

document.dispatchEvent(new Event('DOMContentLoaded'));
document.removeEventListeners('DOMContentLoaded');
document.dispatchEvent(new Event('DOMContentLoaded'));
// click event still works, just do a click in the browser

running php script (php function) in linux bash

Simply this should do:

php test.php

SQL grouping by all the columns

No because this fundamentally means that you will not be grouping anything. If you group by all columns (and have a properly defined table w/ a unique index) then SELECT * FROM table is essentially the same thing as SELECT * FROM table GROUP BY *.

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

Can I use an HTML input type "date" to collect only a year?

You can do the following:

  1. Generate an Array of the years I'll be accepting,
  2. Use a select box.
  3. Use each item from your Array as an 'option' tag.

Example using PHP (you can do this in any language of your choice):

Server:

<?php $years = range(1900, strftime("%Y", time())); ?>

HTML

<select>
  <option>Select Year</option>
  <?php foreach($years as $year) : ?>
    <option value="<?php echo $year; ?>"><?php echo $year; ?></option>
  <?php endforeach; ?>
</select>

As an added benefit, this works has a browser compatibility of a 100% ;-)

Using crontab to execute script every minute and another every 24 hours

every minute:

* * * * * /path/to/php /var/www/html/a.php

every 24hours (every midnight):

0 0 * * * /path/to/php /var/www/html/reset.php

See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

Get last 30 day records from today date in SQL Server

you can use this to get the data of the last 30 days based on a column.

WHERE DATEDIFF(dateColumn,CURRENT_TIMESTAMP) BETWEEN 0 AND 30

How do I find which transaction is causing a "Waiting for table metadata lock" state?

SHOW ENGINE INNODB STATUS \G

Look for the Section -

TRANSACTIONS

We can use INFORMATION_SCHEMA Tables.

Useful Queries

To check about all the locks transactions are waiting for:

USE INFORMATION_SCHEMA;
SELECT * FROM INNODB_LOCK_WAITS;

A list of blocking transactions:

SELECT * 
FROM INNODB_LOCKS 
WHERE LOCK_TRX_ID IN (SELECT BLOCKING_TRX_ID FROM INNODB_LOCK_WAITS);

OR

SELECT INNODB_LOCKS.* 
FROM INNODB_LOCKS
JOIN INNODB_LOCK_WAITS
  ON (INNODB_LOCKS.LOCK_TRX_ID = INNODB_LOCK_WAITS.BLOCKING_TRX_ID);

A List of locks on particular table:

SELECT * FROM INNODB_LOCKS 
WHERE LOCK_TABLE = db_name.table_name;

A list of transactions waiting for locks:

SELECT TRX_ID, TRX_REQUESTED_LOCK_ID, TRX_MYSQL_THREAD_ID, TRX_QUERY
FROM INNODB_TRX
WHERE TRX_STATE = 'LOCK WAIT';

Reference - MySQL Troubleshooting: What To Do When Queries Don't Work, Chapter 6 - Page 96.

Display string as html in asp.net mvc view

You should be using IHtmlString instead:

IHtmlString str = new HtmlString("<a href="/Home/Profile/seeker">seeker</a> has applied to <a href="/Jobs/Details/9">Job</a> floated by you.</br>");

Whenever you have model properties or variables that need to hold HTML, I feel this is generally a better practice. First of all, it is a bit cleaner. For example:

@Html.Raw(str)

Compared to:

@str

Also, I also think it's a bit safer vs. using @Html.Raw(), as the concern of whether your data is HTML is kept in your controller. In an environment where you have front-end vs. back-end developers, your back-end developers may be more in tune with what data can hold HTML values, thus keeping this concern in the back-end (controller).

I generally try to avoid using Html.Raw() whenever possible.

One other thing worth noting, is I'm not sure where you're assigning str, but a few things that concern me with how you may be implementing this.

First, this should be done in a controller, regardless of your solution (IHtmlString or Html.Raw). You should avoid any logic like this in your view, as it doesn't really belong there.

Additionally, you should be using your ViewModel for getting values to your view (and again, ideally using IHtmlString as the property type). Seeing something like @Html.Encode(str) is a little concerning, unless you were doing this just to simplify your example.

Plot two histograms on single chart with matplotlib

Inspired by Solomon's answer, but to stick with the question, which is related to histogram, a clean solution is:

sns.distplot(bar)
sns.distplot(foo)
plt.show()

Make sure to plot the taller one first, otherwise you would need to set plt.ylim(0,0.45) so that the taller histogram is not chopped off.

How to manually deploy artifacts in Nexus Repository Manager OSS 3

My team use Gradle and Nexus OSS 3.5.2,

I have found a solution: upload artyfacts from locakhost (I checked Nexus documentation and did not found anything about uploading artifacts from folders) => I have shared directory (use Apache httpd) and connected one to created new Nexus proxy repository. Now when I want to add my own artifacts I can upload ones into shared directory in my remote server.

Maybe someone find my solution useful: enter image description here

My question is here: Is it possible to deploy artifacts from local folder in Sonatype Nexus Repository Manager 3.x

SQL Server: Filter output of sp_who2

I made an improvement in order to obtain not only the blocked processes but also the blocking process:

DECLARE @Table TABLE
    (
    SPID INT, Status VARCHAR(MAX), LOGIN VARCHAR(MAX), HostName VARCHAR(MAX), BlkBy VARCHAR(MAX), DBName VARCHAR(MAX), Command VARCHAR(MAX), CPUTime INT, DiskIO INT, LastBatch VARCHAR(MAX), ProgramName VARCHAR(MAX), SPID_1 INT, REQUESTID INT
    )

INSERT INTO @Table EXEC sp_who2

SELECT  *
FROM    @Table
WHERE
    BlkBy not like '  .'
    or
    SPID in (SELECT  BlkBy from @Table where BlkBy not like '  .')

delete from @Table

Turn off textarea resizing

this will do your job

  textarea{
        resize:none;
    }

enter image description here

make an html svg object also a clickable link

The easiest way is to not use <object>. Instead use an <img> tag and the anchor should work just fine.

What is size_t in C?

If you are the empirical type,

echo | gcc -E -xc -include 'stddef.h' - | grep size_t

Output for Ubuntu 14.04 64-bit GCC 4.8:

typedef long unsigned int size_t;

Note that stddef.h is provided by GCC and not glibc under src/gcc/ginclude/stddef.h in GCC 4.2.

Interesting C99 appearances

  • malloc takes size_t as an argument, so it determines the maximum size that may be allocated.

    And since it is also returned by sizeof, I think it limits the maximum size of any array.

    See also: What is the maximum size of an array in C?

How to navigate to a directory in C:\ with Cygwin?

cd c: is supported now in cygwin

ResultSet exception - before start of result set

Basically you are positioning the cursor before the first row and then requesting data. You need to move the cursor to the first row.

 result.next();
 String foundType = result.getString(1);

It is common to do this in an if statement or loop.

if(result.next()){
   foundType = result.getString(1);
}

How to write an inline IF statement in JavaScript?

You can also approximate an if/else using only Logical Operators.

(a && b) || c

The above is roughly the same as saying:

a ? b : c

And of course, roughly the same as:

if ( a ) { b } else { c }

I say roughly because there is one difference with this approach, in that you have to know that the value of b will evaluate as true, otherwise you will always get c. Bascially you have to realise that the part that would appear if () { here } is now part of the condition that you place if ( here ) { }.

The above is possible due to JavaScripts behaviour of passing / returning one of the original values that formed the logical expression, which one depends on the type of operator. Certain other languages, like PHP, carry on the actual result of the operation i.e. true or false, meaning the result is always true or false; e.g:

14 && 0          /// results as 0,  not false
14 || 0          /// results as 14, not true
1 && 2 && 3 && 4 /// results as 4,  not true
true && ''       /// results as ''
{} || '0'        /// results as {}

One main benefit, compared with a normal if statement, is that the first two methods can operate on the righthand-side of an argument i.e. as part of an assignment.

d = (a && b) || c;
d = a ? b : c;

if `a == true` then `d = b` else `d = c`

The only way to achieve this with a standard if statement would be to duplicate the assigment:

if ( a ) { d = b } else { d = c }

You may ask why use just Logical Operators instead of the Ternary Operator, for simple cases you probably wouldn't, unless you wanted to make sure a and b were both true. You can also achieve more streamlined complex conditions with the Logical operators, which can get quite messy using nested ternary operations... then again if you want your code to be easily readable, neither are really that intuative.

How can I uninstall an application using PowerShell?

To fix up the second method in Jeff Hillman's post, you could either do a:

$app = Get-WmiObject 
            -Query "SELECT * FROM Win32_Product WHERE Name = 'Software Name'"

Or

$app = Get-WmiObject -Class Win32_Product `
                     -Filter "Name = 'Software Name'"

Get request URL in JSP which is forwarded by Servlet

None of these attributes are reliable because per the servlet spec (2.4, 2.5 and 3.0), these attributes are overridden if you include/forward a second time (or if someone calls getNamedDispatcher). I think the only reliable way to get the original request URI/query string is to stick a filter at the beginning of your filter chain in web.xml that sets your own custom request attributes based on request.getRequestURI()/getQueryString() before any forwards/includes take place.

http://www.caucho.com/resin-3.0/webapp/faq.xtp contains an excellent summary of how this works (minus the technical note that a second forward/include messes up your ability to use these attributes).

Firing events on CSS class changes in jQuery

var timeout_check_change_class;

function check_change_class( selector )
{
    $(selector).each(function(index, el) {
        var data_old_class = $(el).attr('data-old-class');
        if (typeof data_old_class !== typeof undefined && data_old_class !== false) 
        {

            if( data_old_class != $(el).attr('class') )
            {
                $(el).trigger('change_class');
            }
        }

        $(el).attr('data-old-class', $(el).attr('class') );

    });

    clearTimeout( timeout_check_change_class );
    timeout_check_change_class = setTimeout(check_change_class, 10, selector);
}
check_change_class( '.breakpoint' );


$('.breakpoint').on('change_class', function(event) {
    console.log('haschange');
});

"Could not find bundler" error

According to this answer to a similar question, it should be enough:

rvmsudo gem install bundler.

Cheers

JNI and Gradle in Android Studio

In the module build.gradle, in the task field, I get an error unless I use:

def ndkDir = plugins.getPlugin('com.android.application').sdkHandler.getNdkFolder()

I see people using

def ndkDir = android.plugin.ndkFolder

and

def ndkDir = plugins.getPlugin('com.android.library').sdkHandler.getNdkFolder()

but neither of those worked until I changed it to the plugin I was actually importing.

How do you copy and paste into Git Bash

enter image description here

In windows after this setting you can use ctrl + shift + v ( for windows)

How to access parent Iframe from JavaScript

Simply call window.frameElement from your framed page. If the page is not in a frame then frameElement will be null.

The other way (getting the window element inside a frame is less trivial) but for sake of completeness:

/**
 * @param f, iframe or frame element
 * @return Window object inside the given frame
 * @effect will append f to document.body if f not yet part of the DOM
 * @see Window.frameElement
 * @usage myFrame.document = getFramedWindow(myFrame).document;
 */
function getFramedWindow(f)
{
    if(f.parentNode == null)
        f = document.body.appendChild(f);
    var w = (f.contentWindow || f.contentDocument);
    if(w && w.nodeType && w.nodeType==9)
        w = (w.defaultView || w.parentWindow);
    return w;
}

matplotlib colorbar for scatter

If you're looking to scatter by two variables and color by the third, Altair can be a great choice.

Creating the dataset

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])

Altair plot

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)

Plot

enter image description here

Wildcard string comparison in Javascript

You should use RegExp (they are awesome) an easy solution is:

if( /^bird/.test(animals[i]) ){
    // a bird :D
}

HTML5 Pre-resize images before uploading

Typescript

async resizeImg(file: Blob): Promise<Blob> {
    let img = document.createElement("img");
    img.src = await new Promise<any>(resolve => {
        let reader = new FileReader();
        reader.onload = (e: any) => resolve(e.target.result);
        reader.readAsDataURL(file);
    });
    await new Promise(resolve => img.onload = resolve)
    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    let MAX_WIDTH = 1000;
    let MAX_HEIGHT = 1000;
    let width = img.naturalWidth;
    let height = img.naturalHeight;
    if (width > height) {
        if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
        }
    } else {
        if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
        }
    }
    canvas.width = width;
    canvas.height = height;
    ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);
    let result = await new Promise<Blob>(resolve => { canvas.toBlob(resolve, 'image/jpeg', 0.95); });
    return result;
}

How to remove the default link color of the html hyperlink 'a' tag?

you can do some thing like this:

a {
    color: #0060B6;
    text-decoration: none;
}

a:hover 
{
     color:#00A0C6; 
     text-decoration:none; 
     cursor:pointer;  
}

if text-decoration doesn't work then include text-decoration: none !important;

How can I write an anonymous function in Java?

Here's an example of an anonymous inner class.

System.out.println(new Object() {
    @Override public String toString() {
        return "Hello world!";
    }
}); // prints "Hello world!"

This is not very useful as it is, but it shows how to create an instance of an anonymous inner class that extends Object and @Override its toString() method.

See also


Anonymous inner classes are very handy when you need to implement an interface which may not be highly reusable (and therefore not worth refactoring to its own named class). An instructive example is using a custom java.util.Comparator<T> for sorting.

Here's an example of how you can sort a String[] based on String.length().

import java.util.*;
//...

String[] arr = { "xxx", "cd", "ab", "z" };
Arrays.sort(arr, new Comparator<String>() {
    @Override public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }           
});
System.out.println(Arrays.toString(arr));
// prints "[z, cd, ab, xxx]"

Note the comparison-by-subtraction trick used here. It should be said that this technique is broken in general: it's only applicable when you can guarantee that it will not overflow (such is the case with String lengths).

See also

Python: how to capture image from webcam on click using OpenCV

Here is a simple programe to capture a image from using laptop default camera.I hope that this will be very easy method for all.

import cv2

# 1.creating a video object
video = cv2.VideoCapture(0) 
# 2. Variable
a = 0
# 3. While loop
while True:
    a = a + 1
    # 4.Create a frame object
    check, frame = video.read()
    # Converting to grayscale
    #gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    # 5.show the frame!
    cv2.imshow("Capturing",frame)
    # 6.for playing 
    key = cv2.waitKey(1)
    if key == ord('q'):
        break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows 

You can see my github code here

Laravel 4: how to "order by" using Eloquent ORM

If you are using post as a model (without dependency injection), you can also do:

$posts = Post::orderBy('id', 'DESC')->get();

calculating execution time in c++

Note: the question was originally about compilation time, but later it turned out that the OP really meant execution time. But maybe this answer will still be useful for someone.

For Visual Studio: go to Tools / Options / Projects and Solutions / VC++ Project Settings and set Build Timing option to 'yes'. After that the time of every build will be displayed in the Output window.

Change / Add syntax highlighting for a language in Sublime 2/3

The "this" is already coloured in Javascript.

View->Syntax-> and choose your language to highlight.

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

You can use case in update and SWAP as many as you want

update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns

Rails: How can I rename a database column in a Ruby on Rails migration?

Run the below command to create a migration file:

rails g migration ChangeHasedPasswordToHashedPassword

Then in the file generated in the db/migrate folder, write rename_column as below:

class ChangeOldCoulmnToNewColumn < ActiveRecord::Migration
  def change
     rename_column :table_name, :hased_password, :hashed_password
  end
end

How can I get javascript to read from a .json file?

Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.

$.ajax({
    url: "File.json", //the path of the file is replaced by File.json
    dataType: "json",
    success: function (response) {
        console.log(response); //it will return the json array
    }
});

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

use this query in your local DB.

  1. select * from schema_version delete from schema_version where checksum Column = -1729781252;

    Note: -1729781252 is the "Resolved locally" value.

  2. Build and start the server.

how to convert date to a format `mm/dd/yyyy`

Are you looking for something like this?

SELECT CASE WHEN LEFT(created_ts, 1) LIKE '[0-9]' 
            THEN CONVERT(VARCHAR(10), CONVERT(datetime, created_ts,   1), 101)
            ELSE CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 109), 101)
      END created_ts
  FROM table1

Output:

| CREATED_TS |
|------------|
| 02/20/2012 |
| 11/29/2012 |
| 02/20/2012 |
| 11/29/2012 |
| 02/20/2012 |
| 11/29/2012 |
| 11/16/2011 |
| 02/20/2012 |
| 11/29/2012 |

Here is SQLFiddle demo

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

<input type="number" onkeydown="return FilterInput(event)" onpaste="handlePaste(event)"  >

function FilterInput(event) {
    var keyCode = ('which' in event) ? event.which : event.keyCode;

    isNotWanted = (keyCode == 69 || keyCode == 101);
    return !isNotWanted;
};
function handlePaste (e) {
    var clipboardData, pastedData;

    // Get pasted data via clipboard API
    clipboardData = e.clipboardData || window.clipboardData;
    pastedData = clipboardData.getData('Text').toUpperCase();

    if(pastedData.indexOf('E')>-1) {
        //alert('found an E');
        e.stopPropagation();
        e.preventDefault();
    }
};

How to pattern match using regular expression in Scala?

You can do this because regular expressions define extractors but you need to define the regex pattern first. I don't have access to a Scala REPL to test this but something like this should work.

val Pattern = "([a-cA-C])".r
word.firstLetter match {
   case Pattern(c) => c bound to capture group here
   case _ =>
}

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

To prevent this, make sure every BEGIN TRANSACTION has COMMIT

The following will say successful but will leave uncommitted transactions:

BEGIN TRANSACTION
BEGIN TRANSACTION
<SQL_CODE?
COMMIT

Closing query windows with uncommitted transactions will prompt you to commit your transactions. This will generally resolve the Error 1222 message.

How to find which version of TensorFlow is installed in my system?

use

import tensorflow as tf

print(tf.VERSION)

jQuery - setting the selected value of a select control via its text description

Try

[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )

_x000D_
_x000D_
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
_x000D_
<select id="mySelect">
  <option value="A">Text A</option>
  <option value="B">Text B</option>
  <option value="C">Text C</option>
</select>
_x000D_
_x000D_
_x000D_

"inconsistent use of tabs and spaces in indentation"

Solving this using Vim editor

  1. Open terminal (Ctrl + Alt + T).
  2. Go to the directory where the file is located (cd <path_to_your_directory>). Ex: cd /home/vineeshvs/work.
  3. Open the file in Vim (vim <file_name>). Ex: vim myfile.txt .
  4. [Optional step] Enable search keyword highlighting in Vim (ESC :set hlsearch)
  5. Go to the line where you have this problem (ESC :<line_number>). Ex: :53 in Vim editor after pressing ESC button once.
  6. Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing ESC button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press ESC when you are done with the required replacements.

What is difference between Lightsail and EC2?

In lightsail a virtual machine, SSD-based storage, data transfer, DNS management, and a static IP are all offered as a package. Whereas in normal case you provision an EC2 instance and then setup the rest of these things.Also Bandwidth included in the price, no security groups to set up, no need to worry about EBS volumes sizing.

Random string generation with upper case letters and digits

A faster, easier and more flexible way to do this is to use the strgen module (pip install StringGenerator).

Generate a 6-character random string with upper case letters and digits:

>>> from strgen import StringGenerator as SG
>>> SG("[\u\d]{6}").render()
u'YZI2CI'

Get a unique list:

>>> SG("[\l\d]{10}").render_list(5,unique=True)
[u'xqqtmi1pOk', u'zmkWdUr63O', u'PGaGcPHrX2', u'6RZiUbkk2i', u'j9eIeeWgEF']

Guarantee one "special" character in the string:

>>> SG("[\l\d]{10}&[\p]").render()
u'jaYI0bcPG*0'

A random HTML color:

>>> SG("#[\h]{6}").render()
u'#CEdFCa'

etc.

We need to be aware that this:

''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

might not have a digit (or uppercase character) in it.

strgen is faster in developer-time than any of the above solutions. The solution from Ignacio is the fastest run-time performing and is the right answer using the Python Standard Library. But you will hardly ever use it in that form. You will want to use SystemRandom (or fallback if not available), make sure required character sets are represented, use unicode (or not), make sure successive invocations produce a unique string, use a subset of one of the string module character classes, etc. This all requires lots more code than in the answers provided. The various attempts to generalize a solution all have limitations that strgen solves with greater brevity and expressive power using a simple template language.

It's on PyPI:

pip install StringGenerator

Disclosure: I'm the author of the strgen module.

How to export MySQL database with triggers and procedures?

mysqldump will backup by default all the triggers but NOT the stored procedures/functions. There are 2 mysqldump parameters that control this behavior:

  • --routines – FALSE by default
  • --triggers – TRUE by default

so in mysqldump command , add --routines like :

mysqldump <other mysqldump options> --routines > outputfile.sql

See the MySQL documentation about mysqldump arguments.

How to check the version of scipy

on command line

 example$:python
 >>> import scipy
 >>> scipy.__version__
 '0.9.0'

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

Along the same lines as SCFrench's answer, but with a more C# style spin..

I would (and often do) make a class containing multiple static methods. For example:

classdef Statistics

    methods(Static)
        function val = MyMean(data)
            val = mean(data);
        end

        function val = MyStd(data)
            val = std(data);
        end
    end

end

As the methods are static you don't need to instansiate the class. You call the functions as follows:

data = 1:10;

mean = Statistics.MyMean(data);
std = Statistics.MyStd(data);     

How to add url parameters to Django template url tag?

First you need to prepare your url to accept the param in the regex: (urls.py)

url(r'^panel/person/(?P<person_id>[0-9]+)$', 'apps.panel.views.person_form', name='panel_person_form'),

So you use this in your template:

{% url 'panel_person_form' person_id=item.id %}

If you have more than one param, you can change your regex and modify the template using the following:

{% url 'panel_person_form' person_id=item.id group_id=3 %}

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is non-standard and only supported by Internet Explorer on Windows.

There is no native cross browser way to write to the file system without using plugins, even the draft File API gives read only access.

If you want to work cross platform, then you need to look at such things as signed Java applets (keeping in mind that that will only work on platforms for which the Java runtime is available).

How to get array keys in Javascript?

I wrote a function what works fine with every instance of Objects (Arrays are those).

Object.prototype.toArray = function()
{
    if(!this)
    {
      return null;
    }

    var c = [];

    for (var key in this) 
    {
        if ( ( this instanceof Array && this.constructor === Array && key === 'length' ) || !this.hasOwnProperty(key) ) 
        {
            continue;
        }

        c.push(this[key]);
    }

    return c;
};

Usage:

var a   = [ 1, 2, 3 ];
a[11]   = 4;
a["js"] = 5;

console.log(a.toArray());

var b = { one: 1, two: 2, three: 3, f: function() { return 4; }, five: 5 };
b[7] = 7;

console.log(b.toArray());

Output:

> [ 1, 2, 3, 4, 5 ]
> [ 7, 1, 2, 3, function () { return 4; }, 5 ]

It may be useful for anyone.

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I encountered this error too, it occurs because %HTTPPORT% isn’t part of the system variables yet.

The solution to this is NOT by manually typing in the url to your browser, which works but you have to keep doing it every single time.

Simply goto “this pc” or “my computer” right click on it and select properties, then select “advanced system settings” When the new window comes up select “Environment Variables...”

Now under system variables click new to create a new system variable. Type HTTPPORT into the variable name text box, Then type 8080 into the variable value text box. Click OK, close the windows and logout!

Thats an important step, make sure you log out. When you log back in, click the get started icon again and it will open without errors.

??

How to display HTML tags as plain text

Use htmlentities() to convert characters that would otherwise be displayed as HTML.

Mocking Logger and LoggerFactory with PowerMock and Mockito

I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.

console.log showing contents of array object

there are two potential simple solutions to dumping an array as string. Depending on the environment you're using:

…with modern browsers use JSON:

JSON.stringify(filters);
// returns this
"{"dvals":[{"brand":"1","count":"1"},{"brand":"2","count":"2"},{"brand":"3","count":"3"}]}"

…with something like node.js you can use console.info()

console.info(filters);
// will output:
{ dvals: 
[ { brand: '1', count: '1' },
  { brand: '2', count: '2' },
  { brand: '3', count: '3' } ] }

Edit:

JSON.stringify comes with two more optional parameters. The third "spaces" parameter enables pretty printing:

JSON.stringify(
                obj,      // the object to stringify
                replacer, // a function or array transforming the result
                spaces    // prettyprint indentation spaces
              )

example:

JSON.stringify(filters, null, "  ");
// returns this
"{
 "dvals": [
  {
   "brand": "1",
   "count": "1"
  },
  {
   "brand": "2",
   "count": "2"
  },
  {
   "brand": "3",
   "count": "3"
  }
 ]
}"

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

How to catch exception output from Python subprocess.check_output()?

This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):

from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
    cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
    print(e.output.decode()) # print out the stdout messages up to the exception
    print(e) # To print out the exception message

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

(For who ever got here due to wrong table style) Change Table style from plain to grouped, via the attributes inspector, or via code:

let tableView = UITableView(frame: .zero, style: .grouped)

How to overcome the CORS issue in ReactJS

Temporary solve this issue by a chrome plugin called CORS. Btw backend server have to send proper header to front end requests.

Replace a string in a file with nodejs

ES2017/8 for Node 7.6+ with a temporary write file for atomic replacement.

const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))

async function replaceRegexInFile(file, search, replace){
  let contents = await fs.readFileAsync(file, 'utf8')
  let replaced_contents = contents.replace(search, replace)
  let tmpfile = `${file}.jstmpreplace`
  await fs.writeFileAsync(tmpfile, replaced_contents, 'utf8')
  await fs.renameAsync(tmpfile, file)
  return true
}

Note, only for smallish files as they will be read into memory.

UPDATE and REPLACE part of a string

You don't need wildcards in the REPLACE - it just finds the string you enter for the second argument, so the following should work:

UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4

If the column to replace is type text or ntext you need to cast it to nvarchar

UPDATE dbo.xxx
SET Value = REPLACE(CAST(Value as nVarchar(4000)), '123', '')
WHERE ID <=4

Angular 2 : No NgModule metadata found

If you are having this issue in Angular 8 or Angular 9 (like I was), after:

  • Clearing your npm cache
  • reinstalling all node_modules
  • checking your "include" and "files" tsconfig setting etc

and you're still having issues, and you are Lazy Loading Modules check your angularCompilerOptions in your tsconfig.json or tsconfig.app.json, and make sure that "strictMetadataEmit" is set to false or is removed.

"angularCompilerOptions": {
    "preserveWhitespaces": false,
    "strictInjectionParameters": true,
    "fullTemplateTypeCheck": true,
    "strictTemplates": true,
    // "strictMetadataEmit": true <-- remove this setting or set to false
},

The setting is to help library creators which should never have lazy loaded modules built in. I had previously (using Angular 7) set all "strict" options to true...

How to count the occurrence of certain item in an ndarray?

What about len(y[y==0]) and len(y[y==1]) ?

Unexpected character encountered while parsing value

I had the same problem with webapi in ASP.NET core, in my case it was because my application needs authentication, then it assigns the annotation [AllowAnonymous] and it worked.

[AllowAnonymous]
public async Task <IList <IServic >> GetServices () {
        
}

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

An absolute xpath in HTML DOM starts with /html e.g.

/html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]

and a relative xpath finds the closed id to the dom element and generates xpath starting from that element e.g.

.//*[@id='answers']/h2[1]/a[1]

You can use firepath (firebug) for generating both types of xpaths

It won't make any difference which xpath you use in selenium, the former may be faster than the later one (but it won't be observable)

Absolute xpaths are prone to more regression as slight change in DOM makes them invalid or refer to a wrong element