Programs & Examples On #Move constructor

In C++11 a move constructor is a special member function similar to a copy constructor, but taking an rvalue-reference parameter.

jQuery form validation on button click

Within your click handler, the mistake is the .validate() method; it only initializes the plugin, it does not validate the form.

To eliminate the need to have a submit button within the form, use .valid() to trigger a validation check...

$('#btn').on('click', function() {
    $("#form1").valid();
});

jsFiddle Demo

.validate() - to initialize the plugin (with options) once on DOM ready.

.valid() - to check validation state (boolean value) or to trigger a validation test on the form at any time.

Otherwise, if you had a type="submit" button within the form container, you would not need a special click handler and the .valid() method, as the plugin would capture that automatically.

Demo without click handler


EDIT:

You also have two issues within your HTML...

<input id="field1" type="text" class="required">
  • You don't need class="required" when declaring rules within .validate(). It's redundant and superfluous.

  • The name attribute is missing. Rules are declared within .validate() by their name. The plugin depends upon unique name attributes to keep track of the inputs.

Should be...

<input name="field1" id="field1" type="text" />

Found 'OR 1=1/* sql injection in my newsletter database

'OR 1=1 is an attempt to make a query succeed no matter what
The /* is an attempt to start a multiline comment so the rest of the query is ignored.

An example would be

SELECT userid 
FROM users 
WHERE username = ''OR 1=1/*' 
    AND password = ''
    AND domain = ''

As you can see if you were to populate the username field without escaping the ' no matter what credentials the user passes in the query would return all userids in the system likely granting access to the attacker (possibly admin access if admin is your first user). You will also notice the remainder of the query would be commented out because of the /* including the real '.

The fact that you can see the value in your database means that it was escaped and that particular attack did not succeed. However, you should investigate if any other attempts were made.

No generated R.java file in my project

I just had a problem where a previously working project stopped working with everything that referenced R being posted as errors because R.java was not being generated.

** * CHECK THE CONSOLE VIEW TOO **

I had (using finder) made a backup of the main icon (not even used) so one of the res folders (hdpi) had

icon.png copy of icon.png

Console indicated that "copy of icon.png" was not a valid file name. No errors were flagged anywhere else - no red X in the res folders....

but replacing the spaces with "_" and it is all back to normal....

SET versus SELECT when assigning variables?

I believe SET is ANSI standard whereas the SELECT is not. Also note the different behavior of SET vs. SELECT in the example below when a value is not found.

declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */

set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */

Convert String to Uri

If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.

val uri = myUriString.toUri()

To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle

  repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:1.0.0-rc01'
}

How to make full screen background in a web page

its very simple use this css (replace image.jpg with your background image)

body{height:100%;
   width:100%;
   background-image:url(image.jpg);/*your background image*/  
   background-repeat:no-repeat;/*we want to have one single image not a repeated one*/  
   background-size:cover;/*this sets the image to fullscreen covering the whole screen*/  
   /*css hack for ie*/     
   filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.image.jpg',sizingMethod='scale');
   -ms-filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='image.jpg',sizingMethod='scale')";
}

how to make log4j to write to the console as well

Your log4j File should look something like below read comments.

# Define the types of logger and level of logging    
log4j.rootLogger = DEBUG,console, FILE

# Define the File appender    
log4j.appender.FILE=org.apache.log4j.FileAppender    

# Define Console Appender    
log4j.appender.console=org.apache.log4j.ConsoleAppender    

# Define the layout for console appender. If you do not 
# define it, you will get an error    
log4j.appender.console.layout=org.apache.log4j.PatternLayout

# Set the name of the file    
log4j.appender.FILE.File=log.out

# Set the immediate flush to true (default)    
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode    
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite    
log4j.appender.FILE.Append=false

# Define the layout for file appender    
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout    
log4j.appender.FILE.layout.conversionPattern=%m%n

JMS Topic vs Queues

As for the order preservation, see this ActiveMQ page. In short: order is preserved for single consumers, but with multiple consumers order of delivery is not guaranteed.

Directory.GetFiles: how to get only filename, not full path?

Try,

  string[] files =  new DirectoryInfo(dir).GetFiles().Select(o => o.Name).ToArray();

Above line may throw UnauthorizedAccessException. To handle this check out below link

C# Handle System.UnauthorizedAccessException in LINQ

Usage of MySQL's "IF EXISTS"

if exists(select * from db1.table1 where sno=1 )
begin
select * from db1.table1 where sno=1 
end
else if (select * from db2.table1 where sno=1 )
begin
select * from db2.table1 where sno=1 
end
else
begin
print 'the record does not exits'
end

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

How to check if JavaScript object is JSON

An JSON object is an object. To check whether a type is an object type, evaluate the constructor property.

function isObject(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Object;
}

The same applies to all other types:

function isArray(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Array;
}

function isBoolean(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Boolean;
}

function isFunction(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Function;
}

function isNumber(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Number;
}

function isString(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == String;
}

function isInstanced(obj)
{
    if(obj === undefined || obj === null) { return false; }

    if(isArray(obj)) { return false; }
    if(isBoolean(obj)) { return false; }
    if(isFunction(obj)) { return false; }
    if(isNumber(obj)) { return false; }
    if(isObject(obj)) { return false; }
    if(isString(obj)) { return false; }

    return true;
}

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

How to set socket timeout in C when making multiple connections?

connect timeout has to be handled with a non-blocking socket (GNU LibC documentation on connect). You get connect to return immediately and then use select to wait with a timeout for the connection to complete.

This is also explained here : Operation now in progress error on connect( function) error.

int wait_on_sock(int sock, long timeout, int r, int w)
{
    struct timeval tv = {0,0};
    fd_set fdset;
    fd_set *rfds, *wfds;
    int n, so_error;
    unsigned so_len;

    FD_ZERO (&fdset);
    FD_SET  (sock, &fdset);
    tv.tv_sec = timeout;
    tv.tv_usec = 0;

    TRACES ("wait in progress tv={%ld,%ld} ...\n",
            tv.tv_sec, tv.tv_usec);

    if (r) rfds = &fdset; else rfds = NULL;
    if (w) wfds = &fdset; else wfds = NULL;

    TEMP_FAILURE_RETRY (n = select (sock+1, rfds, wfds, NULL, &tv));
    switch (n) {
    case 0:
        ERROR ("wait timed out\n");
        return -errno;
    case -1:
        ERROR_SYS ("error during wait\n");
        return -errno;
    default:
        // select tell us that sock is ready, test it
        so_len = sizeof(so_error);
        so_error = 0;
        getsockopt (sock, SOL_SOCKET, SO_ERROR, &so_error, &so_len);
        if (so_error == 0)
            return 0;
        errno = so_error;
        ERROR_SYS ("wait failed\n");
        return -errno;
    }
}

Select from table by knowing only date without time (ORACLE)

trunc(my_date,'DD') will give you just the date and not the time in Oracle.

ESLint Parsing error: Unexpected token

Just for the record, if you are using eslint-plugin-vue, the correct place to add 'parser': 'babel-eslint' is inside parserOptions param.

  'parserOptions': {
    'parser': 'babel-eslint',
    'ecmaVersion': 2018,
    'sourceType': 'module'
  }

https://eslint.vuejs.org/user-guide/#faq

How to change the color of an image on hover

If I understand correctly then it would be easier if you gave your image a transparent background and set the background container's background-color property without having to use filters and so on.

http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html

Shows you how to use filters in IE. Maybe if you leverage something from that. Not very cross-browser compatible though. Another option might be to have two images and use them as background-images (rather than img tags), swap one out after another using the :hover pseudo selector.

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Proceed following steps at ubuntu-18.04:

Step 1) locate sql.lib.php

It will show something like:

/usr/share/phpmyadmin/libraries/sql.lib.php

Step 2) Open terminal (Alt t) and write:

sudo /usr/sbin/pma-configure

Step 3)sudo gedit /usr/share/phpmyadmin/libraries/sql.lib.php and search below function:

 

    function PMA_isRememberSortingOrder($analyzed_sql_results)
     {
        return $GLOBALS['cfg']['RememberSorting']
            && ! ($analyzed_sql_results['is_count']
                || $analyzed_sql_results['is_export']
                || $analyzed_sql_results['is_func']
                || $analyzed_sql_results['is_analyse'])
            && $analyzed_sql_results['select_from']
            && ((empty($analyzed_sql_results['select_expr']))
                || (count($analyzed_sql_results['select_expr'] == 1)
                    && ($analyzed_sql_results['select_expr'][0] == '*')))
            && count($analyzed_sql_results['select_tables']) == 1;
     }

Step 4) Replace above function with:


     function PMA_isRememberSortingOrder($analyzed_sql_results)
     {
        return $GLOBALS['cfg']['RememberSorting']
            && ! ($analyzed_sql_results['is_count']
                || $analyzed_sql_results['is_export']
                || $analyzed_sql_results['is_func']
                || $analyzed_sql_results['is_analyse'])
            && $analyzed_sql_results['select_from']
            && ((empty($analyzed_sql_results['select_expr']))
                || (count($analyzed_sql_results['select_expr']) == 1)
                    && ($analyzed_sql_results['select_expr'][0] == '*'))
            && count($analyzed_sql_results['select_tables']) == 1;
     }

Step 4) Save & close file and below command on terminal

sudo /usr/sbin/pma-secure

Step 5) sudo service mysql reload

Step 6) sudo service apache2 reload

It works for me.. Goodluck

Throw away local commits in Git

For local commits which are not being pushed, you can also use git rebase -i to delete or squash a commit.

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

How to handle an IF STATEMENT in a Mustache template?

In general, you use the # syntax:

{{#a_boolean}}
  I only show up if the boolean was true.
{{/a_boolean}}

The goal is to move as much logic as possible out of the template (which makes sense).

Remove all whitespaces from NSString

I prefer using regex like this:

NSString *myString = @"this is a test";
NSString *myNewString = [myString stringByReplacingOccurrencesOfString:@"\\s"
                                     withString:@""
                                        options:NSRegularExpressionSearch
                                          range:NSMakeRange(0, [myStringlength])];
 //myNewString will be @"thisisatest"

You can make yourself a category on NSString to make life even easier:

- (NSString *) removeAllWhitespace
{
    return [self stringByReplacingOccurrencesOfString:@"\\s" withString:@""
                                              options:NSRegularExpressionSearch
                                                range:NSMakeRange(0, [self length])];

}

Here is a unit test method on it too:

- (void) testRemoveAllWhitespace
{
    NSString *testResult = nil;

    NSArray *testStringsArray        = @[@""
                                         ,@"    "
                                         ,@"  basicTest    "
                                         ,@"  another Test \n"
                                         ,@"a b c d e f g"
                                         ,@"\n\tA\t\t \t \nB    \f  C \t  ,d,\ve   F\r\r\r"
                                         ,@"  landscape, portrait,     ,,,up_side-down   ;asdf;  lkjfasdf0qi4jr0213 ua;;;;af!@@##$$ %^^ & *  * ()+  +   "
                                         ];

    NSArray *expectedResultsArray   = @[@""
                                        ,@""
                                        ,@"basicTest"
                                        ,@"anotherTest"
                                        ,@"abcdefg"
                                        ,@"ABC,d,eF"
                                        ,@"landscape,portrait,,,,up_side-down;asdf;lkjfasdf0qi4jr0213ua;;;;af!@@##$$%^^&**()++"
                                        ];

    for (int i=0; i < [testStringsArray count]; i++)
    {
        testResult = [testStringsArray[i] removeAllWhitespace];
        STAssertTrue([testResult isEqualToString:expectedResultsArray[i]], @"Expected: \"%@\" to become: \"%@\", but result was \"%@\"",
                     testStringsArray[i], expectedResultsArray[i], testResult);
    }
}

Load local images in React.js

we don't need base64 , just give your image path and dimensions as shown below.

import Logo from './Logo.png' //local path

        var doc=new jsPDF("p", "mm", "a4");
        var img = new Image();
        img.src =Logo;
        doc.addImage(img, 'png', 10, 78, 12, 15)

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

How do I keep two side-by-side divs the same height?

This is a common problem which many have encountered, but luckily some smart minds like Ed Eliot's on his blog have posted their solutions online.

Basically what you do is make both divs/columns very tall by adding a padding-bottom: 100% and then "trick the browser" into thinking they aren't that tall using margin-bottom: -100%. It is better explained by Ed Eliot on his blog, which also includes many examples.

_x000D_
_x000D_
.container {_x000D_
    overflow: hidden;_x000D_
}_x000D_
.column {_x000D_
    float: left;_x000D_
    margin: 20px;_x000D_
    background-color: grey;_x000D_
    padding-bottom: 100%;_x000D_
    margin-bottom: -100%;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
    <div class="column">_x000D_
        Some content!<br>_x000D_
        Some content!<br>_x000D_
        Some content!<br>_x000D_
        Some content!<br>_x000D_
        Some content!<br>_x000D_
    </div>_x000D_
_x000D_
    <div class="column">_x000D_
        Something_x000D_
    </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Git blame -- prior commits?

You might want to check out:

git gui blame <filename>

Gives you a nice graphical display of changes like "git blame" but with clickable links per line, to move into earlier commits. Hover over the links to get a popup with commit details. Not my credits... found it here:

http://zsoltfabok.com/blog/2012/02/git-blame-line-history/

git gui is a graphical Tcl/Tc interface to git. Without any other params it starts a pretty simple but useful graphical app for committing files, hunks or even single lines and other similar commands like amend, revert, push... It's part of the git stock suite. On windows it is included in the installer. On debian - I don't know about other *nix systems - it has to be installed separately:

apt-get install git-gui

From the docs:

https://git-scm.com/docs/git-gui

DESCRIPTION

A Tcl/Tk based graphical user interface to Git. git gui focuses on allowing users to make changes to their repository by making new commits, amending existing ones, creating branches, performing local merges, and fetching/pushing to remote repositories.

Unlike gitk, git gui focuses on commit generation and single file annotation and does not show project history. It does however supply menu actions to start a gitk session from within git gui.

git gui is known to work on all popular UNIX systems, Mac OS X, and Windows (under both Cygwin and MSYS). To the extent possible OS specific user interface guidelines are followed, making git gui a fairly native interface for users.

COMMANDS

blame

Start a blame viewer on the specified file on the given version (or working directory if not specified).

browser

Start a tree browser showing all files in the specified commit. Files selected through the browser are opened in the blame viewer.

citool

Start git gui and arrange to make exactly one commit before exiting and returning to the shell. The interface is limited to only commit actions, slightly reducing the application’s startup time and simplifying the menubar.

version

Display the currently running version of git gui.

ASP.NET MVC passing an ID in an ActionLink to the controller

Doesn't look like you are using the correct overload of ActionLink. Try this:-

<%=Html.ActionLink("Modify Villa", "Modify", new {id = "1"})%>

This assumes your view is under the /Views/Villa folder. If not then I suspect you need:-

<%=Html.ActionLink("Modify Villa", "Modify", "Villa", new {id = "1"}, null)%>

How to Convert the value in DataTable into a string array in c#

Very easy:

var stringArr = dataTable.Rows[0].ItemArray.Select(x => x.ToString()).ToArray();

Where DataRow.ItemArray property is an array of objects containing the values of the row for each columns of the data table.

What does the red exclamation point icon in Eclipse mean?

I had the same problem and Andrew is correct. Check your classpath variable "M2_REPO". It probably points to an invalid location of your local maven repo.

In my case I was using mvn eclipse:eclipse on the command line and this plugin was setting the M2_REPO classpath variable. Eclipse couldn't find my maven settings.xml in my home directory and as a result was incorrectly the M2_REPO classpath variable. My solution was to restart eclipse and it picked up my settings.xml and removed the red exclamation on my projects.

I got some more information from this guy: http://www.mkyong.com/maven/how-to-configure-m2_repo-variable-in-eclipse-ide/

How can I delete a newline if it is the last character in a file?

Assuming Unix file type and you only want the last newline this works.

sed -e '${/^$/d}'

It will not work on multiple newlines...

* Works only if the last line is a blank line.

Access XAMPP Localhost from Internet

you have to open a port of the service in you router then try you puplic ip out of your all network cause if you try it from your network , the puplic ip will always redirect you to your router but from the outside it will redirect to the server you have

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

Please refer the below-detailed explanation.

I have used Built-in data frame in R, called mtcars.

> mtcars 
               mpg cyl disp  hp drat   wt ... 
Mazda RX4     21.0   6  160 110 3.90 2.62 ... 
Mazda RX4 Wag 21.0   6  160 110 3.90 2.88 ... 
Datsun 710    22.8   4  108  93 3.85 2.32 ... 
           ............

The top line of the table is called the header which contains the column names. Each horizontal line afterward denotes a data row, which begins with the name of the row, and then followed by the actual data. Each data member of a row is called a cell.

single square bracket "[]" operator

To retrieve data in a cell, we would enter its row and column coordinates in the single square bracket "[]" operator. The two coordinates are separated by a comma. In other words, the coordinates begin with row position, then followed by a comma, and ends with the column position. The order is important.

Eg 1:- Here is the cell value from the first row, second column of mtcars.

> mtcars[1, 2] 
[1] 6

Eg 2:- Furthermore, we can use the row and column names instead of the numeric coordinates.

> mtcars["Mazda RX4", "cyl"] 
[1] 6 

Double square bracket "[[]]" operator

We reference a data frame column with the double square bracket "[[]]" operator.

Eg 1:- To retrieve the ninth column vector of the built-in data set mtcars, we write mtcars[[9]].

mtcars[[9]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...

Eg 2:- We can retrieve the same column vector by its name.

mtcars[["am"]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...

How do I get indices of N maximum values in a NumPy array?

This code works for a numpy 2D matrix array:

mat = np.array([[1, 3], [2, 5]]) # numpy matrix
 
n = 2  # n
n_largest_mat = np.sort(mat, axis=None)[-n:] # n_largest 
tf_n_largest = np.zeros((2,2), dtype=bool) # all false matrix
for x in n_largest_mat: 
  tf_n_largest = (tf_n_largest) | (mat == x) # true-false  

n_largest_elems = mat[tf_n_largest] # true-false indexing 

This produces a true-false n_largest matrix indexing that also works to extract n_largest elements from a matrix array

How to plot a subset of a data frame in R?

This is how I would do it, in order to get in the var4 restriction:

dfr<-data.frame(var1=rnorm(100), var2=rnorm(100), var3=rnorm(100, 160, 10), var4=rnorm(100, 27, 6))
plot( subset( dfr, var3 < 155 & var4 > 27, select = c( var1, var2 ) ) )

Rgds, Rainer

How to add a Java Properties file to my Java Project in Eclipse

If you have created a Java Project in eclipse by using the 'from existing source' option then it should work as it did before. To be more precise File > New Java Project. In the Contents section select 'Create project from existing source' and then select your existing project folder. The wizard will take care of the rest.

What is the right way to treat argparse.Namespace() as a dictionary?

Is it proper to "reach into" an object and use its dict property?

In general, I would say "no". However Namespace has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.

On the other hand, Namespace does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__, but the limits of my imagination are not the same as yours.

The application has stopped unexpectedly: How to Debug?

If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.

The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.

Tokenizing strings in C

Here's an example of strtok usage, keep in mind that strtok is destructive of its input string (and therefore can't ever be used on a string constant

char *p = strtok(str, " ");
while(p != NULL) {
    printf("%s\n", p);
    p = strtok(NULL, " ");
}

Basically the thing to note is that passing a NULL as the first parameter to strtok tells it to get the next token from the string it was previously tokenizing.

Finding even or odd ID values

<> means not equal. however, in some versions of SQL, you can write !=

Convert Pixels to Points

points = (pixels / 96) * 72 on a standard XP/Vista/7 machine (factory defaults)

points = (pixels / 72) * 72 on a standard Mac running OSX (Factory defaults)

Windows runs as default at 96dpi (display) Macs run as default at 72 dpi (display)

72 POSTSCRIPT Points = 1 inch 12 POSTSCRIPT Points = 1 POSTSCRIPT Pica 6 POSTSCRIPT Picas = 72 Points = 1 inch

1 point = 1/72 inches = 25.4/72 mm = 0.3527 mm

DPI = Dots Per Inch PPI = Pixels Per Inch LPI = Lines per inch

More info if using em as measuring

16px = 1em (default for normal text) 8em = 16px * 8 Pixels/16 = em

SPAN vs DIV (inline-block)

I think it will help you to understand the basic differences between Inline-Elements (e.g. span) and Block-Elements (e.g. div), in order to understand why "display: inline-block" is so useful.

Problem: inline elements (e.g. span, a, button, input etc.) take "margin" only horizontally (margin-left and margin-right) on, not vertically. Vertical spacing works only on block elements (or if "display:block" is set)

Solution: Only through "display: inline-block" will also take the vertical distance (top and bottom). Reason: Inline element Span, behaves now like a block element to the outside, but like an inline element inside

Here Code Examples:

_x000D_
_x000D_
 /* Inlineelement */

        div,
        span {
            margin: 30px;
        }

        span {
            outline: firebrick dotted medium;
            background-color: antiquewhite;
        }

        span.mitDisplayBlock {
            background: #a2a2a2;
            display: block;
            width: 200px;
            height: 200px;
        }

        span.beispielMargin {
            margin: 20px;
        }

        span.beispielMarginDisplayInlineBlock {
            display: inline-block;
        }

        span.beispielMarginDisplayInline {
            display: inline;
        }

        span.beispielMarginDisplayBlock {
            display: block;
        }

        /* Blockelement */

        div {
            outline: orange dotted medium;
            background-color: deepskyblue;
        }

        .paddingDiv {
            padding: 20px;
            background-color: blanchedalmond;
        }

        .marginDivWrapper {
            background-color: aliceblue;

        }

        .marginDiv {
            margin: 20px;
            background-color: blanchedalmond;
        }
    </style>
    <style>
        /* Nur für das w3school Bild */

        #w3_DIV_1 {
            bottom: 0px;
            box-sizing: border-box;
            height: 391px;
            left: 0px;
            position: relative;
            right: 0px;
            text-size-adjust: 100%;
            top: 0px;
            width: 913.984px;
            perspective-origin: 456.984px 195.5px;
            transform-origin: 456.984px 195.5px;
            background: rgb(241, 241, 241) none repeat scroll 0% 0% / auto padding-box border-box;
            border: 2px dashed rgb(187, 187, 187);
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            padding: 45px;
            transition: all 0.25s ease-in-out 0s;
        }

        /*#w3_DIV_1*/

        #w3_DIV_1:before {
            bottom: 349.047px;
            box-sizing: border-box;
            content: '"Margin"';
            display: block;
            height: 31px;
            left: 0px;
            position: absolute;
            right: 0px;
            text-align: center;
            text-size-adjust: 100%;
            top: 6.95312px;
            width: 909.984px;
            perspective-origin: 454.984px 15.5px;
            transform-origin: 454.984px 15.5px;
            font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
        }

        /*#w3_DIV_1:before*/

        #w3_DIV_2 {
            bottom: 0px;
            box-sizing: border-box;
            color: black;
            height: 297px;
            left: 0px;
            position: relative;
            right: 0px;
            text-decoration: none solid rgb(255, 255, 255);
            text-size-adjust: 100%;
            top: 0px;
            width: 819.984px;
            column-rule-color: rgb(255, 255, 255);
            perspective-origin: 409.984px 148.5px;
            transform-origin: 409.984px 148.5px;
            caret-color: rgb(255, 255, 255);
            background: rgb(76, 175, 80) none repeat scroll 0% 0% / auto padding-box border-box;
            border: 0px none rgb(255, 255, 255);
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            outline: rgb(255, 255, 255) none 0px;
            padding: 45px;
        }

        /*#w3_DIV_2*/

        #w3_DIV_2:before {
            bottom: 258.578px;
            box-sizing: border-box;
            content: '"Border"';
            display: block;
            height: 31px;
            left: 0px;
            position: absolute;
            right: 0px;
            text-align: center;
            text-size-adjust: 100%;
            top: 7.42188px;
            width: 819.984px;
            perspective-origin: 409.984px 15.5px;
            transform-origin: 409.984px 15.5px;
            font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
        }

        /*#w3_DIV_2:before*/

        #w3_DIV_3 {
            bottom: 0px;
            box-sizing: border-box;
            height: 207px;
            left: 0px;
            position: relative;
            right: 0px;
            text-size-adjust: 100%;
            top: 0px;
            width: 729.984px;
            perspective-origin: 364.984px 103.5px;
            transform-origin: 364.984px 103.5px;
            background: rgb(241, 241, 241) none repeat scroll 0% 0% / auto padding-box border-box;
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            padding: 45px;
        }

        /*#w3_DIV_3*/

        #w3_DIV_3:before {
            bottom: 168.344px;
            box-sizing: border-box;
            content: '"Padding"';
            display: block;
            height: 31px;
            left: 3.64062px;
            position: absolute;
            right: -3.64062px;
            text-align: center;
            text-size-adjust: 100%;
            top: 7.65625px;
            width: 729.984px;
            perspective-origin: 364.984px 15.5px;
            transform-origin: 364.984px 15.5px;
            font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
        }

        /*#w3_DIV_3:before*/

        #w3_DIV_4 {
            bottom: 0px;
            box-sizing: border-box;
            height: 117px;
            left: 0px;
            position: relative;
            right: 0px;
            text-size-adjust: 100%;
            top: 0px;
            width: 639.984px;
            perspective-origin: 319.984px 58.5px;
            transform-origin: 319.984px 58.5px;
            background: rgb(191, 201, 101) none repeat scroll 0% 0% / auto padding-box border-box;
            border: 2px dashed rgb(187, 187, 187);
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            padding: 20px;
        }

        /*#w3_DIV_4*/

        #w3_DIV_4:before {
            box-sizing: border-box;
            content: '"Content"';
            display: block;
            height: 73px;
            text-align: center;
            text-size-adjust: 100%;
            width: 595.984px;
            perspective-origin: 297.984px 36.5px;
            transform-origin: 297.984px 36.5px;
            font: normal normal 400 normal 21px / 73.5px Lato, sans-serif;
        }

        /*#w3_DIV_4:before*/
_x000D_
   <h1> The Box model - content, padding, border, margin</h1>
    <h2> Inline element - span</h2>
    <span>Info: A span element can not have height and width (not without "display: block"), which means it takes the fixed inline size </span>

    <span class="beispielMargin">
        <b>Problem:</b> inline elements (eg span, a, button, input etc.) take "margin" only vertically (margin-left and margin-right)
        on, not horizontal. Vertical spacing works only on block elements (or if display: block is set) </span>

    <span class="beispielMarginDisplayInlineBlock">
        <b>Solution</b> Only through
        <b> "display: inline-block" </ b> will also take the vertical distance (top and bottom). Reason: Inline element Span,
        behaves now like a block element to the outside, but like an inline element inside</span>

    <span class="beispielMarginDisplayInline">Example: here "display: inline". See the margin with Inspector!</span>

    <span class="beispielMarginDisplayBlock">Example: here "display: block". See the margin with Inspector!</span>

    <span class="beispielMarginDisplayInlineBlock">Example: here "display: inline-block". See the margin with Inspector! </span>

    <span class="mitDisplayBlock">Only with the "Display" -property and "block" -Value in addition, a width and height can be assigned. "span" is then like
        a "div" block element.  </span>

    <h2>Inline-Element - Div</h2>
    <div> A div automatically takes "display: block." </ div>
    <div class = "paddingDiv"> Padding is for padding </ div>

    <div class="marginDivWrapper">
Wrapper encapsulates the example "marginDiv" to clarify the "margin" (distance from inner element "marginDiv" to the text)
        of the outer element "marginDivWrapper". Here 20px;)
        
    <div class = "marginDiv"> margin is for the margins </ div>
        And there, too, 20px;
    </div>

    <h2>w3school sample image </h2>
    source:
    <a href="https://www.w3schools.com/css/css_boxmodel.asp">CSS Box Model</a>
    <div id="w3_DIV_1">
        <div id="w3_DIV_2">
            <div id="w3_DIV_3">
                <div id="w3_DIV_4">
                </div>
            </div>
        </div>
    </div>
_x000D_
_x000D_
_x000D_

`React/RCTBridgeModule.h` file not found

I've encountered this issue while upgrading from 0.58.4 to new react-native version 0.60.4. Nothing from what i found on the internet helped me, but I managed to get it working:

Go to build settings, search for 'Header search paths', select the entry, press DELETE button.

I had these values overriden, and looks like they fell back to defaults after deletion. Also Cocoapods was complaining about it with messages in Terminal after pod install:

[!] The `app [Release]` target overrides the `HEADER_SEARCH_PATHS` build setting defined in `Pods/Target Support Files/Pods-app/Pods-app.release.xcconfig'. This can lead to problems with the CocoaPods installation

What is the { get; set; } syntax in C#?

It is a shortcut to expose data members as public so that you don't need to explicitly create a private data members. C# will creates a private data member for you.

You could just make your data members public without using this shortcut but then if you decided to change the implementation of the data member to have some logic then you would need to break the interface. So in short it is a shortcut to create more flexible code.

LAST_INSERT_ID() MySQL

Just to add for Rodrigo post, instead of LAST_INSERT_ID() in query you can use SELECT MAX(id) FROM table1;, but you must use (),

INSERT INTO table1 (title,userid) VALUES ('test', 1)
INSERT INTO table2 (parentid,otherid,userid) VALUES ( (SELECT MAX(id) FROM table1), 4, 1)

Authenticating in PHP using LDAP through Active Directory

For those looking for a complete example check out http://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/.

I have tested this connecting to both Windows Server 2003 and Windows Server 2008 R2 domain controllers from a Windows Server 2003 Web Server (IIS6) and from a windows server 2012 enterprise running IIS 8.

How do you reset the stored credentials in 'git credential-osxkeychain'?

Try this in your command line.

git config --local credential.helper ""

It works for me every time when I have multiple GitHub accounts in OSX keychain

Find duplicate records in MySQL

The key is to rewrite this query so that it can be used as a subquery.

SELECT firstname, 
   lastname, 
   list.address 
FROM list
   INNER JOIN (SELECT address
               FROM   list
               GROUP  BY address
               HAVING COUNT(id) > 1) dup
           ON list.address = dup.address;

$(...).datepicker is not a function - JQuery - Bootstrap

You need to include jQueryUI

_x000D_
_x000D_
$(document).ready(function() {_x000D_
_x000D_
    $('.datepicker').datepicker({_x000D_
        format: 'dd/mm/yyyy'_x000D_
    });_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>_x000D_
<script   src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"   integrity="sha256-xI/qyl9vpwWFOXz7+x/9WkG5j/SVnSw21viy8fWwbeE="   crossorigin="anonymous"></script>_x000D_
<script src="<?php echo BASE_URL; ?>/js/moment.min.js"></script>_x000D_
<script src="<?php echo BASE_URL; ?>/js/bootstrap.min.js"></script>_x000D_
<script src="<?php echo BASE_URL; ?>/js/bootstrap-datetimepicker.min.js"></script>_x000D_
<script src="<?php echo BASE_URL; ?>/js/main.js"></script>_x000D_
_x000D_
<div class="col-md-6">_x000D_
    <div class="form-group">_x000D_
         <label for="geboortedatum">Geboortedatum:</label>_x000D_
         <div class="input-group datepicker" data-provide="datepicker">_x000D_
               <input type="text" name="geboortedatum" id="geboortedatum" class="form-control">_x000D_
               <div class="input-group-addon">_x000D_
                   <span class="glyphicon glyphicon-th"></span>_x000D_
               </div>_x000D_
         </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Here is a Solution for Jupyter and Python3:

I droped my images in a folder named ImageTest. My directory is:

C:\Users\MyPcName\ImageTest\image.png

To show the image I used this expression:

![title](/notebooks/ImageTest/image.png "ShowMyImage")

Also watch out for / and \

How to remove all duplicate items from a list

Use set():

woduplicates = set(lseparatedOrblist)

Returns a set without duplicates. If you, for some reason, need a list back:

woduplicates = list(set(lseperatedOrblist))

This will, however, have a different order than your original list.

Windows batch - concatenate multiple text files into one

Try this:

@echo off
set yyyy=%date:~6,4%
set mm=%date:~3,2%
set dd=%date:~0,2%

set /p temp= "Enter the name of text file: "
FOR /F "tokens=* delims=" %%x in (texto1.txt, texto2.txt, texto3.txt) DO echo %%x >> day_%temp%.txt

This code ask you to set the name of the file after "day_" where you can input the date. If you want to name your file like the actual date you can do this:

FOR /F "tokens=* delims=" %%x in (texto1.txt, texto2.txt, texto3.txt) DO echo %%x >> day_%yyyy%-%mm%-%dd%.txt

Equal height rows in a flex container

You can with flexbox:

_x000D_
_x000D_
ul.list {
    padding: 0;
    list-style: none;
    display: flex;
    align-items: stretch;
    justify-items: center;
    flex-wrap: wrap;
    justify-content: center;
}
li {
    width: 100px;
    padding: .5rem;
    border-radius: 1rem;
    background: yellow;
    margin: 0 5px;
}
_x000D_
<ul class="list">
  <li>title 1</li>
  <li>title 2<br>new line</li>
  <li>title 3<br>new<br>line</li>
</ul>
_x000D_
_x000D_
_x000D_

How to conclude your merge of a file?

The easiest solution I found for this:

git commit -m "fixing merge conflicts"
git push

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

The cleanest way is to copy the following classes: ShareActionProvider, ActivityChooserView, ActivityChooserModel. Add the ability to filter the intents in the ActivityChooserModel, and the appropriate support methods in the ShareActionProvider. I created the necessary classes, you can copy them into your project (https://gist.github.com/saulpower/10557956). This not only adds the ability to filter the apps you would like to share with (if you know the package name), but also to turn off history.

private final String[] INTENT_FILTER = new String[] {
    "com.twitter.android",
    "com.facebook.katana"
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.journal_entry_menu, menu);

    // Set up ShareActionProvider's default share intent
    MenuItem shareItem = menu.findItem(R.id.action_share);

    if (shareItem instanceof SupportMenuItem) {
        mShareActionProvider = new ShareActionProvider(this);
        mShareActionProvider.setShareIntent(ShareUtils.share(mJournalEntry));
        mShareActionProvider.setIntentFilter(Arrays.asList(INTENT_FILTER));
        mShareActionProvider.setShowHistory(false);
        ((SupportMenuItem) shareItem).setSupportActionProvider(mShareActionProvider);
    }

    return super.onCreateOptionsMenu(menu);
}

Python: How to create a unique file name?

I came across this question, and I will add my solution for those who may be looking for something similar. My approach was just to make a random file name from ascii characters. It will be unique with a good probability.

from random import sample
from string import digits, ascii_uppercase, ascii_lowercase
from tempfile import gettempdir
from os import path

def rand_fname(suffix, length=8):
    chars = ascii_lowercase + ascii_uppercase + digits

    fname = path.join(gettempdir(), 'tmp-'
                + ''.join(sample(chars, length)) + suffix)

    return fname if not path.exists(fname) \
                else rand_fname(suffix, length)

Write to text file without overwriting in Java

For some reason, none of the other methods worked for me...So i tried this and worked. Hope it helps..

JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file\n hi \n hello \n hola";
try 
{
    RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
    long length = raf.length();
    System.out.println(length);
    raf.setLength(length + 1); //+ (integer value) for spacing
    raf.seek(raf.length());
    raf.writeBytes(Content);
    raf.close();
} 
catch (Exception e) {
    System.out.println(e);
}

What is the default value for Guid?

To extend answers above, you cannot use Guid default value with Guid.Empty as an optional argument in method, indexer or delegate definition, because it will give you compile time error. Use default(Guid) or new Guid() instead.

'float' vs. 'double' precision

A float has 23 bits of precision, and a double has 52.

How to insert a picture into Excel at a specified cell position with VBA

Firstly, of all I recommend that the pictures are in the same folder as the workbook. You need to enter some codes in the Worksheet_Change procedure of the worksheet. For example, we can enter the following codes to add the image that with the same name as the value of cell in column A to the cell in column D:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim pic As Picture
If Intersect(Target, [A:A]) Is Nothing Then Exit Sub
On Error GoTo son

For Each pic In ActiveSheet.Pictures
    If Not Application.Intersect(pic.TopLeftCell, Range(Target.Offset(0, 3).Address)) Is Nothing Then
        pic.Delete
    End If
Next pic

ActiveSheet.Pictures.Insert(ThisWorkbook.Path & "\" & Target.Value & ".jpg").Select
Selection.Top = Target.Offset(0, 2).Top
Selection.Left = Target.Offset(0, 3).Left
Selection.ShapeRange.LockAspectRatio = msoFalse
Selection.ShapeRange.Height = Target.Offset(0, 2).Height
Selection.ShapeRange.Width = Target.Offset(0, 3).Width
son:

End Sub

With the codes above, the picture is sized according to the cell it is added to.

Details and sample file here : Vba Insert image to cell

enter image description here

Link to "pin it" on pinterest without generating a button

So you want the code to the pin it button without installing the button? If so just paste this code in the place of the url of the page you're pinning from. It should function as a pin it button without the button.

javascript:void((function(){var%20e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);document.body.appendChild(e)})());

Javascript code for showing yesterday's date and todays date

Get yesterday date in javascript

You have to run code and check it output

_x000D_
_x000D_
    var today = new Date();_x000D_
    var yesterday = new Date(today);_x000D_
    _x000D_
    yesterday.setDate(today.getDate() - 1);_x000D_
    console.log("Original Date : ",yesterday);_x000D_
_x000D_
    const monthNames = [_x000D_
  "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"_x000D_
];_x000D_
    var month = today.getMonth() + 1_x000D_
    yesterday = yesterday.getDate() + ' ' + monthNames[month] + ' ' + yesterday.getFullYear()_x000D_
   _x000D_
    console.log("Modify Date : ",yesterday);
_x000D_
_x000D_
_x000D_

How to fix getImageData() error The canvas has been tainted by cross-origin data?

You are "tainting" the canvas by loading from a cross origins domain. Check out this MDN article:

https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image

Converting <br /> into a new line for use in a text area

Here is another approach.

class orbisius_custom_string {
    /**
     * The reverse of nl2br. Handles <br/> <br/> <br />
     * usage: orbisius_custom_string::br2nl('Your buffer goes here ...');
     * @param str $buff
     * @return str
     * @author Slavi Marinov | http://orbisius.com
     */
    public static function br2nl($buff = '') {
        $buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
        $buff = trim($buff);

        return $buff;
    }
}

filtering a list using LINQ

var filtered = projects;
foreach (var tag in filteredTags) {
  filtered = filtered.Where(p => p.Tags.Contains(tag))
}

The nice thing with this approach is that you can refine search results incrementally.

How to turn NaN from parseInt into 0 for an empty string?

You can also use the isNaN() function:

var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)

Using wget to recursively fetch a directory with arbitrary files in it

You should be able to do it simply by adding a -r

wget -r http://stackoverflow.com/

Cannot set content-type to 'application/json' in jQuery.ajax

I had the same issue. I'm running a java rest app on a jboss server. But I think the solution is similar on an ASP .NET webapp.

Firefox makes a pre call to your server / rest url to check which options are allowed. That is the "OPTIONS" request which your server doesn't reply to accordingly. If this OPTIONS call is replied correct a second call is performed which is the actual "POST" request with json content.

This only happens when performing a cross-domain call. In your case calling 'http://localhost:16329/Hello' instead of calling a url path under the same domain '/Hello'

If you intend to make a cross domain call you have to enhance your rest service class with an annotated method the supports a "OPTIONS" http request. This is the according java implementation:

@Path("/rest")
public class RestfulService {

    @POST
    @Path("/Hello")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public string HelloWorld(string name)
    {
        return "hello, " + name;
    }

//THIS NEEDS TO BE ADDED ADDITIONALLY IF MAKING CROSS-DOMAIN CALLS

    @OPTIONS
    @Path("/Hello")
    @Produces(MediaType.TEXT_PLAIN+ ";charset=utf-8")
    public Response checkOptions(){
        return Response.status(200)
        .header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Headers", "Content-Type")
        .header("Access-Control-Allow-Methods", "POST, OPTIONS") //CAN BE ENHANCED WITH OTHER HTTP CALL METHODS 
        .build();
    }
}

So I guess in .NET you have to add an additional method annotated with

[WebInvoke(
        Method = "OPTIONS",
        UriTemplate = "Hello",
        ResponseFormat = WebMessageFormat.)]

where the following headers are set

.header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Headers", "Content-Type")
        .header("Access-Control-Allow-Methods", "POST, OPTIONS")

Get domain name

 protected void Page_Init(object sender, EventArgs e)
 {
   String hostdet = Request.ServerVariables["HTTP_HOST"].ToString();
 }

How to hide Bootstrap previous modal when you opening new one?

The best that I've been able to do is

$(this).closest('.modal').modal('toggle');

This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

You can however do this:

$(".modal:visible").modal('toggle');

This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

TabLayout tab selection

Kotlin fix

viewPager.currentItem = 0

tabs.setupWithViewPager(viewPager)

How to get directory size in PHP

Regarding Johnathan Sampson's Linux example, watch out when you are doing an intval on the outcome of the "du" function, if the size is >2GB, it will keep showing 2GB.

Replace:

$totalSize = intval(fgets($io, 80));

by:

strtok(fgets($io, 80), " ");

supposed your "du" function returns the size separated with space followed by the directory/file name.

JavaScript adding decimal numbers issue

Testing this Javascript:

var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];

var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
    sum += arr[i];
}

alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );

Conclusion

Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12

Instead, use ( ## + ## + ... + ##).toFixed(5) )

In IE 9, toFixed works very well.

Why does git revert complain about a missing -m option?

I had this problem, the solution was to look at the commit graph (using gitk) and see that I had the following:

*   commit I want to cherry-pick (x)
|\  
| * branch I want to cherry-pick to (y)
* | 
|/  
* common parent (x)

I understand now that I want to do

git cherry-pick -m 2 mycommitsha

This is because -m 1 would merge based on the common parent where as -m 2 merges based on branch y, that is the one I want to cherry-pick to.

How to activate the Bootstrap modal-backdrop?

Just append a div with that class to body, then remove it when you're done:

// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);

// Remove it (later)
$(".modal-backdrop").remove();

Live Example:

_x000D_
_x000D_
$("input").click(function() {_x000D_
  var bd = $('<div class="modal-backdrop"></div>');_x000D_
  bd.appendTo(document.body);_x000D_
  setTimeout(function() {_x000D_
    bd.remove();_x000D_
  }, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
_x000D_
_x000D_

How to adjust gutter in Bootstrap 3 grid system?

To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.

To learn more about the grid and the columns / gutter widths, please also read:

In you case with a container of 960px consider the medium grid (see also: http://getbootstrap.com/css/#grid). This grid will have a max container width of 970px. When setting @grid-columns:3; and setting @grid-gutter-width:15px; in variables.less you will get:

15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

I tried to add ASP.net v4.0 with all permission, add NETWORK SERVICE user but nothing help. At last, added the MODIFY right of DefaultAppPool user in App_Data folder, problem solved.

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

i am using like this.. its easy to understand first argument is mapStateToProps and second argument is mapDispatchToProps in the end connect with function/class.

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(TodoList);

How to calculate the CPU usage of a process by PID in Linux from C?

Take a look at the "pidstat" command, sounds like exactly what you require.

is there a post render callback for Angular JS directive?

Here is a directive to have actions programmed after a shallow render. By shallow I mean it will evaluate after that very element rendered and that will be unrelated to when its contents get rendered. So if you need some sub element doing a post render action, you should consider using it there:

define(['angular'], function (angular) {
  'use strict';
  return angular.module('app.common.after-render', [])
    .directive('afterRender', [ '$timeout', function($timeout) {
    var def = {
        restrict : 'A', 
        terminal : true,
        transclude : false,
        link : function(scope, element, attrs) {
            if (attrs) { scope.$eval(attrs.afterRender) }
            scope.$emit('onAfterRender')
        }
    };
    return def;
    }]);
});

then you can do:

<div after-render></div>

or with any useful expression like:

<div after-render="$emit='onAfterThisConcreteThingRendered'"></div>

How to add files/folders to .gitignore in IntelliJ IDEA?

Here is the screen print showing the options to ignore the file or folder after the installation of the .ignore plugin. The generated file name would be .gitignore enter image description here

what does "dead beef" mean?

It is also used for debugging purposes.

Here is a handy list of some of these values:

http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_debug_values

Telnet is not recognized as internal or external command

You can also try dism /online /Enable-Feature /FeatureName:TelnetClient

Run this command with "Run as an administrator"

Reference

LINQ Join with Multiple Conditions in On Clause

You just need to name the anonymous property the same on both sides

on new { t1.ProjectID, SecondProperty = true } equals 
   new { t2.ProjectID, SecondProperty = t2.Completed } into j1

Based on the comments of @svick, here is another implementation that might make more sense:

from t1 in Projects
from t2 in Tasks.Where(x => t1.ProjectID == x.ProjectID && x.Completed == true)
                .DefaultIfEmpty()
select new { t1.ProjectName, t2.TaskName }

Do I use <img>, <object>, or <embed> for SVG files?

This jQuery function captures all errors in svg images and replaces the file extension with an alternate extension

Please open the console to see the error loading image svg

_x000D_
_x000D_
(function($){_x000D_
  $('img').on('error', function(){_x000D_
    var image = $(this).attr('src');_x000D_
    if ( /(\.svg)$/i.test( image )) {_x000D_
      $(this).attr('src', image.replace('.svg', '.png'));_x000D_
    }_x000D_
  })  _x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<img src="https://jsfiddle.net/img/logo.svg">
_x000D_
_x000D_
_x000D_

Stored Procedure error ORA-06550

Could you try this one:

create or replace 
procedure point_triangle
IS
BEGIN
  FOR thisteam in (select P.FIRSTNAME,P.LASTNAME, SUM(P.PTS) S from PLAYERREGULARSEASON P  where P.TEAM = 'IND'  group by P.FIRSTNAME, P.LASTNAME order by SUM(P.PTS) DESC)
  LOOP
    dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME  || ':' || thisteam.S);
  END LOOP;

END;

CSS background-image - What is the correct usage?

1) putting quotes is a good habit

2) it can be relative path for example:

background-image: url('images/slides/background.jpg');

will look for images folder in the folder from which css is loaded. So if images are in another folder or out of the CSS folder tree you should use absolute path or relative to the root path (starting with /)

3) you should use complete declaration for background-image to make it behave consistently across standards compliant browsers like:

background:blue url('/images/clouds.jpg') no-repeat scroll left center;

Delete files older than 15 days using PowerShell

If you are having problems with the above examples on a Windows 10 box, try replacing .CreationTime with .LastwriteTime. This worked for me.

dir C:\locationOfFiles -ErrorAction SilentlyContinue | Where { ((Get-Date)-$_.LastWriteTime).days -gt 15 } | Remove-Item -Force

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

How to recursively find the latest modified file in a directory?

I prefer this one, it is shorter:

find . -type f -print0|xargs -0 ls -drt|tail -n 1

How does Python return multiple values from a function?

Here It is actually returning tuple.

If you execute this code in Python 3:

def get():
    a = 3
    b = 5
    return a,b
number = get()
print(type(number))
print(number)

Output :

<class 'tuple'>
(3, 5)

But if you change the code line return [a,b] instead of return a,b and execute :

def get():
    a = 3
    b = 5
    return [a,b]
number = get()
print(type(number))
print(number)

Output :

<class 'list'>
[3, 5]

It is only returning single object which contains multiple values.

There is another alternative to return statement for returning multiple values, use yield( to check in details see this What does the "yield" keyword do in Python?)

Sample Example :

def get():
    for i in range(5):
        yield i
number = get()
print(type(number))
print(number)
for i in number:
    print(i)

Output :

<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4

List the queries running on SQL Server

SELECT 
    p.spid, p.status, p.hostname, p.loginame, p.cpu, r.start_time, t.text
FROM
    sys.dm_exec_requests as r,
    master.dbo.sysprocesses as p
    CROSS APPLY sys.dm_exec_sql_text(p.sql_handle) t
WHERE
    p.status NOT IN ('sleeping', 'background')
AND r.session_id = p.spid

And

KILL @spid

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

Giving such permission can be dangerous, especially if your web application uses that same username.

Now the web user (and the whole world wide web) also has the permission to create and drop objects within your database. Think SQL Injection!

I recommend granting Execute privileges only to the specific user on the given object as follows:

grant execute on storedProcedureNameNoquotes to myusernameNoquotes

Now the user myusernameNoquotes can execute procedure storedProcedureNameNoquotes without other unnecessary permissions to your valuable data.

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

in case of a similar issue when I'm creating dockerfile I faced the same scenario:- I used below changed in mysql_connect function as:-

if($CONN = @mysqli_connect($DBHOST, $DBUSER, $DBPASS)){ //mysql_query("SET CHARACTER SET 'gbk'", $CONN);

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

HTML Input="file" Accept Attribute File Type (CSV)

Now you can use new html5 input validation attribute pattern=".+\.(xlsx|xls|csv)".

IN vs OR in the SQL WHERE Clause

The OR operator needs a much more complex evaluation process than the IN construct because it allows many conditions, not only equals like IN.

Here is a like of what you can use with OR but that are not compatible with IN: greater. greater or equal, less, less or equal, LIKE and some more like the oracle REGEXP_LIKE. In addition consider that the conditions may not always compare the same value.

For the query optimizer it's easier to to manage the IN operator because is only a construct that defines the OR operator on multiple conditions with = operator on the same value. If you use the OR operator the optimizer may not consider that you're always using the = operator on the same value and, if it doesn't perform a deeper and very much more complex elaboration, it could probably exclude that there may be only = operators for the same values on all the involved conditions, with a consequent preclusion of optimized search methods like the already mentioned binary search.

[EDIT] Probably an optimizer may not implement optimized IN evaluation process, but this doesn't exclude that one time it could happen(with a database version upgrade). So if you use the OR operator that optimized elaboration will not be used in your case.

PHP string concatenation

Just use . for concatenating. And you missed out the $personCount increment!

while ($personCount < 10) {
    $result .= $personCount . ' people';
    $personCount++;
}

echo $result;

Difference between wait and sleep

  1. wait() is a method of Object class.
    sleep() is a method of Thread class.

  2. sleep() allows the thread to go to sleep state for x milliseconds.
    When a thread goes into sleep state it doesn’t release the lock.

  3. wait() allows thread to release the lock and goes to suspended state.
    This thread will be active when a notify() or notifAll() method is called for the same object.

How can I read comma separated values from a text file in Java?

You can also use the java.util.Scanner class.

private static void readFileWithScanner() {
    File file = new File("path/to/your/file/file.txt");

    Scanner scan = null;

    try {
        scan = new Scanner(file);

        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            String[] lineArray = line.split(",");
            // do something with lineArray, such as instantiate an object
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        scan.close();
    }
}

Error using eclipse for Android - No resource found that matches the given name

If you are an iPhone Developer don't just add your picture (by right clicking then add file...like we do in iPhone). You have to copy and paste the picture in your drawable folder.

Delete all Duplicate Rows except for One in MySQL?

If you want to keep the row with the lowest id value:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MIN(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

If you want the id value that is the highest:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MAX(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.

How to turn off word wrapping in HTML?

You need to use the CSS white-space attribute.

In particular, white-space: nowrap and white-space: pre are the most commonly used values. The first one seems to be what you 're after.

How do I get SUM function in MySQL to return '0' if no values are found?

if sum of column is 0 then display empty

select if(sum(column)>0,sum(column),'')
from table 

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The issue is with this line

 xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text

You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.

Hence replace this with

 xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text 

Null & empty string comparison in Bash

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';
fi

Or to verify that a variable is empty

#!/bin/bash      
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi

tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

Get Selected value of a Combobox

Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)

sub myhandler(eventsource)
  process(eventsource.value)
end sub

for each cell
  cell.setEventHandler(myHandler)

But i dont know the syntax for achieving this in VB/VBA, or if is even possible.

How to tell if string starts with a number with Python?

Surprising that after such a long time there is still the best answer missing.

The downside of the other answers is using [0] to select the first character, but as noted, this breaks on the empty string.

Using the following circumvents this problem, and, in my opinion, gives the prettiest and most readable syntax of the options we have. It also does not import/bother with regex either):

>>> string = '1abc'
>>> string[:1].isdigit()
True

>>> string = ''
>>> string[:1].isdigit()
False

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

Sending email from Command-line via outlook without having to click send

Send SMS/Text Messages from Command Line with VBScript!

If VBA meets the rules for VB Script then it can be called from command line by simply placing it into a text file - in this case there's no need to specifically open Outlook.

I had a need to send automated text messages to myself from the command line, so I used the code below, which is just a compressed version of @Geoff's answer above.

Most mobile phone carriers worldwide provide an email address "version" of your mobile phone number. For example in Canada with Rogers or Chatr Wireless, an email sent to <YourPhoneNumber> @pcs.rogers.com will be immediately delivered to your Rogers/Chatr phone as a text message.

* You may need to "authorize" the first message on your phone, and some carriers may charge an additional fee for theses message although as far as I know, all Canadian carriers provide this little-known service for free. Check your carrier's website for details.

There are further instructions and various compiled lists of worldwide carrier's Email-to-Text addresses available online such as this and this and this.


Code & Instructions

  1. Copy the code below and paste into a new file in your favorite text editor.
  2. Save the file with any name with a .VBS extension, such as TextMyself.vbs.

That's all!
Just double-click the file to send a test message, or else run it from a batch file using START.

Sub SendMessage()
    Const EmailToSMSAddy = "[email protected]"
    Dim objOutlookRecip
    With CreateObject("Outlook.Application").CreateItem(0)
        Set objOutlookRecip = .Recipients.Add(EmailToSMSAddy)
        objOutlookRecip.Type = 1
        .Subject = "The computer needs your attention!"
        .Body = "Go see why Windows Command Line is texting you!"
        .Save
        .Send
    End With
End Sub

Example Batch File Usage:

START x:\mypath\TextMyself.vbs

Of course there are endless possible ways this could be adapted and customized to suit various practical or creative needs.

time.sleep -- sleeps thread or process?

Process is not runnable by itself. In regard to execution, process is just a container for threads. Meaning you can't pause the process at all. It is simply not applicable to process.

Convert hex to binary

Replace each hex digit with the corresponding 4 binary digits:

1 - 0001
2 - 0010
...
a - 1010
b - 1011
...
f - 1111

How to indent HTML tags in Notepad++

In Notepad++ v7.8.9 you can use the Tab key to increase the indention level, and use Shift + Tab to decrease the indentation level.

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

Sort a Map<Key, Value> by values

Sorting the keys requires the Comparator to look up each value for each comparison. A more scalable solution would use the entrySet directly, since then the value would be immediately available for each comparison (although I haven't backed this up by numbers).

Here's a generic version of such a thing:

public static <K, V extends Comparable<? super V>> List<K> getKeysSortedByValue(Map<K, V> map) {
    final int size = map.size();
    final List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(size);
    list.addAll(map.entrySet());
    final ValueComparator<V> cmp = new ValueComparator<V>();
    Collections.sort(list, cmp);
    final List<K> keys = new ArrayList<K>(size);
    for (int i = 0; i < size; i++) {
        keys.set(i, list.get(i).getKey());
    }
    return keys;
}

private static final class ValueComparator<V extends Comparable<? super V>>
                                     implements Comparator<Map.Entry<?, V>> {
    public int compare(Map.Entry<?, V> o1, Map.Entry<?, V> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
}

There are ways to lessen memory rotation for the above solution. The first ArrayList created could for instance be re-used as a return value; this would require suppression of some generics warnings, but it might be worth it for re-usable library code. Also, the Comparator does not have to be re-allocated at every invocation.

Here's a more efficient albeit less appealing version:

public static <K, V extends Comparable<? super V>> List<K> getKeysSortedByValue2(Map<K, V> map) {
    final int size = map.size();
    final List reusedList = new ArrayList(size);
    final List<Map.Entry<K, V>> meView = reusedList;
    meView.addAll(map.entrySet());
    Collections.sort(meView, SINGLE);
    final List<K> keyView = reusedList;
    for (int i = 0; i < size; i++) {
        keyView.set(i, meView.get(i).getKey());
    }
    return keyView;
}

private static final Comparator SINGLE = new ValueComparator();

Finally, if you need to continously access the sorted information (rather than just sorting it once in a while), you can use an additional multi map. Let me know if you need more details...

Can I bind an array to an IN() condition?

If the column can only contain integers, you could probably do this without placeholders and just put the ids in the query directly. You just have to cast all the values of the array to integers. Like this:

$listOfIds = implode(',',array_map('intval', $ids));
$stmt = $db->prepare(
    "SELECT *
     FROM table
     WHERE id IN($listOfIds)"
);
$stmt->execute();

This shouldn't be vulnerable to any SQL injection.

Mysql: Select all data between two dates

its very easy to handle this situation

You can use BETWEEN CLAUSE in combination with date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )

SELECT
    sc_cust_design.design_id as id,
    sc_cust_design.main_image,
    FROM
    sc_cust_design
WHERE
    sc_cust_design.publish = 1 
    AND **`datein`BETWEEN date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )**

Happy Coding :)

How can I enter latitude and longitude in Google Maps?

for higher precision. this format:

45 11.735N,004 34.281E

and this

45 23.623, 5 38.77

Getting IPV4 address from a sockaddr structure

Just cast the entire sockaddr structure to a sockaddr_in. Then you can use:

char *ip = inet_ntoa(their_addr.sin_addr)

To retrieve the standard ip representation.

ValueError: unconverted data remains: 02:05

Best answer is to use the from dateutil import parser.

usage:

from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())

How do I draw a shadow under a UIView?

self.layer.masksToBounds = NO;
self.layer.cornerRadius = 8; // if you like rounded corners
self.layer.shadowOffset = CGSizeMake(-15, 20);
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;

This will slow down the application. Adding the following line can improve performance as long as your view is visibly rectangular:

self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;

JS. How to replace html element with another element/text, represented in string?

idTABLE.parentElement.innerHTML =  '<span>123 element</span> 456';

while this works, it's still recommended to use getElementById: Do DOM tree elements with ids become global variables?

replaceChild would work fine if you want to go to the trouble of building up your replacement, element by element, using document.createElement and appendChild, but I don't see the point.

Resize background image in div using css

Answer

You have multiple options:

  1. background-size: 100% 100%; - image gets stretched (aspect ratio may be preserved, depending on browser)
  2. background-size: contain; - image is stretched without cutting it while preserving aspect ratio
  3. background-size: cover; - image is completely covering the element while preserving aspect ratio (image can be cut off)

/edit: And now, there is even more: https://alligator.io/css/cropping-images-object-fit

Demo on Codepen

Update 2017: Preview

Here are screenshots for some browsers to show their differences.

Chrome

preview background types chrome


Firefox

preview background types firefox


Edge

preview background types edge


IE11

preview background types ie11

Takeaway Message

background-size: 100% 100%; produces the least predictable result.

Resources

Safe Area of Xcode 9

I want to mention something that caught me first when I was trying to adapt a SpriteKit-based app to avoid the round edges and "notch" of the new iPhone X, as suggested by the latest Human Interface Guidelines: The new property safeAreaLayoutGuide of UIView needs to be queried after the view has been added to the hierarchy (for example, on -viewDidAppear:) in order to report a meaningful layout frame (otherwise, it just returns the full screen size).

From the property's documentation:

The layout guide representing the portion of your view that is unobscured by bars and other content. When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. (In tvOS, the safe area reflects the area not covered the screen's bezel.) If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide edges are equal to the edges of the view.

(emphasis mine)

If you read it as early as -viewDidLoad:, the layoutFrame of the guide will be {{0, 0}, {375, 812}} instead of the expected {{0, 44}, {375, 734}}

Full screen background image in an activity

Working. you should tryout this:

android:src="@drawable/img"

How to reset sequence in postgres and fill id column with new data?

Just resetting the sequence and updating all rows may cause duplicate id errors. In many cases you have to update all rows twice. First with higher ids to avoid the duplicates, then with the ids you actually want.

Please avoid to add a fixed amount to all ids (as recommended in other comments). What happens if you have more rows than this fixed amount? Assuming the next value of the sequence is higher than all the ids of the existing rows (you just want to fill the gaps), i would do it like:

UPDATE table SET id = DEFAULT;
ALTER SEQUENCE seq RESTART;
UPDATE table SET id = DEFAULT;

How can I switch to another branch in git?

[git checkout "branch_name"]

is another way to say:

[git checkout -b branch_name origin/branch_name]

in case "branch_name" exists only remotely.

[git checkout -b branch_name origin/branch_name] is useful in case you have multiple remotes.

Regarding [git checkout origin 'another_branch'] I'm not sure this is possible, AFAK you can do this using "fetch" command -- [git fetch origin 'another_branch']

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

This answer might help someone...

All these answers didnt help, then I realised I forgot to check one crucial thing.. The port :)

I have mysql running in a docker container running on a different port. I was pointing to my host machine on port 3306, which I have a mysql server running on. My container exposes the server on port 33060. So all this time, i was looking at the wrong server! doh!

How to install plugins to Sublime Text 2 editor?

According to John Day's answer

You should have a Data/Packages folder in your Sublime Text 2 install directory. All you need to do is download the plugin and put the plugin folder in the Packages folder.

In case if you are searching for Data/Packages folder you can find it here

Windows: %APPDATA%\Sublime Text 2

OS X: ~/Library/Application Support/Sublime Text 2

Linux: ~/.Sublime Text 2

Portable Installation: Sublime Text 2/Data

Converting file size in bytes to human-readable string

Based on cocco's answer but slightly desugerified (honestly, ones I was comfortable with are remained/added) and doesn't show trailing zeros but still supports 0, hope to be useful for others:

_x000D_
_x000D_
function fileSizeSI(size) {_x000D_
    var e = (Math.log(size) / Math.log(1e3)) | 0;_x000D_
    return +(size / Math.pow(1e3, e)).toFixed(2) + ' ' + ('kMGTPEZY'[e - 1] || '') + 'B';_x000D_
}_x000D_
_x000D_
_x000D_
// test:_x000D_
document.write([0, 23, 4322, 324232132, 22e9, 64.22e12, 76.22e15, 64.66e18, 77.11e21, 22e24].map(fileSizeSI).join('<br>'));
_x000D_
_x000D_
_x000D_

Hide HTML element by id

@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS

<style type="text/css">
    #nav-ask{ display:none; }
</style>

or if you already have a "hideMe" CSS Class:

<script type="text/javascript">

    if(document.getElementById && document.createTextNode)
    {
        if(document.getElementById('nav-ask'))
        {
            document.getElementById('nav-ask').className='hideMe';
        }
    }

</script>

Generate random string/characters in JavaScript

If you want just A-Z:

randomAZ(n: number): string {
      return Array(n)
        .fill(null)
        .map(() => Math.random()*100%25 + 'A'.charCodeAt(0))
        .map(a => String.fromCharCode(a))
        .join('')
 }

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

Split array into chunks

Here's a solution using ImmutableJS, where items is an Immutable List and size is the required grouping size.

const partition = ((items, size) => {
  return items.groupBy((items, i) => Math.floor(i/size))
})

OnclientClick and OnClick is not working at the same time?

Vinay (above) gave an effective work-around. What's actually causing the button's OnClick event to not work following the OnClientClick event function is that MS has defined it where, once the button is disabled (in the function called by the OnClientClick event), the button "honors" this by not trying to complete the button's activity by calling the OnClick event's defined method.

I struggled several hours trying to figure this out. Once I removed the statement to disable the submit button (that was inside the OnClientClick function), the OnClick method was called with no further problem.

Microsoft, if you're listening, once the button is clicked it should complete it's assigned activity even if it is disabled part of the way through this activity. As long as it is not disabled when it is clicked, it should complete all assigned methods.

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

Accessing SQL Database in Excel-VBA

Is that a proper connection string?
Where is the SQL Server instance located?

You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.

EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.

What is String pool in Java?

Let's start with a quote from the virtual machine spec:

Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.

This may not occur - This is a hint, that there's something special about String objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:

1: a := "one" 
   --> if(pool[hash("one")] == null)  // true
           pool[hash("one") --> "one"]
       return pool[hash("one")]

2: b := "one" 
  --> if(pool[hash("one")] == null)   // false, "one" already in pool
        pool[hash("one") --> "one"]
      return pool[hash("one")] 

So in this case, variables a and b hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true.

This is not the case if we use the constructor:

1: a := "one"
2: b := new String("one")

Again, "one" is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false

So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).

As programmers we don't have to care much about the String pool, as long as we keep in mind:

  • (a == b) && (a.equals(b)) may be true or false (always use equals to compare Strings)
  • Don't use reflection to change the backing char[] of a String (as you don't know who is actualling using that String)

Finding the last index of an array

say your array is called arr

do

arr[arr.Length - 1]

insert datetime value in sql database with c#

using (SqlConnection conn = new SqlConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = "INSERT INTO <table> (<date_column>) VALUES ('2010-01-01 12:00')";
    cmd.ExecuteNonQuery();
}

It's been awhile since I wrote this stuff, so this may not be perfect. but the general idea is there.

WARNING: this is unsanitized. You should use parameters to avoid injection attacks.

EDIT: Since Jon insists.

AngularJS ui-router login authentication

The solutions posted so far are needlessly complicated, in my opinion. There's a simpler way. The documentation of ui-router says listen to $locationChangeSuccess and use $urlRouter.sync() to check a state transition, halt it, or resume it. But even that actually doesn't work.

However, here are two simple alternatives. Pick one:

Solution 1: listening on $locationChangeSuccess

You can listen to $locationChangeSuccess and you can perform some logic, even asynchronous logic there. Based on that logic, you can let the function return undefined, which will cause the state transition to continue as normal, or you can do $state.go('logInPage'), if the user needs to be authenticated. Here's an example:

angular.module('App', ['ui.router'])

// In the run phase of your Angular application  
.run(function($rootScope, user, $state) {

  // Listen to '$locationChangeSuccess', not '$stateChangeStart'
  $rootScope.$on('$locationChangeSuccess', function() {
    user
      .logIn()
      .catch(function() {
        // log-in promise failed. Redirect to log-in page.
        $state.go('logInPage')
      })
  })
})

Keep in mind that this doesn't actually prevent the target state from loading, but it does redirect to the log-in page if the user is unauthorized. That's okay since real protection is on the server, anyway.

Solution 2: using state resolve

In this solution, you use ui-router resolve feature.

You basically reject the promise in resolve if the user is not authenticated and then redirect them to the log-in page.

Here's how it goes:

angular.module('App', ['ui.router'])

.config(
  function($stateProvider) {
    $stateProvider
      .state('logInPage', {
        url: '/logInPage',
        templateUrl: 'sections/logInPage.html',
        controller: 'logInPageCtrl',
      })
      .state('myProtectedContent', {
        url: '/myProtectedContent',
        templateUrl: 'sections/myProtectedContent.html',
        controller: 'myProtectedContentCtrl',
        resolve: { authenticate: authenticate }
      })
      .state('alsoProtectedContent', {
        url: '/alsoProtectedContent',
        templateUrl: 'sections/alsoProtectedContent.html',
        controller: 'alsoProtectedContentCtrl',
        resolve: { authenticate: authenticate }
      })

    function authenticate($q, user, $state, $timeout) {
      if (user.isAuthenticated()) {
        // Resolve the promise successfully
        return $q.when()
      } else {
        // The next bit of code is asynchronously tricky.

        $timeout(function() {
          // This code runs after the authentication promise has been rejected.
          // Go to the log-in page
          $state.go('logInPage')
        })

        // Reject the authentication promise to prevent the state from loading
        return $q.reject()
      }
    }
  }
)

Unlike the first solution, this solution actually prevents the target state from loading.

Is there a sleep function in JavaScript?

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.

How to force ViewPager to re-instantiate its items

public class DayFlipper extends ViewPager {

private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return DayFlipper.DAY_HISTORY;
    }

    @Override
    public void startUpdate(View container) {
    }

    @Override
    public Object instantiateItem(View container, int position) {
        Log.d(TAG, "instantiateItem(): " + position);

        Date d = DateHelper.getBot();
        for (int i = 0; i < position; i++) {
            d = DateHelper.getTomorrow(d);
        }

        d = DateHelper.normalize(d);

        CubbiesView cv = new CubbiesView(mContext);
        cv.setLifeDate(d);
        ((ViewPager) container).addView(cv, 0);
        // add map
        cv.setCubbieMap(mMap);
        cv.initEntries(d);
adpter = FlipperAdapter.this;
        return cv;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((CubbiesView) object);
    }

    @Override
    public void finishUpdate(View container) {

    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((CubbiesView) object);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {

    }

}

    ...

    public void refresh() {
    adapter().notifyDataSetChanged();
}
}

try this.

Skip certain tables with mysqldump

for multiple databases:

mysqldump -u user -p --ignore-table=db1.tbl1 --ignore-table=db2.tbl1 --databases db1 db2 ..

PowerShell to remove text from a string

This should do what you want:

C:\PS> if ('=keep this,' -match '=([^,]*)') { $matches[1] }
keep this

CSS - Expand float child DIV height to parent's height

<div class="parent" style="height:500px;">
<div class="child-left floatLeft" style="height:100%">
</div>

<div class="child-right floatLeft" style="height:100%">
</div>
</div>

I used inline style just to give idea.

Convert True/False value read from file to boolean

If you want to be case-insensitive, you can just do:

b = True if bool_str.lower() == 'true' else False

Example usage:

>>> bool_str = 'False'
>>> b = True if bool_str.lower() == 'true' else False
>>> b
False
>>> bool_str = 'true'
>>> b = True if bool_str.lower() == 'true' else False
>>> b
True

How to increase Bootstrap Modal Width?

I know this is old, but to anyone looking, you now need to set the max-width property.

.modal-1000 {
    max-width: 1000px;
    margin: 30px auto;
}

How to split a string in Ruby and get all items except the first one?

You probably mistyped a few things. From what I gather, you start with a string such as:

string = "test1, test2, test3, test4, test5"

Then you want to split it to keep only the significant substrings:

array = string.split(/, /)

And in the end you only need all the elements excluding the first one:

# We extract and remove the first element from array
first_element = array.shift

# Now array contains the expected result, you can check it with
puts array.inspect

Did that answer your question ?

Rails - How to use a Helper Inside a Controller

Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.

Option 1: Probably the simplest way is to include your helper module in your controller:

class MyController < ApplicationController
  include MyHelper

  def xxxx
    @comments = []
    Comment.find_each do |comment|
      @comments << {:id => comment.id, :html => html_format(comment.content)}
    end
  end
end

Option 2: Or you can declare the helper method as a class function, and use it like so:

MyHelper.html_format(comment.content)

If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:

module MyHelper
  def self.html_format(str)
    process(str)
  end

  def html_format(str)
    MyHelper.html_format(str)
  end
end

Hope this helps!

Making the iPhone vibrate

In iOS 10, and on newer iPhones, you can also use haptic API. This haptic feedback is softer than the AudioToolbox API.

For your GAME OVER scenario, a heavy UI impact feedback should be suitable.

UIImpactFeedbackGenerator(style: .heavy).impactOccurred()

You could use the other haptic feedback styles.

What does "if (rs.next())" mean?

As to the concrete problem with that SQLException, you need to replace

ResultSet rs = stmt.executeQuery(sql);

by

ResultSet rs = stmt.executeQuery();

because you're using the PreparedStatement subclass instead of Statement. When using PreparedStatement, you've already passed in the SQL string to Connection#prepareStatement(). You just have to set the parameters on it and then call executeQuery() method directly without re-passing the SQL string.

See also:


As to the concrete question about rs.next(), it shifts the cursor to the next row of the result set from the database and returns true if there is any row, otherwise false. In combination with the if statement (instead of the while) this means that the programmer is expecting or interested in only one row, the first row.

See also:

How do I parallelize a simple Python loop?

very simple example of parallel processing is

from multiprocessing import Process

output1 = list()
output2 = list()
output3 = list()

def yourfunction():
    for j in range(0, 10):
        # calc individual parameter value
        parameter = j * offset
        # call the calculation
        out1, out2, out3 = calc_stuff(parameter=parameter)

        # put results into correct output list
        output1.append(out1)
        output2.append(out2)
        output3.append(out3)

if __name__ == '__main__':
    p = Process(target=pa.yourfunction, args=('bob',))
    p.start()
    p.join()

how to use concatenate a fixed string and a variable in Python

Try:

msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]

The + operator is overridden in python to concatenate strings.

Remove Primary Key in MySQL

"if you restore the primary key, you sure may revert it back to AUTO_INCREMENT"

There should be no question of whether or not it is desirable to "restore the PK property" and "restore the autoincrement property" of the ID column.

Given that it WAS an autoincrement in the prior definition of the table, it is quite likely that there exists some program that inserts into this table without providing an ID value (because the ID column is autoincrement anyway).

Any such program's operation will break by not restoring the autoincrement property.

How to sort a HashMap in Java

Do you have to use a HashMap? If you only need the Map Interface use a TreeMap


If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your HashMap:

Map<String, Person> people = new HashMap<>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);

people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);

// not yet sorted
List<Person> peopleByAge = new ArrayList<>(people.values());

Collections.sort(peopleByAge, Comparator.comparing(Person::getAge));

for (Person p : peopleByAge) {
    System.out.println(p.getName() + "\t" + p.getAge());
}

If you want to access this sorted list often, then you could insert your elements into a HashMap<TreeSet<Person>>, though the semantics of sets and lists are a bit different.

Get next element in foreach loop

A foreach loop in php will iterate over a copy of the original array, making next() and prev() functions useless. If you have an associative array and need to fetch the next item, you could iterate over the array keys instead:

foreach (array_keys($items) as $index => $key) {
    // first, get current item
    $item = $items[$key];
    // now get next item in array
    $next = $items[array_keys($items)[$index + 1]];
}

Since the resulting array of keys has a continuous index itself, you can use that instead to access the original array.

Be aware that $next will be null for the last iteration, since there is no next item after the last. Accessing non existent array keys will throw a php notice. To avoid that, either:

  1. Check for the last iteration before assigning values to $next
  2. Check if the key with index + 1 exists with array_key_exists()

Using method 2 the complete foreach could look like this:

foreach (array_keys($items) as $index => $key) {
    // first, get current item
    $item = $items[$key];
    // now get next item in array
    $next = null;
    if (array_key_exists($index + 1, array_keys($items))) {
        $next = $items[array_keys($items)[$index + 1]];
    }
}

How can I reset or revert a file to a specific revision?

git checkout -- foo

That will reset foo to HEAD. You can also:

git checkout HEAD^ foo

for one revision back, etc.

What is Express.js?

ExpressJS is bare-bones web application framework on top of NodeJS.

It can be used to build WebApps, RESTFUL APIs etc quickly.

Supports multiple template engines like Jade, EJS.

ExpressJS keeps only a minimalist functionality as core features and as such there are no ORMs or DBs supported as default. But with a little effort expressjs apps can be integrated with different databases.

For a getting started guide on creating ExpressJS apps, look into the following link:

ExpressJS Introductory Tutorial

Website screenshots

This ought to be good for you:

https://wkhtmltopdf.org/

Make sure you download the wkhtmltoimage distribution!

How do I center list items inside a UL element?

In Bootstrap (4) use display: inline-flex, like so:

li {
    display: inline-flex;
    /* ... */
}

Auto refresh page every 30 seconds

Use setInterval instead of setTimeout. Though in this case either will be fine but setTimeout inherently triggers only once setInterval continues indefinitely.

<script language="javascript">
setInterval(function(){
   window.location.reload(1);
}, 30000);
</script>

How can I pass request headers with jQuery's getJSON() method?

I think you could set the headers and still use getJSON() like this:

$.ajaxSetup({
  headers : {
    'Authorization' : 'Basic faskd52352rwfsdfs',
    'X-PartnerKey' : '3252352-sdgds-sdgd-dsgs-sgs332fs3f'
  }
});
$.getJSON('http://localhost:437/service.svc/logins/jeffrey/house/fas6347/devices?format=json', function(json) { alert("Success"); }); 

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

Reason is as @MilicaMedic says. Alternative solution is disable all constraints, do the update and then enable the constraints again like this. Very useful when updating test data in test environments.

exec sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

update patient set id_no='7008255601088' where id_no='8008255601088'
update patient_address set id_no='7008255601088' where id_no='8008255601088'

exec sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

Source:

https://stackoverflow.com/a/161410/3850405

How to drop a database with Mongoose?

An updated answer, for 4.6.0+, if you have a preference for promises (see docs):

mongoose.connect('mongodb://localhost/mydb', { useMongoClient: true })
.then((connection) => {
   connection.db.dropDatabase();
   // alternatively:
   // mongoose.connection.db.dropDatabase();
});

I tested this code in my own code, using mongoose 4.13.6. Also, note the use of the useMongoClient option (see docs). Docs indicate:

Mongoose's default connection logic is deprecated as of 4.11.0. Please opt in to the new connection logic using the useMongoClient option, but make sure you test your connections first if you're upgrading an existing codebase!

Create new user in MySQL and give it full access to one database

The below command will work if you want create a new user give him all the access to a specific database(not all databases in your Mysql) on your localhost.

GRANT ALL PRIVILEGES ON test_database.* TO 'user'@'localhost' IDENTIFIED BY 'password';

This will grant all privileges to one database test_database (in your case dbTest) to that user on localhost.

Check what permissions that above command issued to that user by running the below command.

SHOW GRANTS FOR 'user'@'localhost'

Just in case, if you want to limit the user access to only one single table

GRANT ALL ON mydb.table_name TO 'someuser'@'host';

Text on image mouseover?

This is using the :hover pseudoelement in CSS3.

HTML:

<div id="wrapper">
    <img src="http://placehold.it/300x200" class="hover" />
    <p class="text">text</p>
</div>?

CSS:

#wrapper .text {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}

#wrapper:hover .text {
visibility:visible;
}

?Demo HERE.


This instead is a way of achieving the same result by using jquery:

HTML:

<div id="wrapper">
    <img src="http://placehold.it/300x200" class="hover" />
    <p class="text">text</p>
</div>?

CSS:

#wrapper p {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}

jquery code:

$('.hover').mouseover(function() {
  $('.text').css("visibility","visible");
});

$('.hover').mouseout(function() {
  $('.text').css("visibility","hidden");
});

You can put the jquery code where you want, in the body of the HTML page, then you need to include the jquery library in the head like this:

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>

You can see the demo HERE.

When you want to use it on your website, just change the <img src /> value and you can add multiple images and captions, just copy the format i used: insert image with class="hover" and p with class="text"

How to replace values at specific indexes of a python list?

Why not just:

map(s.__setitem__, a, m)

Comparing two dictionaries and checking how many (key, value) pairs are equal

I am using this solution that works perfectly for me in Python 3


import logging
log = logging.getLogger(__name__)

...

    def deep_compare(self,left, right, level=0):
        if type(left) != type(right):
            log.info("Exit 1 - Different types")
            return False

        elif type(left) is dict:
            # Dict comparison
            for key in left:
                if key not in right:
                    log.info("Exit 2 - missing {} in right".format(key))
                    return False
                else:
                    if not deep_compare(left[str(key)], right[str(key)], level +1 ):
                        log.info("Exit 3 - different children")
                        return False
            return True
        elif type(left) is list:
            # List comparison
            for key in left:
                if key not in right:
                    log.info("Exit 4 - missing {} in right".format(key))
                    return False
                else:
                    if not deep_compare(left[left.index(key)], right[right.index(key)], level +1 ):
                        log.info("Exit 5 - different children")
                        return False
            return True
        else:
            # Other comparison
            return left == right

        return False

It compares dict, list and any other types that implements the "==" operator by themselves. If you need to compare something else different, you need to add a new branch in the "if tree".

Hope that helps.

How to get on scroll events?

Listen to window:scroll event for window/document level scrolling and element's scroll event for element level scrolling.

window:scroll

@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {

}

or

<div (window:scroll)="onWindowScroll($event)">

scroll

@HostListener('scroll', ['$event'])
onElementScroll($event) {

}

or

<div (scroll)="onElementScroll($event)">

@HostListener('scroll', ['$event']) won't work if the host element itself is not scroll-able.

Examples

Extract Month and Year From Date in R

Here's another solution using a package solely dedicated to working with dates and times in R:

library(tidyverse)
library(lubridate)

(df <- tibble(ID = 1:3, Date = c("2004-02-06" , "2006-03-14", "2007-07-16")))
#> # A tibble: 3 x 2
#>      ID Date      
#>   <int> <chr>     
#> 1     1 2004-02-06
#> 2     2 2006-03-14
#> 3     3 2007-07-16

df %>%
  mutate(
    Date = ymd(Date),
    Month_Yr = format_ISO8601(Date, precision = "ym")
  )
#> # A tibble: 3 x 3
#>      ID Date       Month_Yr
#>   <int> <date>     <chr>   
#> 1     1 2004-02-06 2004-02 
#> 2     2 2006-03-14 2006-03 
#> 3     3 2007-07-16 2007-07

Created on 2020-09-01 by the reprex package (v0.3.0)

How can you get the build/version number of your Android application?

Use the BuildConfig class:

String versionName = BuildConfig.VERSION_NAME;
int versionCode = BuildConfig.VERSION_CODE;

File build.gradle (app)

defaultConfig {
    applicationId "com.myapp"
    minSdkVersion 19
    targetSdkVersion 27
    versionCode 17
    versionName "1.0"
}

XML parsing of a variable string in JavaScript

Update: For a more correct answer see Tim Down's answer.

Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like jQuery to handle the cross-browsers differences.

A really basic example is:

var xml = "<music><album>Beethoven</album></music>";

var result = $(xml).find("album").text();

Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.

Calculate distance between 2 GPS coordinates

I think a version of the algorithm in R is still missing:

gpsdistance<-function(lat1,lon1,lat2,lon2){

# internal function to change deg to rad

degreesToRadians<- function (degrees) {
return (degrees * pi / 180)
}

R<-6371e3  #radius of Earth in meters

phi1<-degreesToRadians(lat1) # latitude 1
phi2<-degreesToRadians(lat2) # latitude 2
lambda1<-degreesToRadians(lon1) # longitude 1
lambda2<-degreesToRadians(lon2) # longitude 2

delta_phi<-phi1-phi2 # latitude-distance
delta_lambda<-lambda1-lambda2 # longitude-distance

a<-sin(delta_phi/2)*sin(delta_phi/2)+
cos(phi1)*cos(phi2)*sin(delta_lambda/2)*
sin(delta_lambda/2)

cc<-2*atan2(sqrt(a),sqrt(1-a))

distance<- R * cc

return(distance)  # in meters
}

Round double value to 2 decimal places

You could do this:

NSNumberFormatter* f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setFormat:@0.00"];

// test
NSNumber* a = @12;
NSString* s = [f stringFromNumber:a];
NSLog(@"%@", s);

Auto reloading python Flask app upon code changes

Use this method:

app.run(debug=True)

It will auto-reload the flask app when a code change happens.

Sample code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
   return "Hello World"


if __name__ == '__main__':
  app.run(debug=True)

Well, if you want save time not reloading the webpage everytime when changes happen, then you can try the keyboard shortcut Ctrl + R to reload the page quickly.

Finding and removing non ascii characters from an Oracle Varchar2

I'm a bit late in answering this question, but had the same problem recently (people cut and paste all sorts of stuff into a string and we don't always know what it is). The following is a simple character whitelist approach:

SELECT est.clients_ref
  ,TRANSLATE (
              est.clients_ref
             ,   'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890#$%^&*()_+-={}|[]:";<>?,./'
              || REPLACE (
                          TRANSLATE (
                                     est.clients_ref
                                    ,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890#$%^&*()_+-={}|[]:";<>?,./'
                                    ,'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
                                    )
                         ,'~'
                         )
             ,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890#$%^&*()_+-={}|[]:";<>?,./'
             )
      clean_ref

FROM edms_staging_table est

Grunt watch error - Waiting...Fatal error: watch ENOSPC

I ran into this error after my client PC crashed, the jest --watch command I was running on the server persisted, and I tried to run jest --watch again.

The addition to /etc/sysctl.conf described in the answers above worked around this issue, but it was also important to find my old process via ps aux | grep node and kill it.

Using Linq to get the last N elements of a collection?

//detailed code for the problem
//suppose we have a enumerable collection 'collection'
var lastIndexOfCollection=collection.Count-1 ;
var nthIndexFromLast= lastIndexOfCollection- N;

var desiredCollection=collection.GetRange(nthIndexFromLast, N);
---------------------------------------------------------------------

// use this one liner
var desiredCollection=collection.GetRange((collection.Count-(1+N)), N);

Find the maximum value in a list of tuples in Python

You could loop through the list and keep the tuple in a variable and then you can see both values from the same variable...

num=(0, 0)
for item in tuplelist:
  if item[1]>num[1]:
    num=item #num has the whole tuple with the highest y value and its x value

How to Make Laravel Eloquent "IN" Query?

Syntax:

$data = Model::whereIn('field_name', [1, 2, 3])->get();

Use for Users Model

$usersList = Users::whereIn('id', [1, 2, 3])->get();

Failed to Connect to MySQL at localhost:3306 with user root

Go to >system preferences >mysql >initialize database

-Change password -Click use legacy password -Click start sql server

it should work now

How to check if NSString begins with a certain character

NSString* expectedString = nil;
if([givenString hasPrefix:@"*"])
{
   expectedString = [givenString substringFromIndex:1];
}

Express.js: how to get remote client address

This is just additional information for this answer.

If you are using nginx, you would add proxy_set_header X-Real-IP $remote_addr; to the location block for the site. /etc/nginx/sites-available/www.example.com for example. Here is a example server block.

server {
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;

    location / {
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_pass http://127.0.1.1:3080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

After restarting nginx, you will be able to access the ip in your node/express application routes with req.headers['x-real-ip'] || req.connection.remoteAddress;

How to get duration, as int milli's and float seconds from <chrono>?

I don't know what "milliseconds and float seconds" means, but this should give you an idea:

#include <chrono>
#include <thread>
#include <iostream>

int main()
{
  auto then = std::chrono::system_clock::now();
  std::this_thread::sleep_for(std::chrono::seconds(1));
  auto now = std::chrono::system_clock::now();
  auto dur = now - then;
  typedef std::chrono::duration<float> float_seconds;
  auto secs = std::chrono::duration_cast<float_seconds>(dur);
  std::cout << secs.count() << '\n';
}

Can I check if Bootstrap Modal Shown / Hidden?

When modal hide? we check like this :

$('.yourmodal').on('hidden.bs.modal', function () {
    // do something here
})

How do I make a fully statically linked .exe with Visual Studio Express 2005?

In regards Jared's response, having Windows 2000 or better will not necessarily fix the issue at hand. Rob's response does work, however it is possible that this fix introduces security issues, as Windows updates will not be able to patch applications built as such.

In another post, Nick Guerrera suggests packaging the Visual C++ Runtime Redistributable with your applications, which installs quickly, and is independent of Visual Studio.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

Java ByteBuffer to String

There is simpler approach to decode a ByteBuffer into a String without any problems, mentioned by Andy Thomas.

String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

Remove carriage return in Unix

Here is the thing,

%0d is the carriage return character. To make it compatabile with Unix. We need to use the below command.

dos2unix fileName.extension fileName.extension

Why do package names often begin with "com"

It's the domain name spelt out in reverse.

For example, one of my domains is hedgee.com. So, I use com.hedgee as the base name of all my packages.

Double array initialization in Java

double m[][] declares an array of arrays, so called multidimensional array.

m[0] points to an array in the size of four, containing 0*0,1*0,2*0,3*0. Simple math shows the values are actually 0,0,0,0.

Second line is also array in the size of four, containing 0,1,2,3.

And so on...

I guess this mutiple format in you book was to show that 0*0 is row 0 column 0, 0*1 is row 0 column 1, and so on.

WARNING: sanitizing unsafe style value url

For anyone who is already doing what the warning suggests you do, before the upgrade to Angular 5, I had to map my SafeStyle types to string before using them in the templates. After Angular 5, this is no longer the case. I had to change my models to have an image: SafeStyle instead of image: string. I was already using the [style.background-image] property binding and bypassing security on the whole url.

Hope this helps someone.

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

Here is the best way to find out Foreign Key Relationship in all Database.

exec sp_helpconstraint 'Table Name'

and one more way

select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME='Table Name'
--and left(CONSTRAINT_NAME,2)='FK'(If you want single key)