Programs & Examples On #Sfml

SFML (Simple Fast Multimedia Library) is a portable and easy to use multimedia API written in C++. You can see it as a modern, object-oriented alternative to SDL. SFML is composed of several packages to perfectly suit your needs. You can use SFML as a minimal windowing system to interface with OpenGL, or as a fully-featured multimedia library for building games or interactive programs.

How to call on a function found on another file?

Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.

Perhaps declare it above your first while?

PHP to search within txt file and echo the whole line

Do it like this. This approach lets you search a file of any size (big size won't crash the script) and will return ALL lines that match the string you want.

<?php
$searchthis = "mystring";
$matches = array();

$handle = @fopen("path/to/inputfile.txt", "r");
if ($handle)
{
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $searchthis) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);
}

//show results:
print_r($matches);
?>

Note the way strpos is used with !== operator.

Adding value to input field with jQuery

You have to escape [ and ]. Try this:

$('.button').click(function(){
    var fieldID = $(this).prev().attr("id");
    fieldID = fieldID.replace(/([\[\]]+)/g, "\\$1");
    $('#' + fieldID).val("hello world");
});

Demo: http://jsfiddle.net/7RJtf/1/

How can I use UserDefaults in Swift?

I saved NSDictionary normally and able to get it correctly.

 dictForaddress = placemark.addressDictionary! as NSDictionary
        let userDefaults = UserDefaults.standard
        userDefaults.set(dictForaddress, forKey:Constants.kAddressOfUser)

// For getting data from NSDictionary.

let userDefaults = UserDefaults.standard
    let dictAddress = userDefaults.object(forKey: Constants.kAddressOfUser) as! NSDictionary

Reactjs setState() with a dynamic key name?

I just wanted to add, that you can also use de-structuring to refactor the code and make it look neater.

inputChangeHandler: function ({ target: { id, value }) {
    this.setState({ [id]: value });
},

Html helper for <input type="file" />

This is a little hacky I guess, but it results in the correct validation attributes etc being applied

@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))

Accessing MVC's model property from Javascript

You could take your entire server-side model and turn it into a Javascript object by doing the following:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

How to get the Parent's parent directory in Powershell?

If you want to use $PSScriptRoot you can do

Join-Path -Path $PSScriptRoot -ChildPath ..\.. -Resolve

Angular JS POST request not sending JSON data

$http({
    url: '/api/user',
    method: "POST",
    data: angular.toJson(yourData)
}).success(function (data, status, headers, config) {
    $scope.users = data.users;
}).error(function (data, status, headers, config) {
    $scope.status = status + ' ' + headers;
});

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.

To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.


Prophylactic measures to prevent you getting the error again

The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.

Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.


Common syntactic mistakes that generate these errors

Mismatched parentheses, braces or brackets

If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.

{}}
## Error: unexpected '}' in "{}}"
{{}} # OK

Missing * when doing multiplication

This is a common mistake by mathematicians.

5x
Error: unexpected symbol in "5x"
5*x # OK

Not wrapping if, for, or return values in parentheses

This is a common mistake by MATLAB users. In R, if, for, return, etc., are functions, so you need to wrap their contents in parentheses.

if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK

Not using multiple lines for code

Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.

x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK

else starting on a new line

In an if-else statement, the keyword else must appear on the same line as the end of the if block.

if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"    
if(TRUE) 1 else 2 # OK
if(TRUE) 
{
  1
} else            # also OK
{
  2
}

= instead of ==

= is used for assignment and giving values to function arguments. == tests two values for equality.

if(x = 0) {}
## Error: unexpected '=' in "if(x ="    
if(x == 0) {} # OK

Missing commas between arguments

When calling a function, each argument must be separated by a comma.

c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK

Not quoting file paths

File paths are just strings. They need to be wrapped in double or single quotes.

path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK

Quotes inside strings

This is a common problem when trying to pass quoted values to the shell via system, or creating quoted xPath or sql queries.

Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.

"x"y"
## Error: unexpected symbol in ""x"y"   
"x\"y" # OK
'x"y'  # OK  

Using curly quotes

So-called "smart" quotes are not so smart for R programming.

path.expand(“~”)
## Error: unexpected input in "path.expand(“"    
path.expand("~") # OK

Using non-standard variable names without backquotes

?make.names describes what constitutes a valid variable name. If you create a non-valid variable name (using assign, perhaps), then you need to access it with backquotes,

assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK

This also applies to column names in data frames created with check.names = FALSE.

dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y`   # also OK

It also applies when passing operators and other special values to functions. For example, looking up help on %in%.

?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK

Sourcing non-R code

The source function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table.

source(textConnection("x y"))
## Error in source(textConnection("x y")) : 
##   textConnection("x y"):1:3: unexpected symbol
## 1: x y
##       ^

Corrupted RStudio desktop file

RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.


Using expression without paste in mathematical plot annotations

When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath page. Otherwise the contents should be contained inside a call to paste.

plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK

VSCode: How to Split Editor Vertically

Press CMD + SHIFT + P (MAC) and search for Toggle Editor Group

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.setAttribute("onclick", "removeColumn(#)");
newTH.setAttribute("id", "#");

function removeColumn(#){
// remove column #
}

Get the system date and split day, month and year

Here is what you are looking for:

String sDate = DateTime.Now.ToString();
DateTime datevalue = (Convert.ToDateTime(sDate.ToString()));

String dy = datevalue.Day.ToString();
String mn = datevalue.Month.ToString();
String yy = datevalue.Year.ToString();

OR

Alternatively, you can use split function to split string date into day, month and year here.

Hope, it will helps you... Cheers. !!

How to generate a GUID in Oracle?

I would recommend using Oracle's "dbms_crypto.randombytes" function.

Why?
This function returns a RAW value containing a cryptographically secure pseudo-random sequence of bytes, which can be used to generate random material for encryption keys.

select REGEXP_REPLACE(dbms_crypto.randombytes(16), '(.{8})(.{4})(.{4})(.{4})(.{12})', '\1-\2-\3-\4-\5') from dual;

You should not use the function "sys_guid" because only one character changes.

ALTER TABLE locations ADD (uid_col RAW(16));

UPDATE locations SET uid_col = SYS_GUID();

SELECT location_id, uid_col FROM locations
   ORDER BY location_id, uid_col;

LOCATION_ID UID_COL
----------- ----------------------------------------------------------------
       1000 09F686761827CF8AE040578CB20B7491
       1100 09F686761828CF8AE040578CB20B7491
       1200 09F686761829CF8AE040578CB20B7491
       1300 09F68676182ACF8AE040578CB20B7491
       1400 09F68676182BCF8AE040578CB20B7491
       1500 09F68676182CCF8AE040578CB20B7491

https://docs.oracle.com/database/121/SQLRF/functions202.htm#SQLRF06120

How to convert a normal Git repository to a bare one?

In case you have a repository with few local checkedout branches /refs/heads/* and few remote branch branches remotes/origin/* AND if you want to convert this into a BARE repository with all branches in /refs/heads/*

you can do the following to save the history.

  1. create a bare repository
  2. cd into the local repository which has local checkedout branches and remote branches
  3. git push /path/to/bare/repo +refs/remotes/origin/:refs/heads/

How to force deletion of a python object?

  1. Add an exit handler that closes all the bars.
  2. __del__() gets called when the number of references to an object hits 0 while the VM is still running. This may be caused by the GC.
  3. If __init__() raises an exception then the object is assumed to be incomplete and __del__() won't be invoked.

Converting Python dict to kwargs?

Here is a complete example showing how to use the ** operator to pass values from a dictionary as keyword arguments.

>>> def f(x=2):
...     print(x)
... 
>>> new_x = {'x': 4}
>>> f()        #    default value x=2
2
>>> f(x=3)     #   explicit value x=3
3
>>> f(**new_x) # dictionary value x=4 
4

What is the right way to populate a DropDownList from a database?

((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;

ECONNREFUSED error when connecting to mongodb from node.js

I had the same issue, all I did was add a setTimeout of about 10 seconds before trying to connect to the Mongo server and it solved the issue right up. I dont know why I had to add a delay but it worked...

Binding objects defined in code-behind

Define a converter:

public class RowIndexConverter : IValueConverter
{
    public object Convert( object value, Type targetType,
                           object parameter, CultureInfo culture )
    {
        var row = (IDictionary<string, object>) value;
        var key = (string) parameter;
        return row.Keys.Contains( key ) ? row[ key ] : null;
    }

    public object ConvertBack( object value, Type targetType,
                               object parameter, CultureInfo culture )
    {
        throw new NotImplementedException( );
    }
}

Bind to a custom definition of a Dictionary. There's lot of overrides that I've omitted, but the indexer is the important one, because it emits the property changed event when the value is changed. This is required for source to target binding.

public class BindableRow : INotifyPropertyChanged, IDictionary<string, object>
{
    private Dictionary<string, object> _data = new Dictionary<string, object>( );

    public object Dummy   // Provides a dummy property for the column to bind to
    {
        get
        {
            return this;
        }
        set
        {
            var o = value;
        }
    }


    public object this[ string index ]
    {
        get
        {
            return _data[ index ];
        }
        set
        {
            _data[ index ] = value;
            InvokePropertyChanged( new PropertyChangedEventArgs( "Dummy" ) ); // Trigger update
        }
    }


}

In your .xaml file use this converter. First reference it:

<UserControl.Resources>
    <ViewModelHelpers:RowIndexConverter x:Key="RowIndexConverter"/>
</UserControl.Resources>

Then, for instance, if your dictionary has an entry where the key is "Name", then to bind to it: use

<TextBlock  Text="{Binding Dummy, Converter={StaticResource RowIndexConverter}, ConverterParameter=Name}">

Key hash for Android-Facebook app

In Android Studio just click on right sidebar panel "Gradle" to show gardel panel then: -YOURAPPNAME --Task ---Android ----(double click) signingReport (to start Gradle Daemon)

then you will see result:

Config: debug
Store: C:\Users\username\.android\debug.keystore
Alias: AndroidDebugKey
MD5: C8:46:01:EA:36:02:D1:21:1B:23:19:91:D4:32:CB:AC
SHA1: 38:AB:4C:01:01:D7:62:E0:61:D1:9F:52:04:0C:E5:07:4E:E4:9B:39
SHA-256: 1B:8C:DC:35:48:10:01:2C:1F:BD:01:64:F1:01:06:01:60:01:A6:8B:10:15:2E:BF:7B:C4:FD:38:4C:C1:74:01
Valid until: Saturday, February 12, 2050

copy SHA1:

38:AB:4C:01:01:D7:62:E0:68:D1:9F:52:04:0C:E5:07:4E:E4:9B:39

go to this PAGE

Paste SHA1 and generate your Facebook key hash code.

python how to pad numpy array with zeros

Tensorflow also implemented functions for resizing/padding images tf.image.pad tf.pad.

padded_image = tf.image.pad_to_bounding_box(image, top_padding, left_padding, target_height, target_width)

padded_image = tf.pad(image, paddings, "CONSTANT")

These functions work just like other input-pipeline features of tensorflow and will work much better for machine learning applications.

Adding a custom header to HTTP request using angular.js

Basic authentication using HTTP POST method:

$http({
    method: 'POST',
    url: '/API/authenticate',
    data: 'username=' + username + '&password=' + password + '&email=' + email,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Login-Ajax-call": 'true'
    }
}).then(function(response) {
    if (response.data == 'ok') {
        // success
    } else {
        // failed
    }
});

...and GET method call with header:

$http({
    method: 'GET',
    url: '/books',
    headers: {
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json',
        "X-Login-Ajax-call": 'true'
    }
}).then(function(response) {
    if (response.data == 'ok') {
        // success
    } else {
        // failed
    }
});

Invoke a second script with arguments from a script

Aha. This turned out to be a simple problem of there being spaces in the path to the script.

Changing the Invoke-Expression line to:

Invoke-Expression "& `"$scriptPath`" $argumentList"

...was enough to get it to kick off. Thanks to Neolisk for your help and feedback!

Creating executable files in Linux

Make file executable:

chmod +x file

Find location of perl:

which perl

This should return something like

/bin/perl sometimes /usr/local/bin

Then in the first line of your script add:

#!"path"/perl with path from above e.g.

#!/bin/perl

Then you can execute the file

./file

There may be some issues with the PATH, so you may want to change that as well ...

Different CURRENT_TIMESTAMP and SYSDATE in oracle

  1. SYSDATE, systimestamp return datetime of server where database is installed. SYSDATE - returns only date, i.e., "yyyy-mm-dd". systimestamp returns date with time and zone, i.e., "yyyy-mm-dd hh:mm:ss:ms timezone"
  2. now() returns datetime at the time statement execution, i.e., "yyyy-mm-dd hh:mm:ss"
  3. CURRENT_DATE - "yyyy-mm-dd", CURRENT_TIME - "hh:mm:ss", CURRENT_TIMESTAMP - "yyyy-mm-dd hh:mm:ss timezone". These are related to a record insertion time.

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

This is a problem with your web server sending out an HTTP header that does not match the one you define. For instructions on how to make the server send the correct headers, see this page.

Otherwise, you can also use PHP to modify the headers, but this has to be done before outputting any text using this code:

header('Content-Type: text/html; charset=utf-8');

More information on how to send out headers using PHP can be found in the documentation for the header function.

'tuple' object does not support item assignment

You probably want the next transformation for you pixels:

pixels = map(list, image.getdata())

Preventing console window from closing on Visual Studio C/C++ Console application

You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:

int a = 0;
scanf("%d",&a);

return YOUR_MAIN_CODE;

and this way the window would not close until you enter data for the a variable.

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

I just got my GUC232A cable with a molded-in PL2302 converter chip.

In addition to adding myself and br to group dialout, I found this helpful tip in the README.Debian file in /usr/share/doc/bottlerocket:

This package uses debconf to configure the /dev/firecracker symlink, should you need to change the symlink in the future run this command:

dpkg-reconfigure -pmedium bottlerocket

That will then prompt you for your new serial port and modify the symlink. This is required for proper use of bottlerocket.

I did that and voila! bottlerocket is able to communicate with my X-10 devices.

How to check empty DataTable

Normally when querying a database with SQL and then fill a data-table with its results, it will never be a null Data table. You have the column headers filled with column information even if you returned 0 records.When one tried to process a data table with 0 records but with column information it will throw exception.To check the datatable before processing one could check like this.

if (DetailTable != null && DetailTable.Rows.Count>0)

Boxplot in R showing the mean

Check chart.Boxplot from package PerformanceAnalytics. It lets you define the symbol to use for the mean of the distribution.

By default, the chart.Boxplot(data) command adds the mean as a red circle and the median as a black line.

Here is the output with sample data; MWE:

#install.packages(PerformanceAnalytics)    
library(PerformanceAnalytics)
chart.Boxplot(cars$speed)

picture of a boxplot using performance analytics package

npm - how to show the latest version of a package

You can see all the version of a module with npm view. eg: To list all versions of bootstrap including beta.

npm view bootstrap versions

But if the version list is very big it will truncate. An --json option will print all version including beta versions as well.

npm view bootstrap versions --json

If you want to list only the stable versions not the beta then use singular version

npm view bootstrap@* versions

Or

npm view bootstrap@* versions --json

And, if you want to see only latest version then here you go.

npm view bootstrap version

How to create and use resources in .NET

The above method works good.

Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.

To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).

To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name]).

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

Return a `struct` from a function in C

yes, it is possible we can pass structure and return structure as well. You were right but you actually did not pass the data type which should be like this struct MyObj b = a.

Actually I also came to know when I was trying to find out a better solution to return more than one values for function without using pointer or global variable.

Now below is the example for the same, which calculate the deviation of a student marks about average.

#include<stdio.h>
struct marks{
    int maths;
    int physics;
    int chem;
};

struct marks deviation(struct marks student1 , struct marks student2 );

int main(){

    struct marks student;
    student.maths= 87;
    student.chem = 67;
    student.physics=96;

    struct marks avg;
    avg.maths= 55;
    avg.chem = 45;
    avg.physics=34;
    //struct marks dev;
    struct marks dev= deviation(student, avg );
    printf("%d %d %d" ,dev.maths,dev.chem,dev.physics);

    return 0;
 }

struct marks deviation(struct marks student , struct marks student2 ){
    struct marks dev;

    dev.maths = student.maths-student2.maths;
    dev.chem = student.chem-student2.chem;
    dev.physics = student.physics-student2.physics; 

    return dev;
}

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

Pandas: Appending a row to a dataframe and specify its index label

The name of the Series becomes the index of the row in the DataFrame:

In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])

In [100]: s = df.xs(3)

In [101]: s.name = 10

In [102]: df.append(s)
Out[102]: 
           A         B         C         D
0  -2.083321 -0.153749  0.174436  1.081056
1  -1.026692  1.495850 -0.025245 -0.171046
2   0.072272  1.218376  1.433281  0.747815
3  -0.940552  0.853073 -0.134842 -0.277135
4   0.478302 -0.599752 -0.080577  0.468618
5   2.609004 -1.679299 -1.593016  1.172298
6  -0.201605  0.406925  1.983177  0.012030
7   1.158530 -2.240124  0.851323 -0.240378
10 -0.940552  0.853073 -0.134842 -0.277135

Cocoa: What's the difference between the frame and the bounds?

The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).

The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.

So, imagine a view that has a size of 100x100 (width x height) positioned at 25,25 (x,y) of its superview. The following code prints out this view's bounds and frame:

// This method is in the view controller of the superview
- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"bounds.origin.x: %f", label.bounds.origin.x);
    NSLog(@"bounds.origin.y: %f", label.bounds.origin.y);
    NSLog(@"bounds.size.width: %f", label.bounds.size.width);
    NSLog(@"bounds.size.height: %f", label.bounds.size.height);

    NSLog(@"frame.origin.x: %f", label.frame.origin.x);
    NSLog(@"frame.origin.y: %f", label.frame.origin.y);
    NSLog(@"frame.size.width: %f", label.frame.size.width);
    NSLog(@"frame.size.height: %f", label.frame.size.height);
}

And the output of this code is:

bounds.origin.x: 0
bounds.origin.y: 0
bounds.size.width: 100
bounds.size.height: 100

frame.origin.x: 25
frame.origin.y: 25
frame.size.width: 100
frame.size.height: 100

So, we can see that in both cases, the width and the height of the view is the same regardless of whether we are looking at the bounds or frame. What is different is the x,y positioning of the view. In the case of the bounds, the x and y coordinates are at 0,0 as these coordinates are relative to the view itself. However, the frame x and y coordinates are relative to the position of the view within the parent view (which earlier we said was at 25,25).

There is also a great presentation that covers UIViews. See slides 1-20 which not only explain the difference between frames and bounds but also show visual examples.

Create, read, and erase cookies with jQuery

Use JavaScript Cookie plugin

Set a cookie

Cookies.set("example", "foo"); // Sample 1
Cookies.set("example", "foo", { expires: 7 }); // Sample 2
Cookies.set("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie

alert( Cookies.get("example") );

Delete the cookie

Cookies.remove("example");
Cookies.remove('example', { path: '/admin' }) // Must specify path if used when setting.

How to remove specific elements in a numpy array

There is a numpy built-in function to help with that.

import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
>>> c
array([1, 2, 5, 6, 8, 9])

How to see my Eclipse version?

Go to the folder in which eclipse is installed then open readme folder followed by the readme txt file. Here you will find all the info you need.

Body set to overflow-y:hidden but page is still scrollable in Chrome

Try this when you want to "fix" your body's scroll:

jQuery('body').css('height', '100vh').css('overflow-y', 'hidden');

and this when you want to turn it normal again:

jQuery('body').css('height', '').css('overflow-y', '');

grabbing first row in a mysql query only

To return only one row use LIMIT 1:

SELECT *
FROM tbl_foo
WHERE name = 'sarmen'
LIMIT 1

It doesn't make sense to say 'first row' or 'last row' unless you have an ORDER BY clause. Assuming you add an ORDER BY clause then you can use LIMIT in the following ways:

  • To get the first row use LIMIT 1.
  • To get the 2nd row you can use limit with an offset: LIMIT 1, 1.
  • To get the last row invert the order (change ASC to DESC or vice versa) then use LIMIT 1.

Clear git local cache

after that change in git-ignore file run this command , This command will remove all file cache not the files or changes

git rm -r --cached .

after execution of this command commit the files

for removing single file or folder from cache use this command

git rm --cached filepath/foldername

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);

Note: the hash is important!

Removing multiple classes (jQuery)

There are many ways can do that!

jQuery

  1. remove all class
    $("element").removeClass();
    OR
    $("#item").removeAttr('class');
    OR
    $("#item").attr('class', '');
    OR
    $('#item')[0].className = '';

  2. remove multi class
    $("element").removeClass("class1 ... classn");
    OR
    $("element").removeClass("class1").removeClass("...").removeClass("classn");

Vanilla Javascript

  1. remove all class

_x000D_
_x000D_
// remove all items all class  _x000D_
const items = document.querySelectorAll('item');_x000D_
for (let i = 0; i < items.length; i++) {_x000D_
    items[i].className = '';_x000D_
}
_x000D_
_x000D_
_x000D_

  1. remove multi class

_x000D_
_x000D_
// only remove all class of first item_x000D_
const item1 = document.querySelector('item');_x000D_
item1.className = '';
_x000D_
_x000D_
_x000D_

Oracle "Partition By" Keyword

EMPNO     DEPTNO DEPT_COUNT

 7839         10          4
 5555         10          4
 7934         10          4
 7782         10          4 --- 4 records in table for dept 10
 7902         20          4
 7566         20          4
 7876         20          4
 7369         20          4 --- 4 records in table for dept 20
 7900         30          6
 7844         30          6
 7654         30          6
 7521         30          6
 7499         30          6
 7698         30          6 --- 6 records in table for dept 30

Here we are getting count for respective deptno. As for deptno 10 we have 4 records in table emp similar results for deptno 20 and 30 also.

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

There are several ways to try to prevent line breaks, and the phrase “a newer construct” might refer to more than one way—that’s actually the most reasonable interpretation. They probably mostly think of the CSS declaration white-space:nowrap and possibly the no-break space character. The different ways are not equivalent, far from that, both in theory and especially in practice, though in some given case, different ways might produce the same result.

There is probably nothing real to be gained by switching from the HTML attribute to the somewhat clumsier CSS way, and you would surely lose when style sheets are disabled. But even the nowrap attribute does no work in all situations. In general, what works most widely is the nobr markup, which has never made its way to any specifications but is alive and kicking: <td><nobr>...</nobr></td>.

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Give full access of .composer to user.

sudo chown -R 'user-name' /home/'user-name'/.composer

or

sudo chmod 777 -R /home/'user-name'/.composer

user-name is your system user-name.

to get user-name type "whoami" in terminal:

enter image description here

"commence before first target. Stop." error

It's a simple Mistake while adding a new file you just have to make sure that \ is added to the file before and the new file remain as it is eg.

Check Out what to do if i want to add a new file named customer.cc

Turning off eslint rule for a specific line

Or for multiple ignores on the next line, string the rules using commas

// eslint-disable-next-line class-methods-use-this, no-unused-vars

Java Timer vs ExecutorService?

If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:

ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();

will give you a ScheduledExecutorService with similar functionality to Timer (i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer class). Using a ScheduledExecutorService also gives you advantages such as:

  • You can customize it if need be (see the newScheduledThreadPoolExecutor() or the ScheduledThreadPoolExecutor class)
  • The 'one off' executions can return results

About the only reasons for sticking to Timer I can think of are:

  • It is available pre Java 5
  • A similar class is provided in J2ME, which could make porting your application easier (but it wouldn't be terribly difficult to add a common layer of abstraction in this case)

Install dependencies globally and locally using package.json

Due to the disadvantages described below, I would recommend following the accepted answer:

Use npm install --save-dev [package_name] then execute scripts with:

$ npm run lint
$ npm run build
$ npm test

My original but not recommended answer follows.


Instead of using a global install, you could add the package to your devDependencies (--save-dev) and then run the binary from anywhere inside your project:

"$(npm bin)/<executable_name>" <arguments>...

In your case:

"$(npm bin)"/node.io --help

This engineer provided an npm-exec alias as a shortcut. This engineer uses a shellscript called env.sh. But I prefer to use $(npm bin) directly, to avoid any extra file or setup.

Although it makes each call a little larger, it should just work, preventing:

  • potential dependency conflicts with global packages (@nalply)
  • the need for sudo
  • the need to set up an npm prefix (although I recommend using one anyway)

Disadvantages:

  • $(npm bin) won't work on Windows.
  • Tools deeper in your dev tree will not appear in the npm bin folder. (Install npm-run or npm-which to find them.)

It seems a better solution is to place common tasks (such as building and minifying) in the "scripts" section of your package.json, as Jason demonstrates above.

How to convert data.frame column from Factor to numeric

breast$class <- as.numeric(as.character(breast$class))

If you have many columns to convert to numeric

indx <- sapply(breast, is.factor)
breast[indx] <- lapply(breast[indx], function(x) as.numeric(as.character(x)))

Another option is to use stringsAsFactors=FALSE while reading the file using read.table or read.csv

Just in case, other options to create/change columns

 breast[,'class'] <- as.numeric(as.character(breast[,'class']))

or

 breast <- transform(breast, class=as.numeric(as.character(breast)))

PLS-00103: Encountered the symbol "CREATE"

Run package declaration and body separately.

CSS height 100% percent not working

I believe you need to make sure that all the container div tags above the 100% height div also has 100% height set on them including the body tag and html.

How to capture Enter key press?

Try this....

HTML inline

onKeydown="Javascript: if (event.keyCode==13) fnsearch();"
or
onkeypress="Javascript: if (event.keyCode==13) fnsearch();"

JavaScript

<script>
function fnsearch()
{
   alert('you press enter');
}
</script>

Passing in class names to react components

With React's support for string interpolation, you could do the following:

class Pill extends React.Component {
    render() {
       return (
          <button className={`pill ${this.props.styleName}`}>{this.props.children}</button>
       );
    }
}

Display loading image while post with ajax

_x000D_
_x000D_
//$(document).ready(function(){_x000D_
//  $("a").click(function(event){_x000D_
//  event.preventDefault();_x000D_
//  $("div").html("This is prevent link...");_x000D_
// });_x000D_
//});   _x000D_
_x000D_
$(document).ready(function(){_x000D_
 $("a").click(function(event){_x000D_
  event.preventDefault();_x000D_
  $.ajax({_x000D_
   beforeSend: function(){_x000D_
    $('#text').html("<img src='ajax-loader.gif' /> Loading...");_x000D_
   },_x000D_
   success : function(){_x000D_
    setInterval(function(){ $('#text').load("cd_catalog.txt"); },1000);_x000D_
   }_x000D_
  });_x000D_
 });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  _x000D_
<a href="http://www.wantyourhelp.com">[click to redirect][1]</a>_x000D_
<div id="text"></div>
_x000D_
_x000D_
_x000D_

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

  1. This error would spring up arbitrarily and caused quite a bit of trouble though the code on my end was solid.

I did the following :

  • I closed it on netbeans.
  • Then open the project by clicking "Open Project", selecting my project and
  • Simply hit the run button in netbeans.

I would not build or clean build it. Hope that helps you out.

  1. I noticed another reason why this happens. If you moved your main class to another package, the same error springs up. In that case you :
    • Right Click Project > Properties > Run
    • Set the "Main Class" correctly by clicking "Browse" and selecting.

How to find all the subclasses of a class given its name?

This isn't as good an answer as using the special built-in __subclasses__() class method which @unutbu mentions, so I present it merely as an exercise. The subclasses() function defined returns a dictionary which maps all the subclass names to the subclasses themselves.

def traced_subclass(baseclass):
    class _SubclassTracer(type):
        def __new__(cls, classname, bases, classdict):
            obj = type(classname, bases, classdict)
            if baseclass in bases: # sanity check
                attrname = '_%s__derived' % baseclass.__name__
                derived = getattr(baseclass, attrname, {})
                derived.update( {classname:obj} )
                setattr(baseclass, attrname, derived)
             return obj
    return _SubclassTracer

def subclasses(baseclass):
    attrname = '_%s__derived' % baseclass.__name__
    return getattr(baseclass, attrname, None)


class BaseClass(object):
    pass

class SubclassA(BaseClass):
    __metaclass__ = traced_subclass(BaseClass)

class SubclassB(BaseClass):
    __metaclass__ = traced_subclass(BaseClass)

print subclasses(BaseClass)

Output:

{'SubclassB': <class '__main__.SubclassB'>,
 'SubclassA': <class '__main__.SubclassA'>}

Extension gd is missing from your system - laravel composer Update

If you are working in PHP version 5.* then you have to install

sudo apt-get install php5-gd

And if you are working in PHP version 7.* then you have to install

sudo apt-get install php7.0-gd

Hope it will work...

And if you are working in PHP version 7.2 then you have to install

sudo apt-get install php7.2-gd... it worked for me

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

Above all answers are right but there is another method also which is very handy.

Pre-condition: Your project is Maven project Or converts it to Maven project.

RightclickOnProject > Configuration > Convert in to Maven Project

enter image description here - Now follow the steps:

1. Select any jar for which you want to download sources or javadocs.

2. RightClick > Maven > Download javadoc or Download javasources

enter image description here

How to find which version of TensorFlow is installed in my system?

The tensorflow version can be checked either on terminal or console or in any IDE editer as well (like Spyder or Jupyter notebook, etc)

Simple command to check version:

(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)

>>> import tensorflow as tf
>>> tf.__version__
'1.13.1'

Extract every nth element of a vector

I think you are asking two things which are not necessarily the same

I want to extract every 6th element of the original

You can do this by indexing a sequence:

foo <- 1:120
foo[1:20*6]

I would like to create a vector in which each element is the i+6th element of another vector.

An easy way to do this is to supplement a logical factor with FALSEs until i+6:

foo <- 1:120
i <- 1
foo[1:(i+6)==(i+6)]
[1]   7  14  21  28  35  42  49  56  63  70  77  84  91  98 105 112 119

i <- 10
foo[1:(i+6)==(i+6)]
[1]  16  32  48  64  80  96 112

Disabled UIButton not faded or grey

just change state config to disable and choose what you want, background Image for disabled state

enter image description here

What is the canonical way to trim a string in Ruby without creating a new string?

Btw, now ruby already supports just strip without "!".

Compare:

p "abc".strip! == " abc ".strip!  # false, because "abc".strip! will return nil
p "abc".strip == " abc ".strip    # true

Also it's impossible to strip without duplicates. See sources in string.c:

static VALUE
rb_str_strip(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_strip_bang(str);
    return str;
}

ruby 1.9.3p0 (2011-10-30) [i386-mingw32]

Update 1: As I see now -- it was created in 1999 year (see rev #372 in SVN):

Update2: strip! will not create duplicates — both in 1.9.x, 2.x and trunk versions.

Difference between break and continue in PHP?

BREAK:

break ends execution of the current for, foreach, while, do-while or switch structure.

CONTINUE:

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

So depending on your need, you can reset the position currently being executed in your code to a different level of the current nesting.

Also, see here for an artical detailing Break vs Continue with a number of examples

Set variable value to array of strings

-- create test table "Accounts"
create table Accounts (
  c_ID int primary key
 ,first_name varchar(100)
 ,last_name varchar(100)
 ,city varchar(100)
 );

insert into Accounts values (101, 'Sebastian', 'Volk', 'Frankfurt' );
insert into Accounts values (102, 'Beate',  'Mueller', 'Hamburg' );
insert into Accounts values (103, 'John',  'Walker', 'Washington' );
insert into Accounts values (104, 'Britney', 'Sears', 'Holywood' );
insert into Accounts values (105, 'Sarah', 'Schmidt', 'Mainz' );
insert into Accounts values (106, 'George', 'Lewis', 'New Jersey' );
insert into Accounts values (107, 'Jian-xin', 'Wang', 'Peking' );
insert into Accounts values (108, 'Katrina', 'Khan', 'Bolywood' );

-- declare table variable
declare @tb_FirstName table(name varchar(100));
insert into  @tb_FirstName values ('John'), ('Sarah'), ('George');

SELECT * 
FROM Accounts
WHERE first_name in (select name from @tb_FirstName);

SELECT * 
FROM Accounts
WHERE first_name not in (select name from @tb_FirstName);
go

drop table Accounts;
go

Remove whitespaces inside a string in javascript

You can use Strings replace method with a regular expression.

"Hello World ".replace(/ /g, "");

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp

RegExp

  • / / - Regular expression matching spaces

  • g - Global flag; find all matches rather than stopping after the first match

_x000D_
_x000D_
const str = "H    e            l l       o  World! ".replace(/ /g, "");_x000D_
document.getElementById("greeting").innerText = str;
_x000D_
<p id="greeting"><p>
_x000D_
_x000D_
_x000D_

tsconfig.json: Build:No inputs were found in config file

You can also try to restart your code editor. That works well too.

Interface type check with Typescript

I would like to point out that TypeScript does not provide a direct mechanism for dynamically testing whether an object implements a particular interface.

Instead, TypeScript code can use the JavaScript technique of checking whether an appropriate set of members are present on the object. For example:

var obj : any = new Foo();

if (obj.someInterfaceMethod) {
    ...
}

Can I redirect the stdout in python into some sort of string buffer?

from cStringIO import StringIO # Python3 use: from io import StringIO
import sys

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

# blah blah lots of code ...

sys.stdout = old_stdout

# examine mystdout.getvalue()

XPath: difference between dot and text()

There is a difference between . and text(), but this difference might not surface because of your input document.

If your input document looked like (the simplest document one can imagine given your XPath expressions)

Example 1

<html>
  <a>Ask Question</a>
</html>

Then //a[text()="Ask Question"] and //a[.="Ask Question"] indeed return exactly the same result. But consider a different input document that looks like

Example 2

<html>
  <a>Ask Question<other/>
  </a>
</html>

where the a element also has a child element other that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"] still returns the a element, while //a[.="Ask Question"] does not return anything!


This is because the meaning of the two predicates (everything between [ and ]) is different. [text()="Ask Question"] actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"] means: return true if the string value of an element is identical to "Ask Question".

In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other element is between "Ask Question" and a newline character that also counts as text content.

To make an even clearer example, consider as an input document:

Example 3

<a>Ask Question<other/>more text</a>

Here, the a element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a. You can test this by running //a/text() on this document, which will return (individual results separated by ----):

Ask Question
-----------------------
more text

So, in such a scenario, text() returns a set of individual nodes, while . in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text'] which will successfully return the a element.


Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()) is given a sequence of nodes, it will only process the first node and silently ignore the rest.

How to get the width and height of an android.widget.ImageView?

I think you can let the Android OS take care of this for you. Set the scale type on the ImageView to fitXY and the image it displays will be sized to fit the current size of the view.

<ImageView 
    android:layout_width="90px" 
    android:layout_height="60px"
    android:scaleType="fitXY" />

How to pass integer from one Activity to another?

It's simple. On the sender side, use Intent.putExtra:

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

On the receiver side, use Intent.getIntExtra:

 Intent mIntent = getIntent();
 int intValue = mIntent.getIntExtra("intVariableName", 0);

How to change XML Attribute

Using LINQ to xml if you are using framework 3.5:

using System.Xml.Linq;

XDocument xmlFile = XDocument.Load("books.xml"); 

var query = from c in xmlFile.Elements("catalog").Elements("book")    
            select c; 

foreach (XElement book in query) 
{
   book.Attribute("attr1").Value = "MyNewValue";
}

xmlFile.Save("books.xml");

How to sort a HashSet?

Just in-case you don't wanna use a TreeSet you could try this.

set = set.stream().sorted().collect(Collectors.toCollection(LinkedHashSet::new));

How do I convert from BLOB to TEXT in MySQL?

SELECCT TO_BASE64(blobfield)  
FROM the Table

worked for me.

The CAST(blobfield AS CHAR(10000) CHARACTER SET utf8) and CAST(blobfield AS CHAR(10000) CHARACTER SET utf16) did not show me the text value I wanted to get.

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Is it possible to change the speed of HTML's <marquee> tag?

There isn't specifically an attribute to control that. Marquee isn't a highly reliable tag anyways. You may want to consider using jQuery and the .animate() function. If you are interested in pursuing that avenue and need code for it, just let me know.

Printing a char with printf

Yes, it prints GARBAGE unless you are lucky.

VERY IMPORTANT.

The type of the printf/sprintf/fprintf argument MUST match the associated format type char.

If the types don't match and it compiles, the results are very undefined.

Many newer compilers know about printf and issue warnings if the types do not match. If you get these warnings, FIX them.

If you want to convert types for arguments for variable functions, you must supply the cast (ie, explicit conversion) because the compiler can't figure out that a conversion needs to be performed (as it can with a function prototype with typed arguments).

printf("%d\n", (int) ch)

In this example, printf is being TOLD that there is an "int" on the stack. The cast makes sure that whatever thing sizeof returns (some sort of long integer, usually), printf will get an int.

printf("%d", (int) sizeof('\n'))

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I encountered this error too, it occurs because %HTTPPORT% isn’t part of the system variables yet.

The solution to this is NOT by manually typing in the url to your browser, which works but you have to keep doing it every single time.

Simply goto “this pc” or “my computer” right click on it and select properties, then select “advanced system settings” When the new window comes up select “Environment Variables...”

Now under system variables click new to create a new system variable. Type HTTPPORT into the variable name text box, Then type 8080 into the variable value text box. Click OK, close the windows and logout!

Thats an important step, make sure you log out. When you log back in, click the get started icon again and it will open without errors.

??

pandas unique values multiple columns

for those of us that love all things pandas, apply, and of course lambda functions:

df['Col3'] = df[['Col1', 'Col2']].apply(lambda x: ''.join(x), axis=1)

Ambiguous overload call to abs(double)

In my cases, I solved the problem when using the labs() instead of abs().

How to quit a java app from within the program

Runtime.getCurrentRumtime().halt(0);

How do I move focus to next input with jQuery?

  function nextFormInput() {
      var focused = $(':focus');
      var inputs = $(focused).closest('form').find(':input');
      inputs.eq(inputs.index(focused) + 1).focus();
  }

latex large division sign in a math formula

Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.

And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.

Animated GIF in IE stopping

Very, very late to answer this one, but I've just discovered that using a background-image that is encoded as a base64 URI in the CSS, rather than held as a separate image, continues to animate in IE8.

Navigation bar show/hide

First read the the section in the View Controller Programming Guide for iOS about 'Adopting a Full-Screen Layout for Navigation Views' and the section about the same for Custom Views. If you are trying to do something like the Photos.app then you are probably using a scroll view. Note the comment that Navigation bars automatically add a scroll content inset to your scroll view to account for the height of the navigation bar (and status bar) so you have to reset the contentInset property of your scroll view back to zero (UIEdgeInsetsZero) right after setting up the initial state of the navigationBar and before the view appears.

Then if you have a single tap that toggles the navigationBar and/or status bar to show or hide, you need to do two things in you toggling method. The first seems to be to save the scroll view's contentOffset property before changing the NavigationBar hidden property and restore your saved value to contentOffset right afterward. And second to again zero out the contentInset property to UIEdgeInsetsZero after changing the navigationBarHidden property. Also, if you are toggling the status bar, you need to change its state before you change the navigationBar's state.

How do I reference the input of an HTML <textarea> control in codebehind?

First make sure you have the runat="server" attribute in your textarea tag like this

<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>

Then you can access the content via:

string body = TextArea1.value;

It is more efficient to use if-return-return or if-else-return?

From Chromium's style guide:

Don't use else after return:

# Bad
if (foo)
  return 1
else
  return 2

# Good
if (foo)
  return 1
return 2

return 1 if foo else 2

c# write text on bitmap

Very old question, but just had to build this for an app today and found the settings shown in other answers do not result in a clean image (possibly as new options were added in later .Net versions).

Assuming you want the text in the centre of the bitmap, you can do this:

// Load the original image
Bitmap bmp = new Bitmap("filename.bmp");

// Create a rectangle for the entire bitmap
RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);

// Create graphic object that will draw onto the bitmap
Graphics g = Graphics.FromImage(bmp);

// ------------------------------------------
// Ensure the best possible quality rendering
// ------------------------------------------
// The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing). 
// One exception is that path gradient brushes do not obey the smoothing mode. 
// Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
g.SmoothingMode = SmoothingMode.AntiAlias;

// The interpolation mode determines how intermediate values between two endpoints are calculated.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;

// Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

// This one is important
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

// Create string formatting options (used for alignment)
StringFormat format = new StringFormat()
{
    Alignment = StringAlignment.Center,
    LineAlignment = StringAlignment.Center
};

// Draw the text onto the image
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf, format);

// Flush all graphics changes to the bitmap
g.Flush();

// Now save or use the bitmap
image.Image = bmp;

References

Difference between OData and REST web services

ODATA is a special kind of REST where we can query data uniformly from URL.

Convert UTC dates to local time in PHP

I store date in the DB in UTC format but then I show them to the final user in their local timezone

// retrieve
$d = (new \DateTime($val . ' UTC'))->format('U');
return date("Y-m-d H:i:s", $d);

How can I throw CHECKED exceptions from inside Java 8 streams?

The only built-in way of handling checked exceptions that can be thrown by a map operation is to encapsulate them within a CompletableFuture. (An Optional is a simpler alternative if you don't need to preserve the exception.) These classes are intended to allow you to represent contingent operations in a functional way.

A couple of non-trivial helper methods are required, but you can arrive at code that's relatively concise, while still making it apparent that your stream's result is contingent on the map operation having completed successfully. Here's what it looks like:

    CompletableFuture<List<Class<?>>> classes =
            Stream.of("java.lang.String", "java.lang.Integer", "java.lang.Double")
                  .map(MonadUtils.applyOrDie(Class::forName))
                  .map(cfc -> cfc.thenApply(Class::getSuperclass))
                  .collect(MonadUtils.cfCollector(ArrayList::new,
                                                  List::add,
                                                  (List<Class<?>> l1, List<Class<?>> l2) -> { l1.addAll(l2); return l1; },
                                                  x -> x));
    classes.thenAccept(System.out::println)
           .exceptionally(t -> { System.out.println("unable to get class: " + t); return null; });

This produces the following output:

[class java.lang.Object, class java.lang.Number, class java.lang.Number]

The applyOrDie method takes a Function that throws an exception, and converts it into a Function that returns an already-completed CompletableFuture -- either completed normally with the original function's result, or completed exceptionally with the thrown exception.

The second map operation illustrates that you've now got a Stream<CompletableFuture<T>> instead of just a Stream<T>. CompletableFuture takes care of only executing this operation if the upstream operation succeeded. The API makes this explict, but relatively painless.

Until you get to the collect phase, that is. This is where we require a pretty significant helper method. We want to "lift" a normal collection operation (in this case, toList()) "inside" the CompletableFuture -- cfCollector() lets us do that using a supplier, accumulator, combiner, and finisher that don't need to know anything at all about CompletableFuture.

The helper methods can be found on GitHub in my MonadUtils class, which is very much still a work in progress.

How to check if a file exists from inside a batch file

C:\>help if

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command

Flattening a shallow list in Python

In Python 3.4 you will be able to do:

[*innerlist for innerlist in outer_list]

What is javax.inject.Named annotation supposed to be used for?

Use @Named to differentiate between different objects of the same type bound in the same scope.

@Named("maxWaitTime")
public long maxWaitTimeMs;

@Named("minWaitTime")
public long minWaitTimeMs;

Without the @Named qualifier, the injector would not know which long to bind to which variable.

  • If you want to create annotations that act like @Named, use the @Qualifier annotation when creating them.

  • If you look at @Named, it is itself annotated with @Qualifier.

system("pause"); - Why is it wrong?

Using system("pause"); is Ungood Practice™ because

  • It's completely unnecessary.
    To keep the program's console window open at the end when you run it from Visual Studio, use Ctrl+F5 to run it without debugging, or else place a breakpoint at the last right brace } of main. So, no problem in Visual Studio. And of course no problem at all when you run it from the command line.

  • It's problematic & annoying
    when you run the program from the command line. For interactive execution you have to press a key at the end to no purpose whatsoever. And for use in automation of some task that pause is very much undesired!

  • It's not portable.
    Unix-land has no standard pause command.

The pause command is an internal cmd.exe command and can't be overridden, as is erroneously claimed in at least one other answer. I.e. it's not a security risk, and the claim that AV programs diagnose it as such is as dubious as the claim of overriding the command (after all, a C++ program invoking system is in position to do itself all that the command interpreter can do, and more). Also, while this way of pausing is extremely inefficient by the usual standards of C++ programming, that doesn't matter at all at the end of a novice's program.

So, the claims in the horde of answers before this are not correct, and the main reason you shouldn't use system("pause") or any other wait command at the end of your main, is the first point above: it's completely unnecessary, it serves absolutely no purpose, it's just very silly.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

A simple case that generates this error message:

In [8]: [1,2,3,4,5][np.array([1])]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-55def8e1923d> in <module>()
----> 1 [1,2,3,4,5][np.array([1])]

TypeError: only integer scalar arrays can be converted to a scalar index

Some variations that work:

In [9]: [1,2,3,4,5][np.array(1)]     # this is a 0d array index
Out[9]: 2
In [10]: [1,2,3,4,5][np.array([1]).item()]    
Out[10]: 2
In [11]: np.array([1,2,3,4,5])[np.array([1])]
Out[11]: array([2])

Basic python list indexing is more restrictive than numpy's:

In [12]: [1,2,3,4,5][[1]]
....
TypeError: list indices must be integers or slices, not list

edit

Looking again at

indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)

indices is a 1d array of integers - but it certainly isn't scalar. It's an array of 50000 integers. List's cannot be indexed with multiple indices at once, regardless of whether they are in a list or array.

Bootstrap Alert Auto Close

Using a fadeTo() that is fading to an opacity of 500 in 2 seconds in "I Can Has Kittenz"'s code isn't readable to me. I think it's better using other options like a delay()

$(".alert").delay(4000).slideUp(200, function() {
    $(this).alert('close');
});

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

In my case I was getting the grey background and it turned out to be inclusion of a zoom value in the map options. Yup, makes no sense.

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

BASH Syntax error near unexpected token 'done'

I have exactly the same issue as above, and took me the whole day to discover that it doesn't like my newline approach. Instead I reused the same code with semi-colon approach instead. For example my initial code using the newline (which threw the same error as yours):

Y=1
while test "$Y" -le "20"
do
        echo "Number $Y"
        Y=$[Y+1]
done

And using code with semicolon approach with worked wonder:

Y=1 ; while test "$Y" -le "20"; do echo "Number $Y"; Y=$[Y+1] ; done

I notice the same problem occurs for other commands as well using the newline approach, so I think I am gonna stick to using semicolon for my future code.

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

BookTitle have a Composite key. so if the key of BookTitle is referenced as a foreign key you have to bring the complete composite key.

So to resolve the problem you need to add the complete composite key in the BookCopy. So add ISBN column as well. and they at the end.

foreign key (ISBN, Title) references BookTitle (ISBN, Title)

Setting a div's height in HTML with CSS

The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page.

Redirecting a request using servlets and the "setHeader" method not working

Another way of doing this if you want to redirect to any url source after the specified point of time

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

public class MyServlet extends HttpServlet


{

public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException

{

response.setContentType("text/html");

PrintWriter pw=response.getWriter();

pw.println("<b><centre>Redirecting to Google<br>");


response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url  after 5 seconds


pw.close();
}

}

How to resize image automatically on browser width resize but keep same height?

Make it a background image and larger than 100% to get the desired effect: http://jsfiddle.net/derekstory/hVM9v/

HTML

<div id="image"></div>

CSS

body, html {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}
#image {
    width: 100%;
    height: 500px;
    background: #000 url('http://static.ddmcdn.com/gif/dog-9.jpg') center no-repeat;
    background-size: auto 200%;
}

ReactJS - Get Height of an element

Following is an up to date ES6 example using a ref.

Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount() because we can only determine the height of an element after it is rendered in the DOM.

import React, {Component} from 'react'
import {render} from 'react-dom'

class DivSize extends Component {

  constructor(props) {
    super(props)

    this.state = {
      height: 0
    }
  }

  componentDidMount() {
    const height = this.divElement.clientHeight;
    this.setState({ height });
  }

  render() {
    return (
      <div 
        className="test"
        ref={ (divElement) => { this.divElement = divElement } }
      >
        Size: <b>{this.state.height}px</b> but it should be 18px after the render
      </div>
    )
  }
}

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

You can find the running example here: https://codepen.io/bassgang/pen/povzjKw

Package opencv was not found in the pkg-config search path

Hi first of all i would like you to use 'Synaptic Package Manager'. You just need to goto the ubuntu software center and search for synaptic package manager.. The beauty of this is that all the packages you need are easily available here. Second it will automatically configures all your paths. Now install this then search for opencv packages over there if you found the package with the green box then its installed but else the package is not in the right place so you need to reinstall it but from package manager this time. If installed then you can do this only, you just need to fill the OpenCV_DIR variable with the path of opencv (containing the OpenCVConfig.cmake file)

    export OpenCV_DIR=<path_of_opencv>

Property '...' has no initializer and is not definitely assigned in the constructor

Get this error at the time of adding Node in my Angular project -

TSError: ? Unable to compile TypeScript: (path)/base.api.ts:19:13 - error TS2564: Property 'apiRoot Path' has no initializer and is not definitely assigned in the constructor.

private apiRootPath: string;

Solution -

Added "strictPropertyInitialization": false in 'compilerOptions' of tsconfig.json.

my package.json -

"dependencies": {
    ...
    "@angular/common": "~10.1.3",
    "@types/express": "^4.17.9",
    "express": "^4.17.1",
    ...
}

Ref URL - https://www.ryadel.com/en/ts2564-ts-property-has-no-initializer-typescript-error-fix-visual-studio-2017-vs2017/

Changing an element's ID with jQuery

Your syntax is incorrect, you should pass the value as the second parameter:

jQuery(this).prev("li").attr("id","newId");

using if else with eval in aspx page

<%# (string)Eval("gender") =="M" ? "Male" :"Female"%>

C++ terminate called without an active exception

Eric Leschinski and Bartosz Milewski have given the answer already. Here, I will try to present it in a more beginner friendly manner.

Once a thread has been started within a scope (which itself is running on a thread), one must explicitly ensure one of the following happens before the thread goes out of scope:

  • The runtime exits the scope, only after that thread finishes executing. This is achieved by joining with that thread. Note the language, it is the outer scope that joins with that thread.
  • The runtime leaves the thread to run on its own. So, the program will exit the scope, whether this thread finished executing or not. This thread executes and exits by itself. This is achieved by detaching the thread. This could lead to issues, for example, if the thread refers to variables in that outer scope.

Note, by the time the thread is joined with or detached, it may have well finished executing. Still either of the two operations must be performed explicitly.

Put quotes around a variable string in JavaScript

You can add these single quotes with template literals:

_x000D_
_x000D_
var text = "http://example.com"_x000D_
var quoteText = `'${text}'`_x000D_
_x000D_
console.log(quoteText)
_x000D_
_x000D_
_x000D_

Docs are here. Browsers that support template literals listed here.

UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

frame.origin = center - bounds.size / 2

(which is the same as)

center = frame.origin + bounds.size / 2

(and there’s also)

frame.size = bounds.size

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

Can't update data-attribute value

THE ANSWER BELOW IS THE GOOD ONE

You aren't using the data method correctly. The correct code to update data is:

$('#foo').data('num', num); 

So your example would be:

var num = $('#foo').data("num") + 1;       
console.log(num)       
$('#foo').data('num', num); 
console.log(num)

Count unique values using pandas groupby

I know it has been a while since this was posted, but I think this will help too. I wanted to count unique values and filter the groups by number of these unique values, this is how I did it:

df.groupby('group').agg(['min','max','count','nunique']).reset_index(drop=False)

How to convert an array into an object using stdClass()

One of the easiest solution is

$objectData = (object) $arrayData

Stack Memory vs Heap Memory

It's a language abstraction - some languages have both, some one, some neither.

In the case of C++, the code is not run in either the stack or the heap. You can test what happens if you run out of heap memory by repeatingly calling new to allocate memory in a loop without calling delete to free it it. But make a system backup before doing this.

Test a weekly cron job

After messing about with some stuff in cron which wasn't instantly compatible I found that the following approach was nice for debugging:

crontab -e

* * * * * /path/to/prog var1 var2 &>>/tmp/cron_debug_log.log

This will run the task once a minute and you can simply look in the /tmp/cron_debug_log.log file to figure out what is going on.

It is not exactly the "fire job" you might be looking for, but this helped me a lot when debugging a script that didn't work in cron at first.

git checkout master error: the following untracked working tree files would be overwritten by checkout

do a :

git branch

if git show you something like :

* (no branch)
master
Dbranch

You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with

git checkout master 

Now you should be able to delete the Dbranch.

C#: HttpClient with POST parameters

As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

The querystring (get) parameters included in your url probably will not do anything.

Try this:

string url = "http://myserver/method";    
string content = "param1=1&param2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);

HTH,

bovako

When to use the different log levels

I think that SYSLOG levels NOTICE and ALERT/EMERGENCY are largely superfluous for application-level logging - while CRITICAL/ALERT/EMERGENCY may be useful alert levels for an operator that may trigger different actions and notifications, to an application admin it's all the same as FATAL. And I just cannot sufficiently distinguish between being given a notice or some information. If the information is not noteworthy, it's not really information :)

I like Jay Cincotta's interpretation best - tracing your code's execution is something very useful in tech support, and putting trace statements into the code liberally should be encouraged - especially in combination with a dynamic filtering mechanism for logging the trace messages from specific application components. However DEBUG level to me indicates that we're still in the process of figuring out what's going on - I see DEBUG level output as a development-only option, not as something that should ever show up in a production log.

There is however a logging level that I like to see in my error logs when wearing the hat of a sysadmin as much as that of tech support, or even developer: OPER, for OPERATIONAL messages. This I use for logging a timestamp, the type of operation invoked, the arguments supplied, possibly a (unique) task identifier, and task completion. It's used when e.g. a standalone task is fired off, something that is a true invocation from within the larger long-running app. It's the sort of thing I want always logged, no matter whether anything goes wrong or not, so I consider the level of OPER to be higher than FATAL, so you can only turn it off by going to totally silent mode. And it's much more than mere INFO log data - a log level often abused for spamming logs with minor operational messages of no historical value whatsoever.

As the case dictates this information may be directed to a separate invocation log, or may be obtained by filtering it out of a large log recording more information. But it's always needed, as historical info, to know what was being done - without descending to the level of AUDIT, another totally separate log level that has nothing to do with malfunctions or system operation, doesn't really fit within the above levels (as it needs its own control switch, not a severity classification) and which definitely needs its own separate log file.

How does `scp` differ from `rsync`?

One major feature of rsync over scp (beside the delta algorithm and encryption if used w/ ssh) is that it automatically verifies if the transferred file has been transferred correctly. Scp will not do that, which occasionally might result in corruption when transferring larger files. So in general rsync is a copy with guarantee.

Centos manpages mention this the end of the --checksum option description:

Note that rsync always verifies that each transferred file was correctly reconstructed on the receiving side by checking a whole-file checksum that is generated as the file is transferred, but that automatic after-the-transfer verification has nothing to do with this option’s before-the-transfer “Does this file need to be updated?” check.

Slick Carousel Uncaught TypeError: $(...).slick is not a function

I found the solution myself later, so I placed it as an answer:

The error persisted every now and then when adding new function to my JS file. I ultimately stripped down my concatenated JS file and found out that there were two versions of jQuery being loaded, of which one was very, very old.

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

A far more common answer is that you have some error that is getting appended to whatever your compressing. The solution is to set display_errors = Off in your php.ini file (Check in your terminal if it's On by running php --info and look for "display_errors")

That should do it. And, how do you discover what errors you're actually? Check your PHP error logs whenever you hit that route/page.

Good luclk!

Border around each cell in a range

I have a set of 15 subroutines I add to every Coded Excel Workbook I create and this is one of them. The following routine clears the area and creates a border.

Sample Call:

Call BoxIt(Range("A1:z25"))

Subroutine:

Sub BoxIt(aRng As Range)
On Error Resume Next

    With aRng

        'Clear existing
        .Borders.LineStyle = xlNone

        'Apply new borders
        .BorderAround xlContinuous, xlThick, 0
        With .Borders(xlInsideVertical)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .Weight = xlMedium
        End With
        With .Borders(xlInsideHorizontal)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .Weight = xlMedium
        End With
    End With

End Sub

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

I have used a method to test if any specific key is pressed by storing the currently pressed key codes in an array:

var keysPressed = [],
    shiftCode = 16;

$(document).on("keyup keydown", function(e) {
    switch(e.type) {
        case "keydown" :
            keysPressed.push(e.keyCode);
            break;
        case "keyup" :
            var idx = keysPressed.indexOf(e.keyCode);
            if (idx >= 0)
                keysPressed.splice(idx, 1);
            break;
    }
});

$("a.shifty").on("click", function(e) {
    e.preventDefault();
    console.log("Shift Pressed: " + (isKeyPressed(shiftCode) ? "true" : "false"));
});

function isKeyPressed(code) {
    return keysPressed.indexOf(code) >= 0;
}

Here is the jsfiddle

Convert the first element of an array to a string in PHP

Use the inbuilt function in PHP, implode(array, separator):

<?php
    $ar = array("parth","raja","nikhar");
    echo implode($ar,"/");
?>

Result: parth/raja/nikhar

make an ID in a mysql table auto_increment (after the fact)

I'm guessing that you don't need to re-increment the existing data so, why can't you just run a simple ALTER TABLE command to change the PK's attributes?

Something like:

ALTER TABLE `content` CHANGE `id` `id` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT 

I've tested this code on my own MySQL database and it works but I have not tried it with any meaningful number of records. Once you've altered the row then you need to reset the increment to a number guaranteed not to interfere with any other records.

ALTER TABLE `content` auto_increment = MAX(`id`) + 1

Again, untested but I believe it will work.

Asynchronous Function Call in PHP

I think if the HTML and other UI stuff needs the data returned then there is not going to be a way to async it.

I believe the only way to do this in PHP would be to log a request in a database and have a cron check every minute, or use something like Gearman queue processing, or maybe exec() a command line process

In the meantime you php page would have to generate some html or js that makes it reload every few seconds to check on progress, not ideal.

To sidestep the issue, how many different requests are you expecting? Could you download them all automatically every hour or so and save to a database?

Method to find string inside of the text file. Then getting the following lines up to a certain limit

Here is a java 8 method to find a string in a text file:

for (String toFindUrl : urlsToTest) {
        streamService(toFindUrl);
    }

private void streamService(String item) {
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
           stream.filter(lines -> lines.contains(item))
                       .forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

document.getElementById vs jQuery $()

All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it

<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>

Online Demo! - https://codepen.io/frank-dspeed/pen/mdywbre

Python: converting a list of dictionaries to json

import json

list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]

Write to json File:

with open('/home/ubuntu/test.json', 'w') as fout:
    json.dump(list , fout)

Read Json file:

with open(r"/home/ubuntu/test.json", "r") as read_file:
    data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]

Remove the last character in a string in T-SQL?

Try It :

  DECLARE @String NVARCHAR(100)
    SET @String = '12354851'
    SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))

JSON - Iterate through JSONArray

You could try my (*heavily borrowed from various sites) recursive method to go through all JSON objects and JSON arrays until you find JSON elements. This example actually searches for a particular key and returns all values for all instances of that key. 'searchKey' is the key you are looking for.

ArrayList<String> myList = new ArrayList<String>();
myList = findMyKeyValue(yourJsonPayload,null,"A"); //if you only wanted to search for A's values

    private ArrayList<String> findMyKeyValue(JsonElement element, String key, String searchKey) {

    //OBJECT
    if(element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();

        //loop through all elements in object

        for (Map.Entry<String,JsonElement> entry : jsonObject.entrySet()) {
            JsonElement array = entry.getValue();
            findMyKeyValue(array, entry.getKey(), searchKey);

        }

    //ARRAY
    } else if(element.isJsonArray()) {
        //when an array is found keep 'key' as that is the array's name i.e. pass it down

        JsonArray jsonArray = element.getAsJsonArray();

        //loop through all elements in array
        for (JsonElement childElement : jsonArray) {
            findMyKeyValue(childElement, key, searchKey);
        }

    //NEITHER
    } else {

        //System.out.println("SKey: " + searchKey + " Key: " + key );

            if (key.equals(searchKey)){
                listOfValues.add(element.getAsString());
            }
    }
    return listOfValues;
}

Concatenating elements in an array to a string

Use the Arrays.toString() function. It keeps your code short and readable. It uses a string builder internally, thus, it's also efficient. To get rid of the extra characters, you might chose to eliminate them using the String.replace() function, which, admittedly, reduces readability again.

String str = Arrays.toString(arr).replaceAll(", |\\[|\\]", "");

This is similar to the answer of Tris Nefzger, but without the lengthy substring construction to get rid of the square brackets.

Explanation of the Regex: "|" means any of ", " and "[" and "]". The "\\" tells the Java String that we are not meaning some special character (like a new line "\n" or a tab "\t") but a real backslash "\". So instead of "\\[", the Regex interpreter reads "\[", which tells it that we mean a literal square bracket and do not want to use it as part of the Regex language (for instance, "[^3]*" denotes any number of characters, but none of them should be "3").

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

Try running fuser command

[root@guest2 ~]# fuser -mv /home

USER PID ACCESS COMMAND

/home: root 2919 f.... automount

[root@guest2 ~]# kill -9 2919

autofs service is known to cause this issue.

You can use command

#service autofs stop

And try again.

Where does Jenkins store configuration files for the jobs it runs?

Jenkins 1.627, OS X 10.10.5 /Users/Shared/Jenkins/Home/jobs/{project_name}/config.xml

What is the difference between attribute and property?

These words existed way before Computer Science came around.

  1. Attribute is a quality or object that we attribute to someone or something. For example, the scepter is an attribute of power and statehood.

  2. Property is a quality that exists without any attribution. For example, clay has adhesive qualities; i.e, a property of clay is its adhesive quality. Another example: one of the properties of metals is electrical conductivity. Properties demonstrate themselves through physical phenomena without the need to attribute them to someone or something. By the same token, saying that someone has masculine attributes is self-evident. In effect, you could say that a property is owned by someone or something.

To be fair though, in Computer Science these two words, at least for the most part, can be used interchangeably - but then again programmers usually don't hold degrees in English Literature and do not write or care much about grammar books :).

Find a private field with Reflection?

typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)

How to place the "table" at the middle of the webpage?

Try this :

<style type="text/css">
        .myTableStyle
        {
           position:absolute;
           top:50%;
           left:50%; 

            /*Alternatively you could use: */
           /*
              position: fixed;
               bottom: 50%;
               right: 50%;
           */


        }
    </style>

How to find all occurrences of a substring?

You can try :

>>> string = "test test test test"
>>> for index,value in enumerate(string):
    if string[index:index+(len("test"))] == "test":
        print index

0
5
10
15

How to change a text with jQuery

$('#toptitle').html('New world');

or

$('#toptitle').text('New world');

Returning a value from thread?

With the latest .NET Framework, it is possible to return a value from a separate thread using a Task, where the Result property blocks the calling thread until the task finishes:

  Task<MyClass> task = Task<MyClass>.Factory.StartNew(() =>
  {
      string s = "my message";
      double d = 3.14159;
      return new MyClass { Name = s, Number = d };
  });
  MyClass test = task.Result;

For details, please see http://msdn.microsoft.com/en-us/library/dd537613(v=vs.110).aspx

The simplest way to resize an UIImage?

This is an UIImage extension compatible with Swift 3 and Swift 4 which scales image to given size with an aspect ratio

extension UIImage {

    func scaledImage(withSize size: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
        return UIGraphicsGetImageFromCurrentImageContext()!
    }

    func scaleImageToFitSize(size: CGSize) -> UIImage {
        let aspect = self.size.width / self.size.height
        if size.width / aspect <= size.height {
            return scaledImage(withSize: CGSize(width: size.width, height: size.width / aspect))
        } else {
            return scaledImage(withSize: CGSize(width: size.height * aspect, height: size.height))
        }
    }

}

Example usage

let image = UIImage(named: "apple")
let scaledImage = image.scaleImageToFitSize(size: CGSize(width: 45.0, height: 45.0))

Convert string to nullable type (int, double, etc...)

The generic answer provided by "Joel Coehoorn" is good.

But, this is another way without using those GetConverter... or try/catch blocks... (i'm not sure but this may have better performance in some cases):

public static class StrToNumberExtensions
{
    public static short ToShort(this string s, short defaultValue = 0) => short.TryParse(s, out var v) ? v : defaultValue;
    public static int ToInt(this string s, int defaultValue = 0) => int.TryParse(s, out var v) ? v : defaultValue;
    public static long ToLong(this string s, long defaultValue = 0) => long.TryParse(s, out var v) ? v : defaultValue;
    public static decimal ToDecimal(this string s, decimal defaultValue = 0) => decimal.TryParse(s, out var v) ? v : defaultValue;
    public static float ToFloat(this string s, float defaultValue = 0) => float.TryParse(s, out var v) ? v : defaultValue;
    public static double ToDouble(this string s, double defaultValue = 0) => double.TryParse(s, out var v) ? v : defaultValue;

    public static short? ToshortNullable(this string s, short? defaultValue = null) => short.TryParse(s, out var v) ? v : defaultValue;
    public static int? ToIntNullable(this string s, int? defaultValue = null) => int.TryParse(s, out var v) ? v : defaultValue;
    public static long? ToLongNullable(this string s, long? defaultValue = null) => long.TryParse(s, out var v) ? v : defaultValue;
    public static decimal? ToDecimalNullable(this string s, decimal? defaultValue = null) => decimal.TryParse(s, out var v) ? v : defaultValue;
    public static float? ToFloatNullable(this string s, float? defaultValue = null) => float.TryParse(s, out var v) ? v : defaultValue;
    public static double? ToDoubleNullable(this string s, double? defaultValue = null) => double.TryParse(s, out var v) ? v : defaultValue;
}

Usage is as following:

var x1 = "123".ToInt(); //123
var x2 = "abc".ToInt(); //0
var x3 = "abc".ToIntNullable(); // (int?)null 
int x4 = ((string)null).ToInt(-1); // -1
int x5 = "abc".ToInt(-1); // -1

var y = "19.50".ToDecimal(); //19.50

var z1 = "invalid number string".ToDoubleNullable(); // (double?)null
var z2 = "invalid number string".ToDoubleNullable(0); // (double?)0

How to center form in bootstrap 3

<div class="col-md-4 offset-md-4"> 
put your form here
</div>

UICollectionView Set number of columns

Because UICollectionView is so flexible, there are multiple ways you could change the number of columns, depending on the kind of layout you use.

The UICollectionViewFlowLayout (which is probably what you're working with) doesn't specify a number of columns directly (because it depends on the view size/orientation). The easiest way to change it would be to set the itemSize property and/or minimumInteritemSpacing/minimumLineSpacing.

Calling a javascript function recursively

Here's one very simple example:

var counter = 0;

function getSlug(tokens) {
    var slug = '';

    if (!!tokens.length) {
        slug = tokens.shift();
        slug = slug.toLowerCase();
        slug += getSlug(tokens);

        counter += 1;
        console.log('THE SLUG ELEMENT IS: %s, counter is: %s', slug, counter);
    }

    return slug;
}

var mySlug = getSlug(['This', 'Is', 'My', 'Slug']);
console.log('THE SLUG IS: %s', mySlug);

Notice that the counter counts "backwards" in regards to what slug's value is. This is because of the position at which we are logging these values, as the function recurs before logging -- so, we essentially keep nesting deeper and deeper into the call-stack before logging takes place.

Once the recursion meets the final call-stack item, it trampolines "out" of the function calls, whereas, the first increment of counter occurs inside of the last nested call.

I know this is not a "fix" on the Questioner's code, but given the title I thought I'd generically exemplify Recursion for a better understanding of recursion, outright.

jQuery function after .append

Although Marcus Ekwall is absolutely right about the synchronicity of append, I have also found that in odd situations sometimes the DOM isn't completely rendered by the browser when the next line of code runs.

In this scenario then shadowdiver solutions is along the correct lines - with using .ready - however it is a lot tidier to chain the call to your original append.

$('#root')
  .append(html)
  .ready(function () {
    // enter code here
  });

Array to Collection: Optimized code

What about :

List myList = new ArrayList(); 
String[] myStringArray = new String[] {"Java", "is", "Cool"}; 

Collections.addAll(myList, myStringArray); 

Removing duplicate rows in Notepad++

Whether the file is sorted or not, you can use below regex to remove duplicates in anywhere occurred in your file.

Find what: ^([^\r]*[^\n])(.*?)\r?\n\1$
Replace with: \1\2
Search Mode:

  • "Regular expression"
  • Check the ". matches newline" option

do "Replace All" as many time as possible until you see "0 occurrences were replaced"

Dialog with transparent background in Android

Make sure R.layout.themechanger has no background color because by default the dialog has a default background color.

You also need to add dialog.getWindow().setBackgroundDrawable(newColorDrawable(Color.TRANSPARENT));

And finally

<style name="TransparentDialog">
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowTitleStyle">@null</item>
</style>

Inline functions in C#?

Cody has it right, but I want to provide an example of what an inline function is.

Let's say you have this code:

private void OutputItem(string x)
{
    Console.WriteLine(x);

    //maybe encapsulate additional logic to decide 
    // whether to also write the message to Trace or a log file
}

public IList<string> BuildListAndOutput(IEnumerable<string> x)
{  // let's pretend IEnumerable<T>.ToList() doesn't exist for the moment
    IList<string> result = new List<string>();

    foreach(string y in x)
    {
        result.Add(y);
        OutputItem(y);
    }
    return result;
}

The compilerJust-In-Time optimizer could choose to alter the code to avoid repeatedly placing a call to OutputItem() on the stack, so that it would be as if you had written the code like this instead:

public IList<string> BuildListAndOutput(IEnumerable<string> x)
{
    IList<string> result = new List<string>();

    foreach(string y in x)
    {
        result.Add(y);

        // full OutputItem() implementation is placed here
        Console.WriteLine(y);   
    }

    return result;
}

In this case, we would say the OutputItem() function was inlined. Note that it might do this even if the OutputItem() is called from other places as well.

Edited to show a scenario more-likely to be inlined.

Rendering HTML elements to <canvas>

RasterizeHTML is a very good project, but if you need to access the canvas it wont work on chrome. due to the use of <foreignObject>.

If you need to access the canvas then you can use html2canvas

I am trying to find another project as html2canvas is very slow in performance

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

I suspect GCC (mingw) has custom code to disable the checks for the wide printf functions on Windows. This is because Microsoft's own implementation (MSVCRT) is badly wrong and has %s and %ls backwards for the wide printf functions; since GCC can't be sure whether you will be linking with MS's broken implementation or some corrected one, the least-obtrusive thing it can do is just shut off the warning.

How do I use cascade delete with SQL Server?

You will need to,

  • Drop the existing foreign key constraint,
  • Add a new one with the ON DELETE CASCADE setting enabled.

Something like:

ALTER TABLE dbo.T2
   DROP CONSTRAINT FK_T1_T2   -- or whatever it's called

ALTER TABLE dbo.T2
   ADD CONSTRAINT FK_T1_T2_Cascade
   FOREIGN KEY (EmployeeID) REFERENCES dbo.T1(EmployeeID) ON DELETE CASCADE

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I had this error message when trying "hello world" like things with Qt. The problems went away by correctly running the qt moc (meta object compiler) and compiling+including these moc-generated files correctly.

How do you disable browser Autocomplete on web form field / input tag?

To prevent browser auto fill with the user's saved site login credentials, place a text and password input field at the top of the form with non empty values and style "position: absolute; top: -999px; left:-999px" set to hide the fields.

<form>
  <input type="text" name="username_X" value="-" tabindex="-1" aria-hidden="true" style="position: absolute; top: -999px; left:-999px" />
  <input type="password" name="password_X" value="-" tabindex="-1" aria-hidden="true" style="position: absolute; top: -999px; left:-999px" />
  <!-- Place the form elements below here. -->
</form>

It is important that a text field precede the password field. Otherwise the auto fill may not be prevented in some cases.

It is important that the value of both the text and password fields not be empty, to prevent default values from being overwritten in some cases.

It is important that these two fields are before the "real" password type field(s) in the form.

For newer browsers that are html 5.3 compliant the autocomplete attribute value "new-password" should work.

<form>
  <input type="text" name="username" value="" />
  <input type="password" name="password" value="" autocomplete="new-password" />
</form>

A combination of the two methods can be used to support both older and newer browsers.

<form>
  <div style="display:none">
    <input type="text" readonly tabindex="-1" />
    <input type="password" readonly tabindex="-1" />
  </div>
  <!-- Place the form elements below here. -->
  <input type="text" name="username" value="" />
  <input type="password" name="password" value="" autocomplete="new-password" />
</form>

Get filename and path from URI from mediastore

As an add-on, if you need to see if a file exists before you try to open an input stream, you can use the DocumentsContract.

(Kotlin code)

var iStream = null
if(DocumentsContract.isDocumentUri(context,myUri)) {
   val pfd: ParcelFileDescriptor? = context.contentResolver.openFileDescriptor(
            myUri, "r") ?: return null
   iStream = ParcelFileDescriptor.AutoCloseInputStream(pfd)
}

Cross field validation with Hibernate Validator (JSR 303)

I made a small adaptation in Nicko's solution so that it is not necessary to use the Apache Commons BeanUtils library and replace it with the solution already available in spring, for those using it as I can be simpler:

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(final FieldMatch constraintAnnotation) {
        firstFieldName = constraintAnnotation.first();
        secondFieldName = constraintAnnotation.second();
    }

    @Override
    public boolean isValid(final Object object, final ConstraintValidatorContext context) {

        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
        final Object firstObj = beanWrapper.getPropertyValue(firstFieldName);
        final Object secondObj = beanWrapper.getPropertyValue(secondFieldName);

        boolean isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);

        if (!isValid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                .addPropertyNode(firstFieldName)
                .addConstraintViolation();
        }

        return isValid;

    }
}

Is there a simple way to convert C++ enum to string?

Another answer: in some contexts, it makes sense to define your enumeration in a non-code format, like a CSV, YAML, or XML file, and then generate both the C++ enumeration code and the to-string code from the definition. This approach may or may not be practical in your application, but it's something to keep in mind.

How do I trim whitespace?

try translate

>>> import string
>>> print '\t\r\n  hello \r\n world \t\r\n'

  hello 
 world  
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '\t\r\n  hello \r\n world \t\r\n'.translate(tr)
'     hello    world    '
>>> '\t\r\n  hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
'helloworld'

Assign null to a SqlParameter

Try this:

if (AgeItem.AgeIndex != null)
{
   SqlParameter[] parameters = new SqlParameter[1];
   SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);
   planIndexParameter.Value = AgeItem.AgeIndex;
   parameters[0] = planIndexParameter;
}

In other words, if the parameter is null just don't send it to your stored proc (assuming, of course, that the stored proc accepts null parameters which is implicit in your question).

Getting or changing CSS class property with Javascript using DOM style

I think this is not the best way, but in my cases other methods did not work.

stylesheet = document.styleSheets[0]
stylesheet.insertRule(".have-border { border: 1px solid black;}", 0);

Example from https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript

How to validate an email address in JavaScript

There is my version of an email validator. This code is done with object-oriented programming and realized as a class with static methods. You will find two versions of the validators: strict(EmailValidator.validate) and kind(EmailValidator.validateKind).

The first throws an error if an email is invalid and returns email otherwise. The second returns Boolean value that says if an email is valid. I prefer the strict version in most of the cases.

export class EmailValidator {
    /**
     * @param {string} email
     * @return {string}
     * @throws {Error}
     */
    static validate(email) {
        email = this.prepareEmail(email);

        const isValid = this.validateKind(email);

        if (isValid)
            return email;

        throw new Error(`Got invalid email: ${email}.`);
    }

    /**
     * @param {string} email
     * @return {boolean}
     */
    static validateKind(email) {
        email = this.prepareEmail(email);

        const regex = this.getRegex();

        return regex.test(email);
    }

    /**
     * @return {RegExp}
     * @private
     */
    static getRegex() {
        return /^(([^<>()\[\]\\.,;:\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,}))$/;
    }

    /**
     * @param {string} email
     * @return {string}
     * @private
     */
    static prepareEmail(email) {
        return String(email).toLowerCase();
    }
}

To validate an email you can follow these ways:

// First way.

try {
    EmailValidator.validate('[email protected]');
} catch (e) {
    console.error(e.message);
}
// Second way.

const email = '[email protected]';
const isValid = EmailValidator.validateKind(email);

if (isValid)
    console.log(`Email is valid: ${email}.`);
else
    console.log(`Email is invalid: ${email}.`);

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

For Me adding few below line in WebApi.config works as after updating the new nuget package did not works out

var setting = config.Formatters.JsonFormatter.SerializerSettings;
setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
setting.Formatting = Formatting.Indented;

Don't forget to add namespace:

using Newtonsoft.Json.Serialization; 
using Newtonsoft.Json;

How to create query parameters in Javascript?

functional

function encodeData(data) {
    return Object.keys(data).map(function(key) {
        return [key, data[key]].map(encodeURIComponent).join("=");
    }).join("&");
}   

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

Use jQuery to navigate away from page

window.location = myUrl;

Anyway, this is not jQuery: it's plain javascript

CSS background image to fit width, height should auto-scale in proportion

body{
    background-image: url(../url/imageName.jpg);
    background-attachment: fixed;
    background-size: auto 100%;
    background-position: center;
}

equals vs Arrays.equals in Java

The Arrays.equals(array1, array2) :

check if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.

The array1.equals(array2) :

compare the object to another object and return true only if the reference of the two object are equal as in the Object.equals()

Count number of times a date occurs and make a graph out of it

The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.

Step 1:

Step1

Step 2:

Step2

Retrieving JSON Object Literal from HttpServletRequest

make use of the jackson JSON processor

 ObjectMapper mapper = new ObjectMapper();
  Book book = mapper.readValue(request.getInputStream(),Book.class);

How to write dynamic variable in Ansible playbook

I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:

   vars:
    myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"

How to import an Oracle database from dmp file and log file?

How was the database exported?

  • If it was exported using exp and a full schema was exported, then

    1. Create the user:

      create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
      
    2. Grant the rights:

      grant connect, create session, imp_full_database to <username>;
      
    3. Start the import with imp:

      imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
      
  • If it was exported using expdp, then start the import with impdp:

    impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
    

Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\).

Either move the export file to the above path or create a directory object to pointing to the path where the dmp file is present and pass the object name to the impdp command above.

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

None of these answers really work. As others noted the Cors package will only use the Access-Control-Allow-Origin header if the request had an Origin header. But you can't generally just add an Origin header to the request because browsers may try to regulate that too.

If you want a quick and dirty way to allow cross site requests to a web api, it's really a lot easier to just write a custom filter attribute:

public class AllowCors : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext == null)
        {
            throw new ArgumentNullException("actionExecutedContext");
        }
        else
        {
            actionExecutedContext.Response.Headers.Remove("Access-Control-Allow-Origin");
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
        }
        base.OnActionExecuted(actionExecutedContext);
    }
}

Then just use it on your Controller action:

[AllowCors]
public IHttpActionResult Get()
{
    return Ok("value");
}

I won't vouch for the security of this in general, but it's probably a lot safer than setting the headers in the web.config since this way you can apply them only as specifically as you need them.

And of course it is simple to modify the above to allow only certain origins, methods etc.

The requested URL /about was not found on this server

That's not a typical Wordpress rewrite block. This is:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

See http://codex.wordpress.org/Using_Permalinks#Where.27s_my_.htaccess_file.3F

Where's my .htaccess file? WordPress's index.php and .htaccess files should be together in the directory indicated by the Site address (URL) setting on your General Options page. Since the name of the file begins with a dot, the file may not be visible through an FTP client unless you change the preferences of the FTP tool to show all files, including the hidden files. Some hosts (e.g. Godaddy) may not show or allow you to edit .htaccess if you install WordPress through the Godaddy Hosting Connection installation.

Creating and editing (.htaccess) If you do not already have a .htaccess file, create one. If you have shell or ssh access to the server, a simple touch .htaccess command will create the file. If you are using FTP to transfer files, create a file on your local computer, call it 1.htaccess, upload it to the root of your WordPress folder, and then rename it to .htaccess.

You can edit the .htaccess file by FTP, shell, or (possibly) your host's control panel.

The easiest and fastest thing to do it reset your permalinks in Dashboard>>Settings>>Permalinks and make sure .htaccess is writable so WordPress can write the rules itself.

And: are you aware you are calling index.cgi as your default document rather than index.php? That's wrong. Remove index.cgi. Or try removing the whole line, too, because defining a default doc on your server may not be needed.

How do I restrict a float value to only two places after the decimal point in C?

Always use the printf family of functions for this. Even if you want to get the value as a float, you're best off using snprintf to get the rounded value as a string and then parsing it back with atof:

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

double dround(double val, int dp) {
    int charsNeeded = 1 + snprintf(NULL, 0, "%.*f", dp, val);
    char *buffer = malloc(charsNeeded);
    snprintf(buffer, charsNeeded, "%.*f", dp, val);
    double result = atof(buffer);
    free(buffer);
    return result;
}

I say this because the approach shown by the currently top-voted answer and several others here - multiplying by 100, rounding to the nearest integer, and then dividing by 100 again - is flawed in two ways:

  • For some values, it will round in the wrong direction because the multiplication by 100 changes the decimal digit determining the rounding direction from a 4 to a 5 or vice versa, due to the imprecision of floating point numbers
  • For some values, multiplying and then dividing by 100 doesn't round-trip, meaning that even if no rounding takes place the end result will be wrong

To illustrate the first kind of error - the rounding direction sometimes being wrong - try running this program:

int main(void) {
    // This number is EXACTLY representable as a double
    double x = 0.01499999999999999944488848768742172978818416595458984375;

    printf("x: %.50f\n", x);

    double res1 = dround(x, 2);
    double res2 = round(100 * x) / 100;

    printf("Rounded with snprintf: %.50f\n", res1);
    printf("Rounded with round, then divided: %.50f\n", res2);
}

You'll see this output:

x: 0.01499999999999999944488848768742172978818416595459
Rounded with snprintf: 0.01000000000000000020816681711721685132943093776703
Rounded with round, then divided: 0.02000000000000000041633363423443370265886187553406

Note that the value we started with was less than 0.015, and so the mathematically correct answer when rounding it to 2 decimal places is 0.01. Of course, 0.01 is not exactly representable as a double, but we expect our result to be the double nearest to 0.01. Using snprintf gives us that result, but using round(100 * x) / 100 gives us 0.02, which is wrong. Why? Because 100 * x gives us exactly 1.5 as the result. Multiplying by 100 thus changes the correct direction to round in.

To illustrate the second kind of error - the result sometimes being wrong due to * 100 and / 100 not truly being inverses of each other - we can do a similar exercise with a very big number:

int main(void) {
    double x = 8631192423766613.0;

    printf("x: %.1f\n", x);

    double res1 = dround(x, 2);
    double res2 = round(100 * x) / 100;

    printf("Rounded with snprintf: %.1f\n", res1);
    printf("Rounded with round, then divided: %.1f\n", res2);
}

Our number now doesn't even have a fractional part; it's an integer value, just stored with type double. So the result after rounding it should be the same number we started with, right?

If you run the program above, you'll see:

x: 8631192423766613.0
Rounded with snprintf: 8631192423766613.0
Rounded with round, then divided: 8631192423766612.0

Oops. Our snprintf method returns the right result again, but the multiply-then-round-then-divide approach fails. That's because the mathematically correct value of 8631192423766613.0 * 100, 863119242376661300.0, is not exactly representable as a double; the closest value is 863119242376661248.0. When you divide that back by 100, you get 8631192423766612.0 - a different number to the one you started with.

Hopefully that's a sufficient demonstration that using roundf for rounding to a number of decimal places is broken, and that you should use snprintf instead. If that feels like a horrible hack to you, perhaps you'll be reassured by the knowledge that it's basically what CPython does.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

According to the latest updates for OpenCV 3.0 and higher, you need to change the Property Identifiers as follows in the code by Mehran:

cv2.cv.CV_CAP_PROP_POS_FRAMES

to

cv2.CAP_PROP_POS_FRAMES

and same applies to cv2.CAP_PROP_POS_FRAME_COUNT.

Hope it helps.

Select first 4 rows of a data.frame in R

If you have less than 4 rows, you can use the head function ( head(data, 4) or head(data, n=4)) and it works like a charm. But, assume we have the following dataset with 15 rows

>data <- data <- read.csv("./data.csv", sep = ";", header=TRUE)

>data
 LungCap Age Height Smoke Gender Caesarean
1    6.475   6   62.1    no   male        no
2   10.125  18   74.7   yes female        no
3    9.550  16   69.7    no female       yes
4   11.125  14   71.0    no   male        no
5    4.800   5   56.9    no   male        no
6    6.225  11   58.7    no female        no
7    4.950   8   63.3    no   male       yes
8    7.325  11   70.4    no  male         no
9    8.875  15   70.5    no   male        no
10   6.800  11   59.2    no   male        no
11   6.900  12   59.3    no   male        no
12   6.100  13   59.4    no   male        no
13   6.110  14   59.5    no   male        no
14   6.120  15   59.6    no   male        no
15   6.130  16   59.7    no   male        no

Let's say, you want to select the first 10 rows. The easiest way to do it would be data[1:10, ].

> data[1:10,]
   LungCap Age Height Smoke Gender Caesarean
1    6.475   6   62.1    no   male        no
2   10.125  18   74.7   yes female        no
3    9.550  16   69.7    no female       yes
4   11.125  14   71.0    no   male        no
5    4.800   5   56.9    no   male        no
6    6.225  11   58.7    no female        no
7    4.950   8   63.3    no   male       yes
8    7.325  11   70.4    no  male         no
9    8.875  15   70.5    no   male        no
10   6.800  11   59.2    no   male        no

However, let's say you try to retrieve the first 19 rows and see the what happens - you will have missing values

> data[1:19,]
     LungCap Age Height Smoke Gender Caesarean
1      6.475   6   62.1    no   male        no
2     10.125  18   74.7   yes female        no
3      9.550  16   69.7    no female       yes
4     11.125  14   71.0    no   male        no
5      4.800   5   56.9    no   male        no
6      6.225  11   58.7    no female        no
7      4.950   8   63.3    no   male       yes
8      7.325  11   70.4    no  male         no
9      8.875  15   70.5    no   male        no
10     6.800  11   59.2    no   male        no
11     6.900  12   59.3    no   male        no
12     6.100  13   59.4    no   male        no
13     6.110  14   59.5    no   male        no
14     6.120  15   59.6    no   male        no
15     6.130  16   59.7    no   male        no
NA        NA  NA     NA  <NA>   <NA>      <NA>
NA.1      NA  NA     NA  <NA>   <NA>      <NA>
NA.2      NA  NA     NA  <NA>   <NA>      <NA>
NA.3      NA  NA     NA  <NA>   <NA>      <NA>

and with the head() function,

> head(data, 19) # or head(data, n=19)
   LungCap Age Height Smoke Gender Caesarean
1    6.475   6   62.1    no   male        no
2   10.125  18   74.7   yes female        no
3    9.550  16   69.7    no female       yes
4   11.125  14   71.0    no   male        no
5    4.800   5   56.9    no   male        no
6    6.225  11   58.7    no female        no
7    4.950   8   63.3    no   male       yes
8    7.325  11   70.4    no  male         no
9    8.875  15   70.5    no   male        no
10   6.800  11   59.2    no   male        no
11   6.900  12   59.3    no   male        no
12   6.100  13   59.4    no   male        no
13   6.110  14   59.5    no   male        no
14   6.120  15   59.6    no   male        no
15   6.130  16   59.7    no   male        no

Hope this help!

Check if one date is between two dates

Try what's below. It will help you...

Fiddle : http://jsfiddle.net/RYh7U/146/

Script :

if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
    alert("Availed");
else
    alert("Not Availed");

function dateCheck(from,to,check) {

    var fDate,lDate,cDate;
    fDate = Date.parse(from);
    lDate = Date.parse(to);
    cDate = Date.parse(check);

    if((cDate <= lDate && cDate >= fDate)) {
        return true;
    }
    return false;
}

How to open remote files in sublime text 3

On macOS, one option is to install FUSE for macOS and use sshfs to mount a remote directory:

mkdir local_dir
sshfs remote_user@remote_host:remote_dir/ local_dir

Some caveats apply with mounting network volumes, so YMMV.

How to create string with multiple spaces in JavaScript

In 2021 - use ES6 Template Literals for this task. If you need IE11 Support - use a transpiler.

let a = `something       something`;

Template Literals are fast, powerful and produce cleaner code.


If you need IE11 support and you don't have transpiler, stay strong and use \xa0 - it is a NO-BREAK SPACE char.

Reference from UTF-8 encoding table and Unicode characters, you can write as below:

var a = 'something' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + 'something';

How do I increase the scrollback buffer in a running screen session?

There is a minimal amount of "default" buffer when you startup a 'screen' session within your 'putty session'. I use screens a lot in my work, so I can tell you that you will not have a combination of 'screen' buffer & 'putty' buffer within your 'screen' session.

Setting the default number of scrollback lines by adding defscrollback 10000 to your ~/.screenrc file is the correct solution.

By the way, I use "defscrollback 200000" in my ./screenrc file.

Re-order columns of table in Oracle

Look at the package DBMS_Redefinition. It will rebuild the table with the new ordering. It can be done with the table online.

As Phil Brown noted, think carefully before doing this. However there is overhead in scanning the row for columns and moving data on update. Column ordering rules I use (in no particular order):

  • Group related columns together.
  • Not NULL columns before null-able columns.
  • Frequently searched un-indexed columns first.
  • Rarely filled null-able columns last.
  • Static columns first.
  • Updateable varchar columns later.
  • Indexed columns after other searchable columns.

These rules conflict and have not all been tested for performance on the latest release. Most have been tested in practice, but I didn't document the results. Placement options target one of three conflicting goals: easy to understand column placement; fast data retrieval; and minimal data movement on updates.

window.open target _self v window.location.href?

Definitely the second method is preferred because you don't have the overhead of another function invocation:

window.location.href = "webpage.htm";

Rendering JSON in controller

What exactly do you want to know? ActiveRecord has methods that serialize records into JSON. For instance, open up your rails console and enter ModelName.all.to_json and you will see JSON output. render :json essentially calls to_json and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback option to specify the name of the callback you would like to call via JSONP.

For instance, lets say we have a User model that looks like this: {name: 'Max', email:' [email protected]'}

We also have a controller that looks like this:

class UsersController < ApplicationController
    def show
        @user = User.find(params[:id])
        render json: @user
    end
end

Now, if we do an AJAX call using jQuery like this:

$.ajax({
    type: "GET",
    url: "/users/5",
    dataType: "json",
    success: function(data){
        alert(data.name) // Will alert Max
    }        
});

As you can see, we managed to get the User with id 5 from our rails app and use it in our JavaScript code because it was returned as a JSON object. The callback option just calls a JavaScript function of the named passed with the JSON object as the first and only argument.

To give an example of the callback option, take a look at the following:

class UsersController < ApplicationController
    def show
        @user = User.find(params[:id])
        render json: @user, callback: "testFunction"
    end
end

Now we can crate a JSONP request as follows:

function testFunction(data) {
    alert(data.name); // Will alert Max
};

var script = document.createElement("script");
script.src = "/users/5";

document.getElementsByTagName("head")[0].appendChild(script);

The motivation for using such a callback is typically to circumvent the browser protections that limit cross origin resource sharing (CORS). JSONP isn't used that much anymore, however, because other techniques exist for circumventing CORS that are safer and easier.

ASP.NET Web API session or something?

You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.

Request and response HTTP headers can also be used to pass information between service calls.

Simple way to create matrix of random numbers

For creating an array of random numbers NumPy provides array creation using:

  1. Real numbers

  2. Integers

For creating array using random Real numbers: there are 2 options

  1. random.rand (for uniform distribution of the generated random numbers )
  2. random.randn (for normal distribution of the generated random numbers )

random.rand

import numpy as np 
arr = np.random.rand(row_size, column_size) 

random.randn

import numpy as np 
arr = np.random.randn(row_size, column_size) 

For creating array using random Integers:

import numpy as np
numpy.random.randint(low, high=None, size=None, dtype='l')

where

  • low = Lowest (signed) integer to be drawn from the distribution
  • high(optional)= If provided, one above the largest (signed) integer to be drawn from the distribution
  • size(optional) = Output shape i.e. if the given shape is, e.g., (m, n, k), then m * n * k samples are drawn
  • dtype(optional) = Desired dtype of the result.

eg:

The given example will produce an array of random integers between 0 and 4, its size will be 5*5 and have 25 integers

arr2 = np.random.randint(0,5,size = (5,5))

in order to create 5 by 5 matrix, it should be modified to

arr2 = np.random.randint(0,5,size = (5,5)), change the multiplication symbol* to a comma ,#

[[2 1 1 0 1][3 2 1 4 3][2 3 0 3 3][1 3 1 0 0][4 1 2 0 1]]

eg2:

The given example will produce an array of random integers between 0 and 1, its size will be 1*10 and will have 10 integers

arr3= np.random.randint(2, size = 10)

[0 0 0 0 1 1 0 0 1 1]

Copy folder recursively, excluding some folders

Similar to Jeff's idea (untested):

find . -name * -print0 | grep -v "exclude" | xargs -0 -I {} cp -a {} destination/