Programs & Examples On #This keyword

Use of "this" keyword in C++

It's programmer preference. Personally, I love using this since it explicitly marks the object members. Of course the _ does the same thing (only when you follow the convention)

Parsing xml using powershell

First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]

$doc = [xml]@'
<xml>
    <Section name="BackendStatus">
        <BEName BE="crust" Status="1" />
        <BEName BE="pizza" Status="1" />
        <BEName BE="pie" Status="1" />
        <BEName BE="bread" Status="1" />
        <BEName BE="Kulcha" Status="1" />
        <BEName BE="kulfi" Status="1" />
        <BEName BE="cheese" Status="1" />
    </Section>
</xml>
'@

Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:

$doc.xml.Section.BEName

Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where

$doc.xml.Section.BEName | ? { $_.Status -eq 1 }

The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).

If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:

$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }

Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

It worked in my case

sudo npm uninstall -g angular-cli @angular/cli
sudo npm cache clean --force
npm install npm@latest -g
sudo npm install -g @angular/cli

Add element to a list In Scala

You are using an immutable list. The operations on the List return a new List. The old List remains unchanged. This can be very useful if another class / method holds a reference to the original collection and is relying on it remaining unchanged. You can either use different named vals as in

val myList1 = 1.0 :: 5.5 :: Nil 
val myList2 = 2.2 :: 3.7 :: mylist1

or use a var as in

var myList = 1.0 :: 5.5 :: Nil 
myList :::= List(2.2, 3.7)

This is equivalent syntax for:

myList = myList.:::(List(2.2, 3.7))

Or you could use one of the mutable collections such as

val myList = scala.collection.mutable.MutableList(1.0, 5.5)
myList.++=(List(2.2, 3.7))

Not to be confused with the following that does not modify the original mutable List, but returns a new value:

myList.++:(List(2.2, 3.7))

However you should only use mutable collections in performance critical code. Immutable collections are much easier to reason about and use. One big advantage is that immutable List and scala.collection.immutable.Vector are Covariant. Don't worry if that doesn't mean anything to you yet. The advantage of it is you can use it without fully understanding it. Hence the collection you were using by default is actually scala.collection.immutable.List its just imported for you automatically.

I tend to use List as my default collection. From 2.12.6 Seq defaults to immutable Seq prior to this it defaulted to immutable.

UnicodeEncodeError: 'ascii' codec can't encode character at special name

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

Example -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

What is the point of "Initial Catalog" in a SQL Server connection string?

This is the initial database of the data source when you connect.

Edited for clarity:

If you have multiple databases in your SQL Server instance and you don't want to use the default database, you need some way to specify which one you are going to use.

SQL Server replace, remove all after certain character

UPDATE MyTable
   SET MyText = SUBSTRING(MyText, 1, CHARINDEX(';', MyText) - 1)
 WHERE CHARINDEX(';', MyText) > 0 

How display only years in input Bootstrap Datepicker?

always year for bootstrap 3 datetimepicker https://eonasdan.github.io/bootstrap-datetimepicker/

   $('#year').datetimepicker({
        format: 'YYYY',
        viewMode: "years",
    });

    $("#year").on("dp.hide", function (e) {
        $('#year').datetimepicker('destroy');
        $('#year').datetimepicker({
            format: 'YYYY',
            viewMode: "years",
        });
    });

SQLite Query in Android to count rows

DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).

SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
                "uname=? AND pwd=?", new String[] {loginname,loginpass});

SVG rounded corner

This basically does the same as Mvins answer, but is a more compressed down and simplified version. It works by going back the distance of the radius of the lines adjacent to the corner and connecting both ends with a bezier curve whose control point is at the original corner point.

function createRoundedPath(coords, radius, close) {
  let path = ""
  const length = coords.length + (close ? 1 : -1)
  for (let i = 0; i < length; i++) {
    const a = coords[i % coords.length]
    const b = coords[(i + 1) % coords.length]
    const t = Math.min(radius / Math.hypot(b.x - a.x, b.y - a.y), 0.5)

    if (i > 0) path += `Q${a.x},${a.y} ${a.x * (1 - t) + b.x * t},${a.y * (1 - t) + b.y * t}`

    if (!close && i == 0) path += `M${a.x},${a.y}`
    else if (i == 0) path += `M${a.x * (1 - t) + b.x * t},${a.y * (1 - t) + b.y * t}`

    if (!close && i == length - 1) path += `L${b.x},${b.y}`
    else if (i < length - 1) path += `L${a.x * t + b.x * (1 - t)},${a.y * t + b.y * (1 - t)}`
  }
  if (close) path += "Z"
  return path
}

How to undo a git pull?

git reflog show should show you the history of HEAD. You can use that to figure out where you were before the pull. Then you can reset your HEAD to that commit.

When is it appropriate to use C# partial classes?

Another use is to split the implementation of different interfaces, e.g:

partial class MyClass : IF3
{
    // main implementation of MyClass
}


partial class MyClass : IF1
{
    // implementation of IF1
}

partial class MyClass : IF2
{
    // implementation of IF2
}

Visual Studio: Relative Assembly References Paths

I might be off here, but it seems that the answer is quite obvious: Look at reference paths in the project properties. In our setup I added our common repository folder, to the ref path GUI window, like so

Reference Paths in VS20xx

That way I can copy my dlls (ready for publish) to this folder and every developer now gets the updated DLL every time it builds from this folder.

If the dll is found in the Solution, the builder should prioritize the local version over the published team version.

Sort hash by key, return hash in Ruby

In Ruby 2.1 it is simple:

h.sort.to_h

What is the difference between C and embedded C?

In the C standard, a standalone implementation doesn't have to provide all of the library functions that a hosted implementation has to provide. The C standard doesn't care about embedded, but vendors of embedded systems usually provide standalone implementations with whatever amount of libraries they're willing to provide.

C is a widely used general purpose high level programming language mainly intended for system programming.

Embedded C is an extension to C programming language that provides support for developing efficient programs for embedded devices.It is not a part of the C language

You can also refer to the articles below:

How to read XML using XPath in Java

Here is an example of processing xpath with vtd-xml... for heavy duty XML processing it is second to none. here is the a recent paper on this subject Processing XML with Java – A Performance Benchmark

import com.ximpleware.*;

public class changeAttrVal {
    public  static  void main(String s[]) throws VTDException,java.io.UnsupportedEncodingException,java.io.IOException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        XMLModifier xm = new XMLModifier(vn);
        ap.selectXPath("/*/place[@id=\"p14\" and   @initialMarking=\"2\"]/@initialMarking");
        int i=0;
        while((i=ap.evalXPath())!=-1){
            xm.updateToken(i+1, "499");// change initial marking from 2 to 499
        }
        xm.output("new.xml");
    }

}

C# get and set properties for a List Collection

If I understand your request correctly, you have to do the following:

public class Section 
{ 
    public String Head
    {
        get
        {
            return SubHead.LastOrDefault();
        }
        set
        {
            SubHead.Add(value);
        }

    public List<string> SubHead { get; private set; }
    public List<string> Content { get; private set; }
} 

You use it like this:

var section = new Section();
section.Head = "Test string";

Now "Test string" is added to the subHeads collection and will be available through the getter:

var last = section.Head; // last will be "Test string"

Hope I understood you correctly.

How to insert image in mysql database(table)?

This is on mysql workbench -- give the image file path:

INSERT INTO XX_SAMPLE(id,image) VALUES(3,'/home/ganesan-pc/Documents/aios_database/confe.jpg');

How to percent-encode URL parameters in Python?

In Python 3, urllib.quote has been moved to urllib.parse.quote and it does handle unicode by default.

>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'

Django DoesNotExist

This line

 except Vehicle.vehicledevice.device.DoesNotExist

means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like

 except Device.DoesNotExist

how to format date in Component of angular 5

You can find more information about the date pipe here, such as formats.

If you want to use it in your component, you can simply do

pipe = new DatePipe('en-US'); // Use your own locale

Now, you can simply use its transform method, which will be

const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');

Keyboard shortcut to comment lines in Sublime Text 3

Sublime 3 for Windows:

Add comment tags -> CTRL + SHIFT + ;
The whole line becomes a comment line -> CTRL + ;

Extending from two classes

Java does not support multiple inheritance, but you can try to implement two or more interface.

Which version of C# am I using

From developer command prompt type

csc -langversion:?

That will display all C# versions supported including the default:

1
2
3
4
5
6
7.0 (default)
7.1
7.2
7.3 (latest)

javascript remove "disabled" attribute from html input

method 1 <input type="text" onclick="this.disabled=false;" disabled>
<hr>
method 2 <input type="text" onclick="this.removeAttribute('disabled');" disabled>
<hr>
method 3 <input type="text" onclick="this.removeAttribute('readonly');" readonly>

code of the previous answers don't seem to work in inline mode, but there is a workaround: method 3.

see demo https://jsfiddle.net/eliz82/xqzccdfg/

T-SQL How to create tables dynamically in stored procedures?

This is a way to create tables dynamically using T-SQL stored procedures:

declare @cmd nvarchar(1000), @MyTableName nvarchar(100);
set @MyTableName = 'CustomerDetails';
set @cmd = 'CREATE TABLE dbo.' + quotename(@MyTableName, '[') + '(ColumnName1 int not null,ColumnName2 int not null);';

Execute it as:

exec(@cmd);

How to check if a file exists in a shell script

You're missing a required space between the bracket and -e:

#!/bin/bash
if [ -e x.txt ]
then
    echo "ok"
else
    echo "nok"
fi

Returning an empty array

A different way to return an empty array is to use a constant as all empty arrays of a given type are the same.

private static final File[] NO_FILES = {};
private static File[] bar(){
    return NO_FILES;
}

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

How to use the switch statement in R functions?

those various ways of switch ...

# by index
switch(1, "one", "two")
## [1] "one"


# by index with complex expressions
switch(2, {"one"}, {"two"})
## [1] "two"


# by index with complex named expression
switch(1, foo={"one"}, bar={"two"})
## [1] "one"


# by name with complex named expression
switch("bar", foo={"one"}, bar={"two"})
## [1] "two"

Python BeautifulSoup extract text between element

soup = BeautifulSoup(html)
for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
  hit = hit.text.strip()
  print hit

This will print: THIS IS MY TEXT Try this..

Javascript loading CSV file into an array

I highly recommend looking into this plugin:

http://github.com/evanplaice/jquery-csv/

I used this for a project handling large CSV files and it handles parsing a CSV into an array quite well. You can use this to call a local file that you specify in your code, also, so you are not dependent on a file upload.

Once you include the plugin above, you can essentially parse the CSV using the following:

$.ajax({
    url: "pathto/filename.csv",
    async: false,
    success: function (csvd) {
        data = $.csv.toArrays(csvd);
    },
    dataType: "text",
    complete: function () {
        // call a function on complete 
    }
});

Everything will then live in the array data for you to manipulate as you need. I can provide further examples for handling the array data if you need.

There are a lot of great examples available on the plugin page to do a variety of things, too.

How to download PDF automatically using js?

It is also possible to open the pdf link in a new window and let the browser handle the rest:

window.open(pdfUrl, '_blank');

or:

window.open(pdfUrl);

Python set to list

s = set([1,2,3])
print [ x for x in iter(s) ]

Getting absolute URLs using ASP.NET Core

In a new ASP.Net 5 MVC project in a controller action you can still do this.Context and this.Context.Request It looks like on the Request there is no longer a Url property but the child properties (schema, host, etc) are all on the request object directly.

 public IActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        var schema = this.Context.Request.Scheme;

        return View();
    }

Rather or not you want to use this.Context or inject the property is another conversation. Dependency Injection in ASP.NET vNext

How do I copy a folder from remote to local using scp?

scp -r [email protected]:/path/to/foo /home/user/Desktop/

By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.

From man scp (See online manual)

-r Recursively copy entire directories

How to set the max size of upload file

I found the the solution at Expert Exchange, which worked fine for me.

@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setMaxFileSize("124MB");
    factory.setMaxRequestSize("124MB");
    return factory.createMultipartConfig();
}

Ref: https://www.experts-exchange.com/questions/28990849/How-to-increase-Spring-boot-Tomcat-max-file-upload-size.html

Why does intellisense and code suggestion stop working when Visual Studio is open?

For python, try clicking on the "Python X.X" button on the left side of the bottom status bar and changing it to different values.

This is the only thing that worked for me.

.m2 , settings.xml in Ubuntu

Quoted from http://maven.apache.org/settings.html:

There are two locations where a settings.xml file may live:

The Maven install: $M2_HOME/conf/settings.xml

A user's install: ${user.home}/.m2/settings.xml

So, usually for a specific user you edit

/home/*username*/.m2/settings.xml

To set environment for all local users, you might think about changing the first path.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

In NHibernate (with NHibernate.Linq) you could do it as follows:

return session.Query<T>()
              .Single(a => a.Filter == filter &&
                           a.Id == session.Query<T>()
                                          .Where(a2 => a2.Filter == filter)
                                          .Max(a2 => a2.Id));

Which will generate SQL like follows:

select *
from TableName foo
where foo.Filter = 'Filter On String'
and foo.Id = (select cast(max(bar.RowVersion) as INT)
              from TableName bar
              where bar.Name = 'Filter On String')

Which seems pretty efficient to me.

Django templates: If false?

I think this will work for you:

{% if not myvar %}

Importing a function from a class in another file?

It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.

For example:

def run():
    print "this does nothing"

def chooser():
    return "run"

def main():
    '''works just like:
    run()'''
    eval(chooser())()

The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.

Drop primary key using script in SQL Server database

You can look up the constraint name in the sys.key_constraints table:

SELECT name
FROM   sys.key_constraints
WHERE  [type] = 'PK'
       AND [parent_object_id] = Object_id('dbo.Student');

If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:

DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);

SELECT @table = N'dbo.Student';

SELECT @sql = 'ALTER TABLE ' + @table 
    + ' DROP CONSTRAINT ' + name + ';'
    FROM sys.key_constraints
    WHERE [type] = 'PK'
    AND [parent_object_id] = OBJECT_ID(@table);

EXEC sp_executeSQL @sql;

This code is from Aaron Bertrand (source).

Split string into individual words Java

StringTokenizer separate = new StringTokenizer(s, " ");
String word = separate.nextToken();
System.out.println(word);

Download Excel file via AJAX MVC

CSL's answer was implemented in a project I'm working on but the problem I incurred was scaling out on Azure broke our file downloads. Instead, I was able to do this with one AJAX call:

SERVER

[HttpPost]
public FileResult DownloadInvoice(int id1, int id2)
{
    //necessary to get the filename in the success of the ajax callback
    HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

    byte[] fileBytes = _service.GetInvoice(id1, id2);
    string fileName = "Invoice.xlsx";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

CLIENT (modified version of Handle file download from ajax post)

$("#downloadInvoice").on("click", function() {
    $("#loaderInvoice").removeClass("d-none");

    var xhr = new XMLHttpRequest();
    var params = [];
    xhr.open('POST', "@Html.Raw(Url.Action("DownloadInvoice", "Controller", new { id1 = Model.Id1, id2 = Model.Id2 }))", true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function () {
        if (this.status === 200) {
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            }
            var type = xhr.getResponseHeader('Content-Type');

            var blob = typeof File === 'function'
                ? new File([this.response], filename, { type: type })
                : new Blob([this.response], { type: type });
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                window.navigator.msSaveBlob(blob, filename);
            } else {
                var URL = window.URL || window.webkitURL;
                var downloadUrl = URL.createObjectURL(blob);

                if (filename) {
                    // use HTML5 a[download] attribute to specify filename
                    var a = document.createElement("a");
                    // safari doesn't support this yet
                    if (typeof a.download === 'undefined') {
                        window.location = downloadUrl;
                    } else {
                        a.href = downloadUrl;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                    }
                } else {
                    window.location = downloadUrl;

                }

                setTimeout(function() {
                        URL.revokeObjectURL(downloadUrl);
                    $("#loaderInvoice").addClass("d-none");
                }, 100); // cleanup
            }
        }
    };
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send($.param(params));
});

java.util.NoSuchElementException - Scanner reading user input

This has really puzzled me for a while but this is what I found in the end.

When you call, sc.close() in first method, it not only closes your scanner but closes your System.in input stream as well. You can verify it by printing its status at very top of the second method as :

    System.out.println(System.in.available());

So, now when you re-instantiate, Scanner in second method, it doesn't find any open System.in stream and hence the exception.

I doubt if there is any way out to reopen System.in because:

public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**

The only good solution for your problem is to initiate the Scanner in your main method, pass that as argument in your two methods, and close it again in your main method e.g.:

main method related code block:

Scanner scanner = new Scanner(System.in);  

// Ask users for quantities 
PromptCustomerQty(customer, ProductList, scanner );

// Ask user for payment method
PromptCustomerPayment(customer, scanner );

//close the scanner 
scanner.close();

Your Methods:

 public static void PromptCustomerQty(Customer customer, 
                             ArrayList<Product> ProductList, Scanner scanner) {

    // no more scanner instantiation
    ...
    // no more scanner close
 }


 public static void PromptCustomerPayment (Customer customer, Scanner sc) {

    // no more scanner instantiation
    ...
    // no more scanner close
 }

Hope this gives you some insight about the failure and possible resolution.

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

I'm not familiar with python 3 yet, but it seems like urllib.request.urlopen().read() returns a byte object rather than string.

You might try to feed it into a StringIO object, or even do a str(response).

Loading inline content using FancyBox

The way I figured this out was going through the example index.html/style.css that comes packaged with the Fancybox installation.

If you view the code that is used for the demo website and basically copy/paste, you'll be fine.

To get an inline Fancybox working, you will need to have this code present in your index.html file:

  <head>
    <link href="./fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" media="screen" />
    <script>!window.jQuery && document.write('<script src="jquery-1.4.3.min.js"><\/script>');</script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {

    $("#various1").fancybox({
            'titlePosition'     : 'inside',
            'transitionIn'      : 'none',
            'transitionOut'     : 'none'
        });
    });
    </script>
  </head>

 <body>

    <a id="various1" href="#inline1" title="Put a title here">Name of Link Here</a>
    <div style="display: none;">
        <div id="inline1" style="width:400px;height:100px;overflow:auto;">
                   Write whatever text you want right here!!
        </div>
    </div> 

</body>

Remember to be precise about what folders your script files are placed in and where you are pointing to in the Head tag; they must correspond.

Cannot find control with name: formControlName in angular reactive form

I tried to generate a form dynamically because the amount of questions depend on an object and for me the error was fixed when I added ngDefaultControl to my mat-form-field.

    <form [formGroup]="questionsForm">
        <ng-container *ngFor="let question of questions">
            <mat-form-field [formControlName]="question.id" ngDefaultControl>
                <mat-label>{{question.questionContent}}</mat-label>
                <textarea matInput rows="3" required></textarea>
            </mat-form-field>
        </ng-container>
        <button mat-raised-button (click)="sendFeedback()">Submit all questions</button>
    </form>

In sendFeedback() I get the value from my dynamic form by selecting the formgroup's value as such

  sendFeedbackAsAgent():void {
    if (this.questionsForm.valid) {
      console.log(this.questionsForm.value)
    }
  }

Copy every nth line from one sheet to another

If I were confronted with extracting every 7th row I would “insert” a column before Column “A” . I would then (assuming that there is a header row in row 1) type in the numbers 1,2,3,4,5,6,7 in rows 2,3,4,5,6,7,8, I would highlight the 1,2,3,4,5,6,7 and paste that block to the end of the sheet (700 rows worth). The result will be 1,23,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7……. Now do a data sort ascending on column “A”. After the sort all of the 1’s will be the first in the series, all of the 7’s will be the seventh item.

What are file descriptors, explained in simple terms?

File Descriptors are the descriptors to a file. They give links to a file. With the help of them we can read, write and open a file.

Server is already running in Rails

You can get rid of the process by killing it:

kill -9 $(lsof -i tcp:3000 -t)

Npm install cannot find module 'semver'

On Arch Linux what did the trick for me was:

sudo pacman -Rs npm
sudo pacman -S npm

Which sort algorithm works best on mostly sorted data?

ponder Try Heap. I believe it's the most consistent of the O(n lg n) sorts.

C# how to create a Guid value?

To makes an "empty" all-0 guid like 00000000-0000-0000-0000-000000000000.

var makeAllZeroGuID = new System.Guid();

or

var makeAllZeroGuID = System.Guid.Empty;

To makes an actual guid with a unique value, what you probably want.

var uniqueGuID = System.Guid.NewGuid(); 

How do I pick randomly from an array?

myArray.sample(x) can also help you to get x random elements from the array.

What's the difference between import java.util.*; and import java.util.Date; ?

You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.

Or better, try to avoid naming your classes "Date".

CSS "and" and "or"

You can somehow reproduce the behavior of "OR" using & and :not.

SomeElement.SomeClass [data-statement="things are getting more complex"]  :not(:not(A):not(B))     {
    /* things aren't so complex for A or B */
}

Find an item in List by LINQ?

If you want the index of the element, this will do it:

int index = list.Select((item, i) => new { Item = item, Index = i })
                .First(x => x.Item == search).Index;

// or
var tagged = list.Select((item, i) => new { Item = item, Index = i });
int index = (from pair in tagged
            where pair.Item == search
            select pair.Index).First();

You can't get rid of the lambda in the first pass.

Note that this will throw if the item doesn't exist. This solves the problem by resorting to nullable ints:

var tagged = list.Select((item, i) => new { Item = item, Index = (int?)i });
int? index = (from pair in tagged
            where pair.Item == search
            select pair.Index).FirstOrDefault();

If you want the item:

// Throws if not found
var item = list.First(item => item == search);
// or
var item = (from item in list
            where item == search
            select item).First();

// Null if not found
var item = list.FirstOrDefault(item => item == search);
// or
var item = (from item in list
            where item == search
            select item).FirstOrDefault();

If you want to count the number of items that match:

int count = list.Count(item => item == search);
// or
int count = (from item in list
            where item == search
            select item).Count();

If you want all the items that match:

var items = list.Where(item => item == search);
// or
var items = from item in list
            where item == search
            select item;

And don't forget to check the list for null in any of these cases.

Or use (list ?? Enumerable.Empty<string>()) instead of list.

Thanks to Pavel for helping out in the comments.

File inside jar is not visible for spring

If your spring-context.xml and my.config files are in different jars then you will need to use classpath*:my.config?

More info here

Also, make sure you are using resource.getInputStream() not resource.getFile() when loading from inside a jar file.

Get selected row item in DataGrid WPF

If you're using the MVVM pattern you can bind a SelectedRecord property of your VM with SelectedItem of the DataGrid, this way you always have the SelectedValue in you VM. Otherwise you should use the SelectedIndex property of the DataGrid.

What is the syntax of the enhanced for loop in Java?

  1. Enhanced For Loop (Java)
for (Object obj : list);
  1. Enhanced For Each in arraylist (Java)
ArrayList<Integer> list = new ArrayList<Integer>(); 
list.forEach((n) -> System.out.println(n)); 

Postman - How to see request with headers and body data with variables substituted

I'd like to add complementary information: In postman app you may use the "request" object to see your subsituted input data. (refer to https://www.getpostman.com/docs/postman/scripts/postman_sandbox in paragraph "Request/response related properties", ie.

console.log("header : " + request.headers["Content-Type"]);
console.log("body : " + request.data);
console.log("url : " + request.url);

I didn't test for header substitution but it works for url and body.

Alex

Java Interfaces/Implementation naming convention

I've seen answers here that suggest that if you only have one implementation then you don't need an interface. This flies in the face of the Depencency Injection/Inversion of Control principle (don't call us, we'll call you!).

So yes, there are situations in which you wish to simplify your code and make it easily testable by relying on injected interface implementations (which may also be proxied - your code doesn't know!). Even if you only have two implementations - one a Mock for testing, and one that gets injected into the actual production code - this doesn't make having an interface superfluous. A well documented interface establishes a contract, which can also be maintained by a strict mock implementation for testing.

in fact, you can establish tests that have mocks implement the most strict interface contract (throwing exceptions for arguments that shouldn't be null, etc) and catch errors in testing, using a more efficient implementation in production code (not checking arguments that should not be null for being null since the mock threw exceptions in your tests and you know that the arguments aren't null due to fixing the code after these tests, for example).

Dependency Injection/IOC can be hard to grasp for a newcomer, but once you understand its potential you'll want to use it all over the place and you'll find yourself making interfaces all the time - even if there will only be one (actual production) implementation.

For this one implementation (you can infer, and you'd be correct, that I believe the mocks for testing should be called Mock(InterfaceName)), I prefer the name Default(InterfaceName). If a more specific implementation comes along, it can be named appropriately. This also avoids the Impl suffix that I particularly dislike (if it's not an abstract class, OF COURSE it is an "impl"!).

I also prefer "Base(InterfaceName)" as opposed to "Abstract(InterfaceName)" because there are some situations in which you want your base class to become instantiable later, but now you're stuck with the name "Abstract(InterfaceName)", and this forces you to rename the class, possibly causing a little minor confusion - but if it was always Base(InterfaceName), removing the abstract modifier doesn't change what the class was.

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

Right Click Microsoft BI -> Click Run as Administrator -> either open your existing SSRS report or create your new SSRS report and then deploy your report after that complied you will be received one web URL for to view your report. Copy that URL and paste to web browser(Run as Administrator) and you will get your report view. You could use Internet Explorer, which would be essential for web service

If it is wrong means,Please forgive me since i did like this so that i just written.

What function is to replace a substring from a string in C?

You could build your own replace function using strstr to find the substrings and strncpy to copy in parts to a new buffer.

Unless what you want to replace_with is the same length as what you you want to replace, then it's probably best to use a new buffer to copy the new string to.

Single TextView with multiple colored text

yes, if you format the String with html's font-color property then pass it to the method Html.fromHtml(your text here)

String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));

CSS Classes & SubClasses

FYI, when you define a rule like you did above, with two selectors chained together:

.area1.item
{
    color:red;
}

It means:

Apply this style to any element that has both the class "area1" and "item".

Such as:

<div class="area1 item">

Sadly it doesn't work in IE6, but that's what it means.

Find the day of a week

Let's say you additionally want the week to begin on Monday (instead of default on Sunday), then the following is helpful:

require(lubridate)
df$day = ifelse(wday(df$time)==1,6,wday(df$time)-2)

The result is the days in the interval [0,..,6].

If you want the interval to be [1,..7], use the following:

df$day = ifelse(wday(df$time)==1,7,wday(df$time)-1)

... or, alternatively:

df$day = df$day + 1

Check for null variable in Windows batch

The right thing would be to use a "if defined" statement, which is used to test for the existence of a variable. For example:

IF DEFINED somevariable echo Value exists

In this particular case, the negative form should be used:

IF NOT DEFINED somevariable echo Value missing

PS: the variable name should be used without "%" caracters.

How to embed small icon in UILabel

Swift 4.2:

let attachment = NSTextAttachment()        
attachment.image = UIImage(named: "yourIcon.png")
let attachmentString = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: price)
myString.append(attachmentString)
label.attributedText = myString

Oracle date to string conversion

Try this. Oracle has this feature to distinguish the millennium years..

As you mentioned, if your column is a varchar, then the below query will yield you 1989..

select to_date(column_name,'dd/mm/rr') from table1;

When the format rr is used in year, the following would be done by oracle.

if rr->00 to 49 ---> result will be 2000 - 2049, if rr->50 to 99 ---> result will be 1950 - 1999

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

You must have either disabled, froze or uninstalled FaceProvider in settings>applications>all
This will only happen if it's frozen, either uninstall it, or enable it.

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Only way I can think of is to concatenate the worksheet name with the cell reference, as follows:

Dim cell As Range
Dim cellAddress As String
Set cell = ThisWorkbook.Worksheets(1).Cells(1, 1)
cellAddress = cell.Parent.Name & "!" & cell.Address(External:=False)

EDIT:

Modify last line to :

cellAddress = "'" & cell.Parent.Name & "'!" & cell.Address(External:=False) 

if you want it to work even if there are spaces or other funny characters in the sheet name.

What is the difference between docker-compose ports vs expose

According to the docker-compose reference,

Ports is defined as:

Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).

  • Ports mentioned in docker-compose.yml will be shared among different services started by the docker-compose.
  • Ports will be exposed to the host machine to a random port or a given port.

My docker-compose.yml looks like:

mysql:
  image: mysql:5.7
  ports:
    - "3306"

If I do docker-compose ps, it will look like:

  Name                     Command               State            Ports
-------------------------------------------------------------------------------------
  mysql_1       docker-entrypoint.sh mysqld      Up      0.0.0.0:32769->3306/tcp

Expose is defined as:

Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.

Ports are not exposed to host machines, only exposed to other services.

mysql:
  image: mysql:5.7
  expose:
    - "3306"

If I do docker-compose ps, it will look like:

  Name                  Command             State    Ports
---------------------------------------------------------------
 mysql_1      docker-entrypoint.sh mysqld   Up      3306/tcp

Edit

In recent versions of Docker, expose doesn't have any operational impact anymore, it is just informative. (see also)

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

Not an enclosing class error Android Studio

you are calling the context of not existing activity...so just replace your code in onClick(View v) as Intent intent=new Intent(this,Katra_home.class); startActivity(intent); it will definitely works....

what's the easiest way to put space between 2 side-by-side buttons in asp.net

If you are using bootstrap, add ml-3 to your second button:

 <div class="row justify-content-center mt-5">
        <button class="btn btn-secondary" type="button">Button1</button>
        <button class="btn btn-secondary ml-3" type="button">Button2</button>
 </div>

Setting Column width in Apache POI

You can use also util methods mentioned in this blog: Getting cell witdth and height from excel with Apache POI. It can solve your problem.

Copy & paste from that blog:

static public class PixelUtil {

    public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
    public static final short EXCEL_ROW_HEIGHT_FACTOR = 20;
    public static final int UNIT_OFFSET_LENGTH = 7;
    public static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 };

    public static short pixel2WidthUnits(int pxs) {
        short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH));
        widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];
        return widthUnits;
    }

    public static int widthUnits2Pixel(short widthUnits) {
        int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH;
        int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;
        pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));
        return pixels;
    }

    public static int heightUnits2Pixel(short heightUnits) {
        int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR);
        int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR;
        pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH));
        return pixels;
    }
}

So when you want to get cell width and height you can use this to get value in pixel, values are approximately.

PixelUtil.heightUnits2Pixel((short) row.getHeight())
PixelUtil.widthUnits2Pixel((short) sh.getColumnWidth(columnIndex));

Rolling or sliding window iterator?

There is a library which does exactly what you need:

import more_itertools
list(more_itertools.windowed([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],n=3, step=3))

Out: [(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12), (13, 14, 15)]

UILabel is not auto-shrinking text to fit label size

also my solution is the boolean label.adjustsFontSizeToFitWidth = YES; BUT. You must in the interface Builder the Word Wrapping switch to "CLIP". Then autoshrink the Labels. This is very important.

Plain Old CLR Object vs Data Transfer Object

here is the general rule: DTO==evil and indicator of over-engineered software. POCO==good. 'enterprise' patterns have destroyed the brains of a lot of people in the Java EE world. please don't repeat the mistake in .NET land.

How do I set GIT_SSL_NO_VERIFY for specific repos only?

Like what Thirumalai said, but inside of the cloned repository and without --global. I.e.,

  1. GIT_SSL_NO_VERIFY=true git clone https://url
  2. cd <directory-of-the-clone>
  3. git config http.sslVerify false

Sending email with gmail smtp with codeigniter email library

You need to enable SSL in your PHP config. Load up php.ini and find a line with the following:

;extension=php_openssl.dll

Uncomment it. :D

(by removing the semicolon from the statement)

extension=php_openssl.dll

Loop over html table and get checked checkboxes (JQuery)

Use this instead:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked') //...
});

Let me explain you what the selector does: input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox After that: :checked will match all checked checkboxes.

You can loop over these checkboxes with:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked').each(function () {
       //this is the current checkbox
    });
});

Here is demo in JSFiddle.


And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.

$('#save').click(function () {
    $('#mytable').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked') &&
            row.find('textarea').val().length <= 0) {
            alert('You must fill the text area!');
        }
    });
});

Query to select data between two dates with the format m/d/yyyy

This solution provides CONVERT_IMPLICIT operation for your condition in predicate

SELECT * 
FROM xxx 
WHERE CAST(dates AS date) BETWEEN '1/1/2013' and '1/2/2013'

enter image description here

OR

SELECT * 
FROM xxx 
WHERE CONVERT(date, dates, 101) BETWEEN '1/1/2013' and '1/2/2013'

enter image description here

Demo on SQLFiddle

Make xargs handle filenames that contain spaces

On macOS 10.12.x (Sierra), if you have spaces in file names or subdirectories, you can use the following:

find . -name '*.swift' -exec echo '"{}"' \; |xargs wc -l

Where is SQLite database stored on disk?

When you call sqlite3_open() you specify the filepath the database is opened from/saved to, if it is not an absolute path it is specified relative to your current working directory.

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

i had the same problem. finally i got the solution

before updating listview, if the soft keypad is present close it first. after that set data source and call notifydatasetchanged().

while closing keypad internally listview will update its ui. it keep calling till closing keypad. that time if data source change it willl throw this exception. if data is updating in onActivityResult, there is a chance for same error.

 InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshList();
            }
        },100L);

CodeIgniter - how to catch DB errors?

If one uses PDO, additional to all the answers above.

I log my errors silently as below

        $q = $this->db->conn_id->prepare($query);

        if($q instanceof PDOStatement) {
           // go on with bind values and execute

        } else {

          $dbError = $this->db->error();
          $this->Logger_model->logError('Db Error', date('Y-m-d H:i:s'), __METHOD__.' Line '.__LINE__, 'Code: '.$dbError['code'].' -  '.'Message: '.$dbError['message']);

        }

How to convert JSON to XML or XML to JSON?

Yes, you can do it (I do) but Be aware of some paradoxes when converting, and handle appropriately. You cannot automatically conform to all interface possibilities, and there is limited built-in support in controlling the conversion- many JSON structures and values cannot automatically be converted both ways. Keep in mind I am using the default settings with Newtonsoft JSON library and MS XML library, so your mileage may vary:

XML -> JSON

  1. All data becomes string data (for example you will always get "false" not false or "0" not 0) Obviously JavaScript treats these differently in certain cases.
  2. Children elements can become nested-object {} OR nested-array [ {} {} ...] depending if there is only one or more than one XML child-element. You would consume these two differently in JavaScript, etc. Different examples of XML conforming to the same schema can produce actually different JSON structures this way. You can add the attribute json:Array='true' to your element to workaround this in some (but not necessarily all) cases.
  3. Your XML must be fairly well-formed, I have noticed it doesn't need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries.
  4. In older versions, Blank elements do not convert to JSON. They are ignored. A blank element does not become "element":null

A new update changes how null can be handled (Thanks to Jon Story for pointing it out): https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

JSON -> XML

  1. You need a top level object that will convert to a root XML element or the parser will fail.
  2. Your object names cannot start with a number, as they cannot be converted to elements (XML is technically even more strict than this) but I can 'get away' with breaking some of the other element naming rules.

Please feel free to mention any other issues you have noticed, I have developed my own custom routines for preparing and cleaning the strings as I convert back and forth. Your situation may or may not call for prep/cleanup. As StaxMan mentions, your situation may actually require that you convert between objects...this could entail appropriate interfaces and a bunch of case statements/etc to handle the caveats I mention above.

Getting current date and time in JavaScript

var datetime = new Date().toLocaleString().slice(0,9) +" "+new Date(new Date()).toString().split(' ')[4];
console.log(datetime);

How to use a servlet filter in Java to change an incoming servlet request url?

A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.

public class UrlPrettyfierFilter implements Filter {

    private static final String JSF_VIEW_ROOT_PATH = "/ui";

    private static final String JSF_VIEW_SUFFIX = ".xhtml";

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
        String requestURI = httpServletRequest.getRequestURI();
        //Only process the paths starting with /ui, so as other requests get unprocessed. 
        //You can register the filter itself for /ui/* only, too
        if (requestURI.startsWith(JSF_VIEW_ROOT_PATH) 
                && !requestURI.contains(JSF_VIEW_SUFFIX)) {
            request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
                .forward(request,response);
        } else {
            chain.doFilter(httpServletRequest, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

Turning error reporting off php

Tried this yet?

error_reporting(0);
@ini_set('display_errors', 0);

What is href="#" and why is it used?

As some of the other answers have pointed out, the a element requires an href attribute and the # is used as a placeholder, but it is also a historical artifact.

From Mozilla Developer Network:

href

This was the single required attribute for anchors defining a hypertext source link, but is no longer required in HTML5. Omitting this attribute creates a placeholder link. The href attribute indicates the link target, either a URL or a URL fragment. A URL fragment is a name preceded by a hash mark (#), which specifies an internal target location (an ID) within the current document.

Also, per the HTML5 spec:

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.

Changing :hover to touch/click for mobile devices

If you use :active selector in combination with :hover you can achieve this according to w3schools as long as the :active selector is called after the :hover selector.

 .info-slide:hover, .info-slide:active{
   height:300px;
 }

You'd have to test the FIDDLE in a mobile environment. I can't at the moment.
correction - I just tested in a mobile, it works fine

Android TextView Text not getting wrapped

I put this attribute:

android:inputType="textMultiLine"

into my TextView and it has wrapping line and user can "Enter" for a new line.

============================================================

When you come to this post, you may want to create a Big TextView which can display multiple lines so these attributes may also needed

android:layout_height="Xdp" //where X is a number depends on how big Textview you want
android:gravity="top" //in order to make your text start from the top of your TextView.

Alternative to itoa() for converting integer to string C++?

?++11 finally resolves this providing std::to_string. Also boost::lexical_cast is handy tool for older compilers.

How to display alt text for an image in chrome

Various browsers (mis)handle this in various ways. Using title (an old IE 'standard') isn't particularly appropriate, since the title attribute is a mouseover effect. The jQuery solution above (Alexis) seems on the right track, but I don't think the 'error' occurs at a point where it could be caught. I've had success by replacing at the src with itself, and then catching the error:

$('img').each(function()
{
    $(this).error(function()
    {
        $(this).replaceWith(this.alt);
    }).attr('src',$(this).prop('src'));
});

This, as in the Alexis contribution, has the benefit of removing the missing img image.

Beginner Python: AttributeError: 'list' object has no attribute

They are lists because you type them as lists in the dictionary:

bikes = {
    # Bike designed for children"
    "Trike": ["Trike", 20, 100],
    # Bike designed for everyone"
    "Kruzer": ["Kruzer", 50, 165]
    }

You should use the bike-class instead:

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165)
    }

This will allow you to get the cost of the bikes with bike.cost as you were trying to.

for bike in bikes.values():
    profit = bike.cost * margin
    print(bike.name + " : " + str(profit))

This will now print:

Kruzer : 33.0
Trike : 20.0

How to support different screen size in android

Android adjust by it self you can put separate image for different folder if you want to use different images for high resolution devices and other device. Otherwise just put in one drawable,layout folder only for some images you can make 9-patch also.

read here

you need permission in manifest for multiple screen support link

<supports-screens android:resizeable=["true"| "false"]
                  android:smallScreens=["true" | "false"]
                  android:normalScreens=["true" | "false"]
                  android:largeScreens=["true" | "false"]
                  android:xlargeScreens=["true" | "false"]
                  android:anyDensity=["true" | "false"]
                  android:requiresSmallestWidthDp="integer"
                  android:compatibleWidthLimitDp="integer"
                  android:largestWidthLimitDp="integer"/>

make sounds (beep) with c++

#include<iostream>
#include<conio.h>
#include<windows.h>
using namespace std;

int main()
{

    Beep(1568, 200);
    Beep(1568, 200);
    Beep(1568, 200);
    Beep(1245, 1000);
    Beep(1397, 200);
    Beep(1397, 200);
    Beep(1397, 200);
    Beep(1175, 1000);

cout<<endl;
_getch()

return 0
}

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

In addition to the previous comments browser support for word-wrap seems to be a bit better than for word-break.

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Further reading for any of the topics here: The Definitive Guide to Linux System Calls


I verified these using GNU Assembler (gas) on Linux.

Kernel Interface

x86-32 aka i386 Linux System Call convention:

In x86-32 parameters for Linux system call are passed using registers. %eax for syscall_number. %ebx, %ecx, %edx, %esi, %edi, %ebp are used for passing 6 parameters to system calls.

The return value is in %eax. All other registers (including EFLAGS) are preserved across the int $0x80.

I took following snippet from the Linux Assembly Tutorial but I'm doubtful about this. If any one can show an example, it would be great.

If there are more than six arguments, %ebx must contain the memory location where the list of arguments is stored - but don't worry about this because it's unlikely that you'll use a syscall with more than six arguments.

For an example and a little more reading, refer to http://www.int80h.org/bsdasm/#alternate-calling-convention. Another example of a Hello World for i386 Linux using int 0x80: Hello, world in assembly language with Linux system calls?

There is a faster way to make 32-bit system calls: using sysenter. The kernel maps a page of memory into every process (the vDSO), with the user-space side of the sysenter dance, which has to cooperate with the kernel for it to be able to find the return address. Arg to register mapping is the same as for int $0x80. You should normally call into the vDSO instead of using sysenter directly. (See The Definitive Guide to Linux System Calls for info on linking and calling into the vDSO, and for more info on sysenter, and everything else to do with system calls.)

x86-32 [Free|Open|Net|DragonFly]BSD UNIX System Call convention:

Parameters are passed on the stack. Push the parameters (last parameter pushed first) on to the stack. Then push an additional 32-bit of dummy data (Its not actually dummy data. refer to following link for more info) and then give a system call instruction int $0x80

http://www.int80h.org/bsdasm/#default-calling-convention


x86-64 Linux System Call convention:

(Note: x86-64 Mac OS X is similar but different from Linux. TODO: check what *BSD does)

Refer to section: "A.2 AMD64 Linux Kernel Conventions" of System V Application Binary Interface AMD64 Architecture Processor Supplement. The latest versions of the i386 and x86-64 System V psABIs can be found linked from this page in the ABI maintainer's repo. (See also the tag wiki for up-to-date ABI links and lots of other good stuff about x86 asm.)

Here is the snippet from this section:

  1. User-level applications use as integer registers for passing the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9. The kernel interface uses %rdi, %rsi, %rdx, %r10, %r8 and %r9.
  2. A system-call is done via the syscall instruction. This clobbers %rcx and %r11 as well as the %rax return value, but other registers are preserved.
  3. The number of the syscall has to be passed in register %rax.
  4. System-calls are limited to six arguments, no argument is passed directly on the stack.
  5. Returning from the syscall, register %rax contains the result of the system-call. A value in the range between -4095 and -1 indicates an error, it is -errno.
  6. Only values of class INTEGER or class MEMORY are passed to the kernel.

Remember this is from the Linux-specific appendix to the ABI, and even for Linux it's informative not normative. (But it is in fact accurate.)

This 32-bit int $0x80 ABI is usable in 64-bit code (but highly not recommended). What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? It still truncates its inputs to 32-bit, so it's unsuitable for pointers, and it zeros r8-r11.

User Interface: function calling

x86-32 Function Calling convention:

In x86-32 parameters were passed on stack. Last parameter was pushed first on to the stack until all parameters are done and then call instruction was executed. This is used for calling C library (libc) functions on Linux from assembly.

Modern versions of the i386 System V ABI (used on Linux) require 16-byte alignment of %esp before a call, like the x86-64 System V ABI has always required. Callees are allowed to assume that and use SSE 16-byte loads/stores that fault on unaligned. But historically, Linux only required 4-byte stack alignment, so it took extra work to reserve naturally-aligned space even for an 8-byte double or something.

Some other modern 32-bit systems still don't require more than 4 byte stack alignment.


x86-64 System V user-space Function Calling convention:

x86-64 System V passes args in registers, which is more efficient than i386 System V's stack args convention. It avoids the latency and extra instructions of storing args to memory (cache) and then loading them back again in the callee. This works well because there are more registers available, and is better for modern high-performance CPUs where latency and out-of-order execution matter. (The i386 ABI is very old).

In this new mechanism: First the parameters are divided into classes. The class of each parameter determines the manner in which it is passed to the called function.

For complete information refer to : "3.2 Function Calling Sequence" of System V Application Binary Interface AMD64 Architecture Processor Supplement which reads, in part:

Once arguments are classified, the registers get assigned (in left-to-right order) for passing as follows:

  1. If the class is MEMORY, pass the argument on the stack.
  2. If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9 is used

So %rdi, %rsi, %rdx, %rcx, %r8 and %r9 are the registers in order used to pass integer/pointer (i.e. INTEGER class) parameters to any libc function from assembly. %rdi is used for the first INTEGER parameter. %rsi for 2nd, %rdx for 3rd and so on. Then call instruction should be given. The stack (%rsp) must be 16B-aligned when call executes.

If there are more than 6 INTEGER parameters, the 7th INTEGER parameter and later are passed on the stack. (Caller pops, same as x86-32.)

The first 8 floating point args are passed in %xmm0-7, later on the stack. There are no call-preserved vector registers. (A function with a mix of FP and integer arguments can have more than 8 total register arguments.)

Variadic functions (like printf) always need %al = the number of FP register args.

There are rules for when to pack structs into registers (rdx:rax on return) vs. in memory. See the ABI for details, and check compiler output to make sure your code agrees with compilers about how something should be passed/returned.


Note that the Windows x64 function calling convention has multiple significant differences from x86-64 System V, like shadow space that must be reserved by the caller (instead of a red-zone), and call-preserved xmm6-xmm15. And very different rules for which arg goes in which register.

URL rewriting with PHP

If you only want to change the route for picture.php then adding rewrite rule in .htaccess will serve your needs, but, if you want the URL rewriting as in Wordpress then PHP is the way. Here is simple example to begin with.

Folder structure

There are two files that are needed in the root folder, .htaccess and index.php, and it would be good to place the rest of the .php files in separate folder, like inc/.

root/
  inc/
  .htaccess
  index.php

.htaccess

RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

This file has four directives:

  1. RewriteEngine - enable the rewriting engine
  2. RewriteRule - deny access to all files in inc/ folder, redirect any call to that folder to index.php
  3. RewriteCond - allow direct access to all other files ( like images, css or scripts )
  4. RewriteRule - redirect anything else to index.php

index.php

Because everything is now redirected to index.php, there will be determined if the url is correct, all parameters are present, and if the type of parameters are correct.

To test the url we need to have a set of rules, and the best tool for that is a regular expression. By using regular expressions we will kill two flies with one blow. Url, to pass this test must have all the required parameters that are tested on allowed characters. Here are some examples of rules.

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'
);

Next is to prepare the request uri.

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

Now that we have the request uri, the final step is to test uri on regular expression rules.

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        /* now you know the action and parameters so you can 
         * include appropriate template file ( or proceed in some other way )
         */
    }
}

Successful match will, since we use named subpatterns in regex, fill the $params array almost the same as PHP fills the $_GET array. However, when using a dynamic url, $_GET array is populated without any checks of the parameters.

    /picture/some+text/51

    Array
    (
        [0] => /picture/some text/51
        [text] => some text
        [1] => some text
        [id] => 51
        [2] => 51
    )

    picture.php?text=some+text&id=51

    Array
    (
        [text] => some text
        [id] => 51
    )

These few lines of code and a basic knowing of regular expressions is enough to start building a solid routing system.

Complete source

define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'
);

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        /* now you know the action and parameters so you can 
         * include appropriate template file ( or proceed in some other way )
         */
        include( INCLUDE_DIR . $action . '.php' );

        // exit to avoid the 404 message 
        exit();
    }
}

// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );

How do I exit from the text window in Git?

There is a default text editor that will be used when Git needs you to type in a message. By default, Git uses your system’s default editor, which is generally Vi or Vim. In your case, it is Vim that Git has chosen. See How do I make Git use the editor of my choice for commits? for details of how to choose another editor. Meanwhile...

You'll want to enter a message before you leave Vim:

O

...will start a new line for you to type in.

To exit (g)Vim type:

EscZZ or Esc:wqReturn.

It's worth getting to know Vim, as you can use it for editing text on almost any platform. I recommend the Vim Tutor, I used it many years ago and have never looked back (barely a day goes by when I don't use Vim).

How to list all methods for an object in Ruby?

If You are looking list of methods which respond by an instance (in your case @current_user). According to ruby documentation methods

Returns a list of the names of public and protected methods of obj. This will include all the methods accessible in obj's ancestors. If the optional parameter is false, it returns an array of obj's public and protected singleton methods, the array will not include methods in modules included in obj.

@current_user.methods
@current_user.methods(false) #only public and protected singleton methods and also array will not include methods in modules included in @current_user class or parent of it.

Alternatively, You can also check that a method is callable on an object or not?.

@current_user.respond_to?:your_method_name

If you don't want parent class methods then just subtract the parent class methods from it.

@current_user.methods - @current_user.class.superclass.new.methods #methods that are available to @current_user instance.

javascript onclick increment number

I know this is an old post but its relevant to what I'm working on currently.

What I'm aiming to do is create next/previous page buttons at the top of a html page, and say I'm on 'book.html', with the current 'display' ID content being 'page-1.html' through ajax, if i click the 'next' button it will load 'page-2.html' through ajax, WITHOUT reloading the page.

How would I go about doing this through AJAX as I have seen many examples but most of them are completely different, and most examples of using AJAX are for WordPress forms and stuff.

Currently using the below line will open the entire page, I want to know the best way to go about using AJAX instead if possible :) window.location(url);

I'm incorportating the below code as an example:

var i = 1;
var url = "pages/page-" + i + ".html";

    function incPage() {
    if (i < 10) {
        i++;
        window.location = url; 
        //load next page in body using AJAX request

    } else if (i = 10) {
        i = 0;
    }
    document.getElementById("display").innerHTML = i;
}

function decPage() {
    if (i > 0) {
        --i;
        window.location = url; 
        //load previous page in body using AJAX request
    } else if (i = 0) {
        i = 10;
    }
    document.getElementById("display").innerHTML = i;
}

Convert multidimensional array into single array

This simple code you can use

$array = array_column($array, 'value', 'key');

android: how to align image in the horizontal center of an imageview?

Try:

android:layout_height="wrap_content"
android:scaleType="fitStart"

on the image in the RelativeLayout

Date / Timestamp to record when a record was added to the table?

You can create a non-nullable DATETIME column on your table, and create a DEFAULT constraint on it to auto populate when a row is added.

e.g.

CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)

How do I get the unix timestamp in C as an int?

#include <stdio.h>
#include <time.h>

int main ()
{
   time_t seconds;

   seconds = time(NULL);
   printf("Seconds since January 1, 1970 = %ld\n", seconds);

   return(0);
}

And will get similar result:
Seconds since January 1, 1970 = 1476107865

Difference between a virtual function and a pure virtual function

A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.

You denote that fact by appending the "= 0" to the declaration, like this:

class AbstractBase
{
    virtual void PureVirtualFunction() = 0;
}

Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:

class Derived : public AbstractBase
{
    virtual void PureVirtualFunction() override { }
}

By adding the override keyword, the compiler will ensure that there is a base class virtual function with the same signature.

Excel VBA, How to select rows based on data in a column?

The easiest way to do it is to use the End method, which is gives you the cell that you reach by pressing the end key and then a direction when you're on a cell (in this case B6). This won't give you what you expect if B6 or B7 is empty, though.

Dim start_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Range(start_cell, start_cell.End(xlDown)).Copy Range("[Workbook2.xlsx]Sheet1!A2")

If you can't use End, then you would have to use a loop.

Dim start_cell As Range, end_cell As Range

Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Set end_cell = start_cell

Do Until IsEmpty(end_cell.Offset(1, 0))
    Set end_cell = end_cell.Offset(1, 0)
Loop

Range(start_cell, end_cell).Copy Range("[Workbook2.xlsx]Sheet1!A2")

Find mouse position relative to element

You can simply use jQuery’s event.pageX and event.pageY with the method offset() of jQuery to get the position of the mouse relative to an element.

  $(document).ready(function() {
    $("#myDiv").mousemove(function(event){            
      var X = event.pageX - $(this).offset().left;
      var Y = event.pageY - $(this).offset().top;
      $(".cordn").text("(" + X + "," + Y + ")");
    });
  });

You can see an example here: How to find mouse position relative to element

Subtract two dates in SQL and get days of the result

SELECT (to_date('02-JAN-2013') - to_date('02-JAN-2012')) days_between
FROM dual
/

Are email addresses case sensitive?

From RFC 5321, section 2.3.11:

The standard mailbox naming convention is defined to be "local-part@domain"; contemporary usage permits a much broader set of applications than simple "user names". Consequently, and due to a long history of problems when intermediate hosts have attempted to optimize transport by modifying them, the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address.

So yes, the part before the "@" could be case-sensitive, since it is entirely under the control of the host system. In practice though, no widely used mail systems distinguish different addresses based on case.

The part after the @ sign however is the domain and according to RFC 1035, section 3.1,

"Name servers and resolvers must compare [domains] in a case-insensitive manner"

In short, you are safe to treat email addresses as case-insensitive.

How do I parse a HTML page with Node.js

Htmlparser2 by FB55 seems to be a good alternative.

How to check if a socket is connected/disconnected in C#?

Just use the KeepAlive like @toster-cx says and then use the Socket Connected status to check if the Socket is still connected. Set your receive timeout at the same timeout of the keepalive. If you have more questions i am always happy to help!

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

Try this <link rel="stylesheet" type="text/css" href="../##/yourcss.css">

where ## is your folder wherein is your .CSS - file

Don't forget about the: .. (double dots).

What does "Changes not staged for commit" mean

It's another way of Git telling you:

Hey, I see you made some changes, but keep in mind that when you write pages to my history, those changes won't be in these pages.

Changes to files are not staged if you do not explicitly git add them (and this makes sense).

So when you git commit, those changes won't be added since they are not staged. If you want to commit them, you have to stage them first (ie. git add).

Can I pass parameters by reference in Java?

Java is always pass by value.

When you pass a primitive it's a copy of the value, when you pass an object it's a copy of the reference pointer.

Check if ADODB connection is open

This topic is old but if other people like me search a solution, this is a solution that I have found:

Public Function DBStats() As Boolean
    On Error GoTo errorHandler
        If Not IsNull(myBase.Version) Then 
            DBStats = True
        End If
        Exit Function
    errorHandler:
        DBStats = False  
End Function

So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":

Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false

Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false

When to use pthread_exit() and when to use pthread_join() in Linux?

You don't need any calls to pthread_exit(3) in your particular code.

In general, the main thread should not call pthread_exit, but should often call pthread_join(3) to wait for some other thread to finish.

In your PrintHello function, you don't need to call pthread_exit because it is implicit after returning from it.

So your code should rather be:

void *PrintHello(void *threadid)  {
  long tid = (long)threadid;
  printf("Hello World! It's me, thread #%ld!\n", tid);
  return threadid;
}

int main (int argc, char *argv[]) {
   pthread_t threads[NUM_THREADS];
   int rc;
   intptr_t t;
   // create all the threads
   for(t=0; t<NUM_THREADS; t++){
     printf("In main: creating thread %ld\n", (long) t);
     rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
     if (rc) { fprintf(stderr, "failed to create thread #%ld - %s\n",
                                (long)t, strerror(rc));
               exit(EXIT_FAILURE);
             };
   }
   pthread_yield(); // useful to give other threads more chance to run
   // join all the threads
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: joining thread #%ld\n", (long) t);
      rc = pthread_join(&threads[t], NULL);
      if (rc) { fprintf(stderr, "failed to join thread #%ld - %s\n",
                                (long)t, strerror(rc));
               exit(EXIT_FAILURE);
      }
   }
}

What is the difference between Promises and Observables?

Both Promises and Observables will help us work with the asynchronous functionalities in JavaScript. They are very similar in many cases, however, there are still some differences between the two as well, promises are values that will resolve in asynchronous ways like http calls. On the other hand, observables deal with a sequence of asynchronous events. The main differences between them are listed below:

promise:

  • having one pipeline
  • usually only use with async data return
  • not easy to cancel

observable:

  • are cancellable
  • are re-triable by nature such as retry and retryWhen
  • stream data in multiple pipelines
  • having array-like operations like map, filter etc
  • can be created from other sources like events
  • they are functions, which could be subscribed later on

Also, I've created the graphical image for you below to show the differences visually:

Promises and Observables image

C# Parsing JSON array of objects

I believe this is much simpler;

dynamic obj = JObject.Parse(jsonString);
string results  = obj.results;
foreach(string result in result.Split('))
{
//Todo
}

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

Calculate cosine similarity given 2 sentence strings

Try this. Download the file 'numberbatch-en-17.06.txt' from https://conceptnet.s3.amazonaws.com/downloads/2017/numberbatch/numberbatch-en-17.06.txt.gz and extract it. The function 'get_sentence_vector' uses a simple sum of word vectors. However it can be improved by using weighted sum where weights are proportional to Tf-Idf of each word.

import math
import numpy as np

std_embeddings_index = {}
with open('path/to/numberbatch-en-17.06.txt') as f:
    for line in f:
        values = line.split(' ')
        word = values[0]
        embedding = np.asarray(values[1:], dtype='float32')
        std_embeddings_index[word] = embedding

def cosineValue(v1,v2):
    "compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
    sumxx, sumxy, sumyy = 0, 0, 0
    for i in range(len(v1)):
        x = v1[i]; y = v2[i]
        sumxx += x*x
        sumyy += y*y
        sumxy += x*y
    return sumxy/math.sqrt(sumxx*sumyy)


def get_sentence_vector(sentence, std_embeddings_index = std_embeddings_index ):
    sent_vector = 0
    for word in sentence.lower().split():
        if word not in std_embeddings_index :
            word_vector = np.array(np.random.uniform(-1.0, 1.0, 300))
            std_embeddings_index[word] = word_vector
        else:
            word_vector = std_embeddings_index[word]
        sent_vector = sent_vector + word_vector

    return sent_vector

def cosine_sim(sent1, sent2):
    return cosineValue(get_sentence_vector(sent1), get_sentence_vector(sent2))

I did run for the given sentences and found the following results

s1 = "This is a foo bar sentence ."
s2 = "This sentence is similar to a foo bar sentence ."
s3 = "What is this string ? Totally not related to the other two lines ."

print cosine_sim(s1, s2) # Should give high cosine similarity
print cosine_sim(s1, s3) # Shouldn't give high cosine similarity value
print cosine_sim(s2, s3) # Shouldn't give high cosine similarity value

0.9851735249068168
0.6570885718962608
0.6589335425458225

Check if null Boolean is true results in exception

Boolean types can be null. You need to do a null check as you have set it to null.

if (bool != null && bool)
{
  //DoSomething
}                   

What underlies this JavaScript idiom: var self = this?

See this article on alistapart.com. (Ed: The article has been updated since originally linked)

self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).

Edit: Note that using self is now discouraged as window.self exists and has the potential to cause errors if you are not careful.

What you call the variable doesn't particularly matter. var that = this; is fine, but there's nothing magic about the name.

Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.

For example, a simple event callback:

_x000D_
_x000D_
function MyConstructor(options) {_x000D_
  let that = this;_x000D_
_x000D_
  this.someprop = options.someprop || 'defaultprop';_x000D_
_x000D_
  document.addEventListener('click', (event) => {_x000D_
    alert(that.someprop);_x000D_
  });_x000D_
}_x000D_
_x000D_
new MyConstructor({_x000D_
  someprop: "Hello World"_x000D_
});
_x000D_
_x000D_
_x000D_

Eclipse error, "The selection cannot be launched, and there are no recent launches"

Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.

Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.

Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.

To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.

What is a good regular expression to match a URL?

(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})

Will match the following cases

  • http://www.foufos.gr
  • https://www.foufos.gr
  • http://foufos.gr
  • http://www.foufos.gr/kino
  • http://werer.gr
  • www.foufos.gr
  • www.mp3.com
  • www.t.co
  • http://t.co
  • http://www.t.co
  • https://www.t.co
  • www.aa.com
  • http://aa.com
  • http://www.aa.com
  • https://www.aa.com

Will NOT match the following

  • www.foufos
  • www.foufos-.gr
  • www.-foufos.gr
  • foufos.gr
  • http://www.foufos
  • http://foufos
  • www.mp3#.com

_x000D_
_x000D_
var expression = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;_x000D_
var regex = new RegExp(expression);_x000D_
_x000D_
var check = [_x000D_
  'http://www.foufos.gr',_x000D_
  'https://www.foufos.gr',_x000D_
  'http://foufos.gr',_x000D_
  'http://www.foufos.gr/kino',_x000D_
  'http://werer.gr',_x000D_
  'www.foufos.gr',_x000D_
  'www.mp3.com',_x000D_
  'www.t.co',_x000D_
  'http://t.co',_x000D_
  'http://www.t.co',_x000D_
  'https://www.t.co',_x000D_
  'www.aa.com',_x000D_
  'http://aa.com',_x000D_
  'http://www.aa.com',_x000D_
  'https://www.aa.com',_x000D_
  'www.foufos',_x000D_
  'www.foufos-.gr',_x000D_
  'www.-foufos.gr',_x000D_
  'foufos.gr',_x000D_
  'http://www.foufos',_x000D_
  'http://foufos',_x000D_
  'www.mp3#.com'_x000D_
];_x000D_
_x000D_
check.forEach(function(entry) {_x000D_
  if (entry.match(regex)) {_x000D_
    $("#output").append( "<div >Success: " + entry + "</div>" );_x000D_
  } else {_x000D_
    $("#output").append( "<div>Fail: " + entry + "</div>" );_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Check it in rubular - NEW version

Check it in rubular - old version

Counting unique / distinct values by group in a data frame

In dplyr you may use n_distinct to "count the number of unique values":

library(dplyr)
myvec %>%
  group_by(name) %>%
  summarise(n_distinct(order_no))

Disable output buffering

One way to get unbuffered output would be to use sys.stderr instead of sys.stdout or to simply call sys.stdout.flush() to explicitly force a write to occur.

You could easily redirect everything printed by doing:

import sys; sys.stdout = sys.stderr
print "Hello World!"

Or to redirect just for a particular print statement:

print >>sys.stderr, "Hello World!"

To reset stdout you can just do:

sys.stdout = sys.__stdout__

Capturing standard out and error with Start-Process

Here's a kludgy way to get the output from another powershell process:

start-process -wait -nonewwindow powershell 'ps | Export-Clixml out.xml'; import-clixml out.xml

How to execute Ant build in command line

Go to the Ant website and download. This way, you have a copy of Ant outside of Eclipse. I recommend to put it under the C:\ant directory. This way, it doesn't have any spaces in the directory names. In your System Control Panel, set the Environment Variable ANT_HOME to this directory, then pre-pend to the System PATHvariable, %ANT_HOME%\bin. This way, you don't have to put in the whole directory name.

Assuming you did the above, try this:

C:\> cd \Silk4J\Automation\iControlSilk4J
C:\Silk4J\Automation\iControlSilk4J> ant -d build

This will do several things:

  • It will eliminate the possibility that the problem is with Eclipe's version of Ant.
  • It is way easier to type
  • Since you're executing the build.xml in the directory where it exists, you don't end up with the possibility that your Ant build can't locate a particular directory.

The -d will print out a lot of output, so you might want to capture it, or set your terminal buffer to something like 99999, and run cls first to clear out the buffer. This way, you'll capture all of the output from the beginning in the terminal buffer.

Let's see how Ant should be executing. You didn't specify any targets to execute, so Ant should be taking the default build target. Here it is:

<target depends="build-subprojects,build-project" name="build"/>

The build target does nothing itself. However, it depends upon two other targets, so these will be called first:

The first target is build-subprojects:

<target name="build-subprojects"/>

This does nothing at all. It doesn't even have a dependency.

The next target specified is build-project does have code:

<target depends="init" name="build-project">

This target does contain tasks, and some dependent targets. Before build-project executes, it will first run the init target:

<target name="init">
    <mkdir dir="bin"/>
    <copy includeemptydirs="false" todir="bin">
        <fileset dir="src">
            <exclude name="**/*.java"/>
        </fileset>
    </copy>
</target>

This target creates a directory called bin, then copies all files under the src tree with the suffix *.java over to the bin directory. The includeemptydirs mean that directories without non-java code will not be created.

Ant uses a scheme to do minimal work. For example, if the bin directory is created, the <mkdir/> task is not executed. Also, if a file was previously copied, or there are no non-Java files in your src directory tree, the <copy/> task won't run. However, the init target will still be executed.

Next, we go back to our previous build-project target:

<target depends="init" name="build-project">
    <echo message="${ant.project.name}: ${ant.file}"/>
    <javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
        <src path="src"/>
        <classpath refid="iControlSilk4J.classpath"/>
    </javac>
</target>

Look at this line:

<echo message="${ant.project.name}: ${ant.file}"/>

That should have always executed. Did your output print:

[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

Maybe you didn't realize that was from your build.

After that, it runs the <javac/> task. That is, if there's any files to actually compile. Again, Ant tries to avoid work it doesn't have to do. If all of the *.java files have previously been compiled, the <javac/> task won't execute.

And, that's the end of the build. Your build might not have done anything simply because there was nothing to do. You can try running the clean task, and then build:

C:\Silk4J\Automation\iControlSilk4J> ant -d clean build

However, Ant usually prints the target being executed. You should have seen this:

init:

build-subprojects:

build-projects:

    [echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

build:

Build Successful

Note that the targets are all printed out in order they're executed, and the tasks are printed out as they are executed. However, if there's nothing to compile, or nothing to copy, then you won't see these tasks being executed. Does this look like your output? If so, it could be there's nothing to do.

  • If the bin directory already exists, <mkdir/> isn't going to execute.
  • If there are no non-Java files in src, or they have already been copied into bin, the <copy/> task won't execute.
  • If there are no Java file in your src directory, or they have already been compiled, the <java/> task won't run.

If you look at the output from the -d debug, you'll see Ant looking at a task, then explaining why a particular task wasn't executed. Plus, the debug option will explain how Ant decides what tasks to execute.

See if that helps.

How do I run a Java program from the command line on Windows?

As of Java 9, the JDK includes jshell, a Java REPL.

Assuming the JDK 9+ bin directory is correctly added to your path, you will be able to simply:

  1. Run jshell File.javaFile.java being your file of course.
  2. A prompt will open, allowing you to call the main method: jshell> File.main(null).
  3. To close the prompt and end the JVM session, use /exit

Full documentation for JShell can be found here.

How to get length of a list of lists in python

"The above text file used has 3 lines of 4 elements separated by commas. The variable numLines prints out as '4' not '3'. So, len(myLines) is returning the number of elements in each list not the length of the list of lists."

It sounds like you're reading in a .csv with 3 rows and 4 columns. If this is the case, you can find the number of rows and lines by using the .split() method:

text = open("filetest.txt", "r").read()
myRows = text.split("\n")      #this method tells Python to split your filetest object each time it encounters a line break 
print len(myRows)              #will tell you how many rows you have
for row in myRows:
  myColumns = row.split(",")   #this method will consider each of your rows one at a time. For each of those rows, it will split that row each time it encounters a comma.  
  print len(myColumns)         #will tell you, for each of your rows, how many columns that row contains

When to use IMG vs. CSS background-image?

It's a black and white decision to me. If the image is part of the content such as a logo or diagram or person (real person, not stock photo people) then use the <img /> tag plus alt attribute. For everything else there's CSS background images.

The other time to use CSS background images is when doing image-replacement of text eg. paragraphs/headers.

How can I check if a key exists in a dictionary?

If you want to retrieve the key's value if it exists, you can also use

try:
    value = a[key]
except KeyError:
    # Key is not present
    pass

If you want to retrieve a default value when the key does not exist, use value = a.get(key, default_value). If you want to set the default value at the same time in case the key does not exist, use value = a.setdefault(key, default_value).

Reverse a string in Python

This is also an interesting way:

def reverse_words_1(s):
    rev = ''
    for i in range(len(s)):
        j = ~i  # equivalent to j = -(i + 1)
        rev += s[j]
    return rev

or similar:

def reverse_words_2(s):
    rev = ''
    for i in reversed(range(len(s)):
        rev += s[i]
    return rev

Another more 'exotic' way using byterarray which supports .reverse()

b = bytearray('Reverse this!', 'UTF-8')
b.reverse()
b.decode('UTF-8')

will produce:

'!siht esreveR'

How to compare objects by multiple fields

@Patrick To sort more than one field consecutively try ComparatorChain

A ComparatorChain is a Comparator that wraps one or more Comparators in sequence. The ComparatorChain calls each Comparator in sequence until either 1) any single Comparator returns a non-zero result (and that result is then returned), or 2) the ComparatorChain is exhausted (and zero is returned). This type of sorting is very similar to multi-column sorting in SQL, and this class allows Java classes to emulate that kind of behaviour when sorting a List.

To further facilitate SQL-like sorting, the order of any single Comparator in the list can >be reversed.

Calling a method that adds new Comparators or changes the ascend/descend sort after compare(Object, Object) has been called will result in an UnsupportedOperationException. However, take care to not alter the underlying List of Comparators or the BitSet that defines the sort order.

Instances of ComparatorChain are not synchronized. The class is not thread-safe at construction time, but it is thread-safe to perform multiple comparisons after all the setup operations are complete.

How do I delete a local repository in git?

Delete the .git directory in the root-directory of your repository if you only want to delete the git-related information (branches, versions).

If you want to delete everything (git-data, code, etc), just delete the whole directory.

.git directories are hidden by default, so you'll need to be able to view hidden files to delete it.

Submitting form and pass data to controller method of type FileStreamResult

When in doubt, follow MVC conventions.

Create a viewModel if you haven't already that contains a property for JobID

public class Model
{
     public string JobId {get; set;}
     public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
     //...any other properties you may need
}

Strongly type your view

@model Fully.Qualified.Path.To.Model

Add a hidden field for JobId to the form

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{   
    //...    
    @Html.HiddenFor(m => m.JobId)
}

And accept the model as the parameter in your controller action:

[HttpPost]
public FileStreamResult myMethod(Model model)
{
    sting str = model.JobId;
}

How do I connect to my existing Git repository using Visual Studio Code?

Use the Git GUI in the Git plugin.

Clone your online repository with the URL which you have.

After cloning, make changes to the files. When you make changes, you can see the number changes. Commit those changes.

Fetch from the remote (to check if anything is updated while you are working).

If the fetch operation gives you an update about the changes in the remote repository, make a pull operation which will update your copy in Visual Studio Code. Otherwise, do not make a pull operation if there aren't any changes in the remote repository.

Push your changes to the upstream remote repository by making a push operation.

Redirecting to previous page after login? PHP

You can save a page using php, like this:

$_SESSION['current_page'] = $_SERVER['REQUEST_URI']

And return to the page with:

header("Location: ". $_SESSION['current_page'])

Corrupt jar file

Also, make sure that the java version used at runtime is an equivalent or later version than the java used during compilation

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

How to fix System.NullReferenceException: Object reference not set to an instance of an object

During debug, break on all exceptions thrown. Debug->Exceptions

Check all 'Thrown' exceptions. F5, the code will stop on the offending line.

Using Exit button to close a winform program

this.Close();

Closes the form programmatically.

Pandas convert dataframe to array of tuples

list(data_set.itertuples(index=False))

As of 17.1, the above will return a list of namedtuples.

If you want a list of ordinary tuples, pass name=None as an argument:

list(data_set.itertuples(index=False, name=None))

How can I save a base64-encoded image to disk?

I think you are converting the data a bit more than you need to. Once you create the buffer with the proper encoding, you just need to write the buffer to the file.

var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");

require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
  console.log(err);
});

new Buffer(..., 'base64') will convert the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string. Then you can just write that byte array to the file.

Update

As mentioned in the comments, req.rawBody is no longer a thing. If you are using express/connect then you should use the bodyParser() middleware and use req.body, and if you are doing this using standard Node then you need to aggregate the incoming data event Buffer objects and do this image data parsing in the end callback.

Session state can only be used when enableSessionState is set to true either in a configuration

I want to let everyone know that sometimes this error just is a result of some weird memory error. Restart your pc and go back into visual studio and it will be gone!! Bizarre! Try that before you start playing around with your web config file etc like I did!!!! ;-)

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 to fix "Referenced assembly does not have a strong name" error?

I had this issue for an app that was strongly named then had to change it in order to reference a non-strongly named assembly, so I unchecked 'Sign the assembly' in the project properties Signing section but it still complained. I figured it had to be an artifact somewhere causing the problem since I did everything else correctly and it was just that. I found and removed the line: [assembly: AssemblyKeyFile("yourkeyfilename.snk")] from its assemblyInfo.cs file. Then no build complaints after that.

How to rsync only a specific list of files?

--files-from= parameter needs trailing slash if you want to keep the absolute path intact. So your command would become something like below:

rsync -av --files-from=/path/to/file / /tmp/

This could be done like there are a large number of files and you want to copy all files to x path. So you would find the files and throw output to a file like below:

find /var/* -name *.log > file

How to convert int[] to Integer[] in Java?

Using regular for-loop without external libraries:

Convert int[] to Integer[]:

int[] primitiveArray = {1, 2, 3, 4, 5};
Integer[] objectArray = new Integer[primitiveArray.length];

for(int ctr = 0; ctr < primitiveArray.length; ctr++) {
    objectArray[ctr] = Integer.valueOf(primitiveArray[ctr]); // returns Integer value
}

Convert Integer[] to int[]:

Integer[] objectArray = {1, 2, 3, 4, 5};
int[] primitiveArray = new int[objectArray.length];

for(int ctr = 0; ctr < objectArray.length; ctr++) {
    primitiveArray[ctr] = objectArray[ctr].intValue(); // returns int value
}

Efficient way to determine number of digits in an integer

The ppc architecture has a bit counting instruction. With that, you can determine the log base 2 of a positive integer in a single instruction. For example, 32 bit would be:

#define log_2_32_ppc(x) (31-__cntlzw(x))

If you can handle a small margin of error on large values you can convert that to log base 10 with another few instructions:

#define log_10_estimate_32_ppc(x) (9-(((__cntlzw(x)*1233)+1545)>>12))

This is platform specific and slightly inaccurate, but also involves no branches, division or conversion to floating point. All depends on what you need.

I only know the ppc instructions off hand, but other architectures should have similar instructions.

Convert dictionary to bytes and back again python?

If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.

For example:

my_dict = {'key' : [1,2,3]}

import json
def dict_to_binary(the_dict):
    str = json.dumps(the_dict)
    binary = ' '.join(format(ord(letter), 'b') for letter in str)
    return binary


def binary_to_dict(the_binary):
    jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
    d = json.loads(jsn)  
    return d

bin = dict_to_binary(my_dict)
print bin

dct = binary_to_dict(bin)
print dct

will give the output

1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101

{u'key': [1, 2, 3]}

Oracle 12c Installation failed to access the temporary location

Looking at Oracle's support site, it could be one of two things (may be #2 in your case, but including both).

Problem 1:

  1. Enable administrative share for C$ (Please check with your System Admin to do this or See Microsoft document http://support.microsoft.com/kb/314984)

  2. Check that it is ok:

    • net use \\c$ should work
    • the current user (i.e. user in administrator group) should have all privileges on the default share
  3. Retry the installation

  4. Remove the administrative share again

Problem 2: Remove the OracleRemExecService before doing the Oracle Client 12c Release 1 32-bit or 64-bit installation on the same Microsoft Windows x64 (64-bit) after installing the Oracle 64-bit or 32-bit software .

  • Go to the Windows 'Services'
  • Stop OracleRemExecServiceV2

( This service is having a intelligence .Once someone tries to stop it this service gets deleted. This is due to the fact ,that this service is not running from the Oracle Home like other oracle services ,but from temp . For example : C:\Users\AppData\Local\Temp\oraremservi... )

  • Then try to install the Oracle 12c 32-bit or 64-bit on the same Microsoft Windows x64 (64-bit)

ORA-00932: inconsistent datatypes: expected - got CLOB

Take a substr of the CLOB and then convert it to a char:

UPDATE IMS_TEST 
  SET TEST_Category           = 'just testing' 
WHERE to_char(substr(TEST_SCRIPT, 1, 9))    = 'something'
  AND ID                      = '10000239';

What is the meaning of "$" sign in JavaScript

From the jQuery documentation describing the jQuery Core Object:

Many developers prefix a $ to the name of variables that contain jQuery objects in order to help differentiate. There is nothing magic about this practice – it just helps some people keep track of what different variables contain.

Turn off display errors using file "php.ini"

It's been quite some time and iam sure OP's answer is cleared. If any new user still looking for answer and scrolled this far, then here it is.

Check your updated information in php.ini file

Using Windows explorer:

C/xampp/php/php.ini

Using XAMPP Control Panel

  1. Click the Config button for 'Apache' (Stop | Admin | Config | Logs)
  2. Select PHP (php.ini)

Can i create my own phpinfo()? Yes you can

  1. Create a phpinfo.php in your root directly or anywhere you want
  2. Place this <?php phpinfo(); ?>
  3. Save the file.
  4. Open the file and you should see all the details.

How to set display_errors to Off in my own file without using php.ini

You can do this using ini_set() function. Read more about ini_set() here (https://www.php.net/manual/en/function.ini-set.php)

  1. Go to your header.php or index.php
  2. add this code ini_set('display_errors', FALSE);

To check the output without accessing php.ini file

$displayErrors = (ini_get('display_errors') == 1) ? 'On' : 'Off';
$PHPCore = array(
    'Display error' => $displayErrors
    // add other details for more output
);
foreach ($PHPCore as $key => $value) {
    echo "$key: $value";
}

scp (secure copy) to ec2 instance without password

lets assume that your pem file and somefile.txt you want to send is in Downloads folder

scp -i ~/Downloads/mykey.pem ~/Downloads/somefile.txt [email protected]:~/

let me know if it doesn't work

How to specify test directory for mocha?

If in node.js, some new configurations as of Mocha v6:

Option 1: Create .mocharc.json in project's root directory:

{
  "spec": "path/to/test/files"
}

Option 2: add mocha property in project's package.json:

{
  ...

  "mocha": {
    "spec": "path/to/test/files"
  }
}

More options are here.

Regex Email validation

1

^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$

2

^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$

Hashmap does not work with int, char

Generic parameters can only bind to reference types, not primitive types, so you need to use the corresponding wrapper types. Try HashMap<Character, Integer> instead.

However, I'm having trouble figuring out why HashMap fails to be able to deal with primitive data types.

This is due to type erasure. Java didn't have generics from the beginning so a HashMap<Character, Integer> is really a HashMap<Object, Object>. The compiler does a bunch of additional checks and implicit casts to make sure you don't put the wrong type of value in or get the wrong type out, but at runtime there is only one HashMap class and it stores objects.

Other languages "specialize" types so in C++, a vector<bool> is very different from a vector<my_class> internally and they share no common vector<?> super-type. Java defines things though so that a List<T> is a List regardless of what T is for backwards compatibility with pre-generic code. This backwards-compatibility requirement that there has to be a single implementation class for all parameterizations of a generic type prevents the kind of template specialization which would allow generic parameters to bind to primitives.

Is log(n!) = T(n·log(n))?

Helping you further, where Mick Sharpe left you:

It's deriveration is quite simple: see http://en.wikipedia.org/wiki/Logarithm -> Group Theory

log(n!) = log(n * (n-1) * (n-2) * ... * 2 * 1) = log(n) + log(n-1) + ... + log(2) + log(1)

Think of n as infinitly big. What is infinite minus one? or minus two? etc.

log(inf) + log(inf) + log(inf) + ... = inf * log(inf)

And then think of inf as n.

How to implement and do OCR in a C# project?

I'm using tesseract OCR engine with TessNet2 (a C# wrapper - http://www.pixel-technology.com/freeware/tessnet2/).

Some basic code:

using tessnet2;

...

Bitmap image = new Bitmap(@"u:\user files\bwalker\2849257.tif");
            tessnet2.Tesseract ocr = new tessnet2.Tesseract();
            ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,$-/#&=()\"':?"); // Accepted characters
            ocr.Init(@"C:\Users\bwalker\Documents\Visual Studio 2010\Projects\tessnetWinForms\tessnetWinForms\bin\Release\", "eng", false); // Directory of your tessdata folder
            List<tessnet2.Word> result = ocr.DoOCR(image, System.Drawing.Rectangle.Empty);
            string Results = "";
            foreach (tessnet2.Word word in result)
            {
                Results += word.Confidence + ", " + word.Text + ", " + word.Left + ", " + word.Top + ", " + word.Bottom + ", " + word.Right + "\n";
            }

Node.js Web Application examples/tutorials

DailyJS has a good tutorial (long series of 24 posts) that walks you through all the aspects of building a notepad app (including all the possible extras).

Heres an overview of the tutorial: http://dailyjs.com/2010/11/01/node-tutorial/

And heres a link to all the posts: http://dailyjs.com/tags.html#nodepad

C++ cast to derived class

dynamic_cast should be what you are looking for.

EDIT:

DerivedType m_derivedType = m_baseType; // gives same error

The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.

DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error

You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.

Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):

DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);

If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.

Hope this helps!

Find column whose name contains a specific string

You also can use this code:

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

Build android release apk on Phonegap 3.x CLI

i got this to work by copy pasting the signed app in the same dir as zipalign. It seems that aapt.exe could not find the source file even when given the path. i.e. this did not work zipalign -f -v 4 C:...\CordovaApp-release-unsigned.apk C:...\destination.apk it reached aapt.exeCordovaApp-release-unsigned.apk , froze and upon hitting return 'aapt.exeCordovaApp-release-unsigned.apk' is not recognized as an internal or external command, operable program or batch file. And this did zipalign -f -v 4 CordovaApp-release-unsigned.apk myappname.apk

Import data.sql MySQL Docker Container

Mount your sql-dump under/docker-entrypoint-initdb.d/yourdump.sql utilizing a volume mount

mysql:
  image: mysql:latest
  container_name: mysql-container
  ports:
    - 3306:3306
  volumes:
    - ./dump.sql:/docker-entrypoint-initdb.d/dump.sql
  environment:
    MYSQL_ROOT_PASSWORD: secret
    MYSQL_DATABASE: name_db
    MYSQL_USER: user
    MYSQL_PASSWORD: password

This will trigger an import of the sql-dump during the start of the container, see https://hub.docker.com/_/mysql/ under "Initializing a fresh instance"

Is there any way to return HTML in a PHP function? (without building the return value as a string)

If you don't want to have to rely on a third party tool you can use this technique:

function TestBlockHTML($replStr){
  $template = 
   '<html>
     <body>
       <h1>$str</h1>
     </body>
   </html>';
 return strtr($template, array( '$str' => $replStr));
}

Regex pattern for checking if a string starts with a certain substring?

The StartsWith method will be faster, as there is no overhead of interpreting a regular expression, but here is how you do it:

if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...

The ^ mathes the start of the string. You can put any protocols between the parentheses separated by | characters.

edit:

Another approach that is much faster, is to get the start of the string and use in a switch. The switch sets up a hash table with the strings, so it's faster than comparing all the strings:

int index = theString.IndexOf(':');
if (index != -1) {
  switch (theString.Substring(0, index)) {
    case "mailto":
    case "ftp":
    case "joe":
      // do something
      break;
  }
}

Passing arguments to require (when loading module)

I'm not sure if this will still be useful to people, but with ES6 I have a way to do it that I find clean and useful.

class MyClass { 
  constructor ( arg1, arg2, arg3 )
  myFunction1 () {...}
  myFunction2 () {...}
  myFunction3 () {...}
}

module.exports = ( arg1, arg2, arg3 ) => { return new MyClass( arg1,arg2,arg3 ) }

And then you get your expected behaviour.

var MyClass = require('/MyClass.js')( arg1, arg2, arg3 )

How to set an environment variable in a running docker container

I solve this problem with docker commit after some modifications in the base container, we only need to tag the new image and start that one

docs.docker.com/engine/reference/commandline/commit

docker commit [container-id] [tag]

docker commit b0e71de98cb9 stack-overflow:0.0.1

then you can pass environment vars or file

docker run --env AWS_ACCESS_KEY_ID --env AWS_SECRET_ACCESS_KEY --env AWS_SESSION_TOKEN --env-file env.local -p 8093:8093 stack-overflow:0.0.1

sed command with -i option failing on Mac, but works on Linux

I've created a function to handle sed difference between MacOS (tested on MacOS 10.12) and other OS:

OS=`uname`
# $(replace_in_file pattern file)
function replace_in_file() {
    if [ "$OS" = 'Darwin' ]; then
        # for MacOS
        sed -i '' -e "$1" "$2"
    else
        # for Linux and Windows
        sed -i'' -e "$1" "$2"
    fi
}

Usage:

$(replace_in_file 's,MASTER_HOST.*,MASTER_HOST='"$MASTER_IP"',' "./mysql/.env")

Where:

, is a delimeter

's,MASTER_HOST.*,MASTER_HOST='"$MASTER_IP"',' is pattern

"./mysql/.env" is path to file

Autoincrement VersionCode with gradle extra properties

To increment versionCode only in release version do it:

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    def versionPropsFile = file('version.properties')
    def code = 1;
    if (versionPropsFile.canRead()) {
        def Properties versionProps = new Properties()

        versionProps.load(new FileInputStream(versionPropsFile))
        List<String> runTasks = gradle.startParameter.getTaskNames();
        def value = 0
        for (String item : runTasks)
        if ( item.contains("assembleRelease")) {
            value = 1;
        }
        code = Integer.parseInt(versionProps['VERSION_CODE']).intValue() + value
        versionProps['VERSION_CODE']=code.toString()
        versionProps.store(versionPropsFile.newWriter(), null)
    }
    else {
        throw new GradleException("Could not read version.properties!")
    }

    defaultConfig {
        applicationId "com.pack"
        minSdkVersion 14
        targetSdkVersion 21
        versionName "1.0."+ code
        versionCode code
    }

expects an existing c://YourProject/app/version.properties file, which you would create by hand before the first build to have VERSION_CODE=8

File version.properties:

VERSION_CODE=8

jQuery replace one class with another

Create a class in your CSS file:

.active {
  z-index: 20;
  background: rgb(23,55,94)
  color: #fff;
}

Then in your jQuery

$(this).addClass("active");

Using an attribute of the current class instance as a default value for method's parameter

It's written as:

def my_function(self, param_one=None): # Or custom sentinel if None is vaild
    if param_one is None:
        param_one = self.one_of_the_vars

And I think it's safe to say that will never happen in Python due to the nature that self doesn't really exist until the function starts... (you can't reference it, in its own definition - like everything else)

For example: you can't do d = {'x': 3, 'y': d['x'] * 5}

MySQL Great Circle Distance (Haversine formula)

$greatCircleDistance = acos( cos($latitude0) * cos($latitude1) * cos($longitude0 - $longitude1) + sin($latitude0) * sin($latitude1));

with latitude and longitude in radian.

so

SELECT 
  acos( 
      cos(radians( $latitude0 ))
    * cos(radians( $latitude1 ))
    * cos(radians( $longitude0 ) - radians( $longitude1 ))
    + sin(radians( $latitude0 )) 
    * sin(radians( $latitude1 ))
  ) AS greatCircleDistance 
 FROM yourTable;

is your SQL query

to get your results in Km or miles, multiply the result with the mean radius of Earth (3959 miles,6371 Km or 3440 nautical miles)

The thing you are calculating in your example is a bounding box. If you put your coordinate data in a spatial enabled MySQL column, you can use MySQL's build in functionality to query the data.

SELECT 
  id
FROM spatialEnabledTable
WHERE 
  MBRWithin(ogc_point, GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'))

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

That looks like unix file permissions modes to me (755=rwxr-xr-x, 644=rw-r--r--) - the old mode included the +x (executable) flag, the new mode doesn't.

This msysgit issue's replies suggests setting core.filemode to false in order to get rid of the issue:

git config core.filemode false

In WPF, what are the differences between the x:Name and Name attributes?

The only difference is that if you are using user Controls into a control from Same Assembly then Name will not identify your control and you will get an error " Use x:Name for controls in the same Assembly". So x:Name is the WPF versioning of naming controls in WPF. Name is just used as a Winform Legacy. They wanted to differentiate the naming of controls in WPF and winforms as they use attributes in Xaml to identify controls from other assemblies they used x: for Names of control.

Just keep in mind dont put a name for a control just for the sake of keeping it as it resides in memory as a blank and it will give you a warning that Name has been applied for a control buts its never used.

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

I believe another solution to this problem would be use to variables of type long instead of int.

I was just working on some code where the % operator was returning a negative value which caused some issues (for generating uniform random variables on [0,1] you don't really want negative numbers :) ), but after switching the variables to type long, everything was running smoothly and the results matched the ones I was getting when running the same code in python (important for me as I wanted to be able to generate the same "random" numbers across several platforms.

AngularJs event to call after content is loaded

var myTestApp = angular.module("myTestApp", []); 
myTestApp.controller("myTestController", function($scope, $window) {
$window.onload = function() {
 alert("is called on page load.");
};
});

What is HEAD in Git?

As a concept, the head is the latest revision in a branch. If you have more than one head per named branch you probably created it when doing local commits without merging, effectively creating an unnamed branch.

To have a "clean" repository, you should have one head per named branch and always merge to a named branch after you worked locally.

This is also true for Mercurial.

Conditionally Remove Dataframe Rows with R

Use the which function:

A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)

r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]

How to get the mysql table columns data type?

SHOW COLUMNS FROM mytable

Self contained complete examples are often useful.

<?php
  // The server where your database is hosted                 localhost
  // The name of your database                                mydatabase
  // The user name of the database user                       databaseuser
  // The password of the database user                        thesecretpassword
  // Most web pages are in utf-8 so should be the database    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
  try
  {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "databaseuser", "thesecretpassword", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));  
  }
    catch(PDOException $e)
  {
    die('Could not connect: ' . $e->getMessage());
  }

  $sql   = "SHOW COLUMNS FROM mytable";
  $query = $pdo->prepare($sql);
  $query->execute();

  $err = $query->errorInfo();
  $bug = $err[2];

  if ($bug != "") { echo "<p>$bug</p>"; }

  while ($row = $query->fetch(PDO::FETCH_ASSOC))
  {
    echo "<pre>" . print_r($row, true) . "</pre>";
  }

  /* OUTPUT SAMPLE  
  Array
  (
      [Field] => page_id
      [Type] => char(40)
      [Null] => NO
      [Key] => 
      [Default] => 
      [Extra] => 
  )

  Array
  (  
      [Field] => last_name
      [Type] => char(50)
      More ...
  */
?>

How to show a confirm message before delete?

function del_confirm(msg,url)
        {
            if(confirm(msg))
            {
                window.location.href=url
            }
            else
            {
                false;
            }

        }



<a  onclick="del_confirm('Are you Sure want to delete this record?','<filename>.php?action=delete&id=<?<id> >')"href="#"></a>

How to compare only date components from DateTime in EF?

NOTE: at the time of writing this answer, the EF-relation was unclear (that was edited into the question after this was written). For correct approach with EF, check Mandeeps answer.


You can use the DateTime.Date property to perform a date-only comparison.

DateTime a = GetFirstDate();
DateTime b = GetSecondDate();

if (a.Date.Equals(b.Date))
{
    // the dates are equal
}

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

How to shutdown my Jenkins safely?

Immediately shuts down Jenkins server.

In Windows CMD.exe, Go to folder where jenkins-cli.jar file is located.

C:\Program Files (x86)\Jenkins\war\WEB-INF

Use Command to Safely Shutdown

java -jar jenkins-cli.jar -s http://localhost:8080 safe-shutdown --username "YourUsername" 
--password "YourPassword"

The full list of commands is available at http://localhost:8080/cli

Credits to Francisco post for cli commands.

Reference:

1.

Hope helps someone.

Use dynamic variable names in JavaScript

Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.

// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000;  // in a function we use "this";
alert(article_count);

Maven: mvn command not found

  1. Run 'path' in command prompt and ensure that the maven installation directory is listed.
  2. Ensure the maven is installed in 'C:\Program Files\Maven'.

Python, Matplotlib, subplot: How to set the axis range?

Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes or AxesSubplot object. The functions of interest are set_autoscale_on, set_autoscalex_on, and set_autoscaley_on.

In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on property to False. Here is a modified version of the FFT subplot snippet from your code:

fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))

JavaScript string encryption and decryption?

Simple functions,


function Encrypt(value) 
{
  var result="";
  for(i=0;i<value.length;i++)
  {
    if(i<value.length-1)
    {
        result+=value.charCodeAt(i)+10;
        result+="-";
    }
    else
    {
        result+=value.charCodeAt(i)+10;
    }
  }
  return result;
}
function Decrypt(value)
{
  var result="";
  var array = value.split("-");

  for(i=0;i<array.length;i++)
  {
    result+=String.fromCharCode(array[i]-10);
  }
  return result;
} 

How to iterate object keys using *ngFor

If you are using a map() operator on your response,you could maybe chain a toArray() operator to it...then you should be able to iterate through newly created array...at least that worked for me :)

Converting two lists into a matrix

The standard numpy function for what you want is np.column_stack:

>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
       [2, 5],
       [3, 6]])

So with your portfolio and index arrays, doing

np.column_stack((portfolio, index))

would yield something like:

[[portfolio_value1, index_value1],
 [portfolio_value2, index_value2],
 [portfolio_value3, index_value3],
 ...]

Find all storage devices attached to a Linux machine

Modern linux systems will normally only have entries in /dev for devices that exist, so going through hda* and sda* as you suggest would work fairly well.

Otherwise, there may be something in /proc you can use. From a quick look in there, I'd have said /proc/partitions looks like it could do what you need.