Programs & Examples On #Or operator

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

What does the construct x = x || y mean?

|| is the boolean OR operator. As in javascript, undefined, null, 0, false are considered as falsy values.

It simply means

true || true = true
false || true = true
true || false = true
false || false = false

undefined || "value" = "value"
"value" || undefined = "value"
null || "value" = "value"
"value" || null = "value"
0 || "value" = "value"
"value" || 0 = "value"
false || "value" = "value"
"value" || false = "value"

Logical Operators, || or OR?

Some languages use short-circuit, and others use full Boolean evaluation (if you know, this is similar to the directive $B in Pascal).

Explanations:

function A(){
    ...Do something..
    return true;
}

function B(){
    ...Do something..
    return true;
}

if ( A() OR B() ) { .....

In this example the function B() will never be executed. Since the function A() returns TRUE, the result of the OR statement is known from the first part without it being necessary to evaluate the second part of the expression.

However with ( A() || B() ), the second part is always evaluated regardless of the value of the first.

For optimized programming, you should always use OR which is faster (except for the case when the first part returns false and second part actually needs to be evaluated).

JavaScript OR (||) variable assignment explanation

This question has already received several good answers.

In summary, this technique is taking advantage of a feature of how the language is compiled. That is, JavaScript "short-circuits" the evaluation of Boolean operators and will return the value associated with either the first non-false variable value or whatever the last variable contains. See Anurag's explanation of those values that will evaluate to false.

Using this technique is not good practice for several reasons; however.

  1. Code Readability: This is using Boolean operators, and if the behavior of how this compiles is not understood, then the expected result would be a Boolean value.

  2. Stability: This is using a feature of how the language is compiled that is inconsistent across multiple languages, and due to this it is something that could potentially be targeted for change in the future.

  3. Documented Features: There is an existing alternative that meets this need and is consistent across more languages. This would be the ternary operator:

    () ? value 1: Value 2.

Using the ternary operator does require a little more typing, but it clearly distinguishes between the Boolean expression being evaluated and the value being assigned. In addition it can be chained, so the types of default assignments being performed above could be recreated.

var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';

var f =  ( a ) ? a : 
                ( b ) ? b :
                       ( c ) ? c :
                              ( d ) ? d :
                                      e;

alert(f); // 4

Changing .gitconfig location on Windows

I wanted to do the same thing. The best I could find was @MicTech's solution. However, as pointed out by @MotoWilliams this does not survive any updates made by Git to the .gitconfig file which replaces the link with a new file containing only the new settings.

I solved this by writing the following PowerShell script and running it in my profile startup script. Each time it is run it copies any settings that have been added to the user's .gitconfig to the global one and then replaces all the text in the .gitconfig file with and [include] header that imports the global file.

I keep the global .gitconfig file in a repo along with a lot of other global scripts and tools. All I have to do is remember to check in any changes that the script appends to my global file.

This seems to work pretty transparently for me. Hope it helps!

Sept 9th: Updated to detect when new entries added to the config file are duplicates and ignore them. This is useful for tools like SourceTree which will write new updates if they cannot find existing ones and do not follow includes.

function git-config-update
{
  $localPath = "$env:USERPROFILE\.gitconfig".replace('\', "\\")
  $globalPath = "C:\src\github\Global\Git\gitconfig".replace('\', "\\")

  $redirectAutoText = "# Generated file. Do not edit!`n[include]`n  path = $globalPath`n`n"
  $localText = get-content $localPath

  $diffs = (compare-object -ref $redirectAutoText.split("`n") -diff ($localText) | 
    measure-object).count

  if ($diffs -eq 0)
  {
    write-output ".gitconfig unchanged."
    return
  }

  $skipLines = 0
  $diffs = (compare-object -ref ($redirectAutoText.split("`n") | 
     select -f 3) -diff ($localText | select -f 3) | measure-object).count
  if ($diffs -eq 0)
  {
    $skipLines = 4
    write-warning "New settings appended to $localPath...`n "
  }
  else
  {
    write-warning "New settings found in $localPath...`n "
  }
  $localLines = (get-content $localPath | select -Skip $skipLines) -join "`n"
  $newSettings = $localLines.Split(@("["), [StringSplitOptions]::RemoveEmptyEntries) | 
    where { ![String]::IsNullOrWhiteSpace($_) } | %{ "[$_".TrimEnd() }

  $globalLines = (get-content  $globalPath) -join "`n"
  $globalSettings =  $globalLines.Split(@("["), [StringSplitOptions]::RemoveEmptyEntries)| 
    where { ![String]::IsNullOrWhiteSpace($_) } | %{ "[$_".TrimEnd() }

  $appendSettings = ($newSettings | %{ $_.Trim() } | 
    where { !($globalSettings -contains $_.Trim()) })
  if ([string]::IsNullOrWhitespace($appendSettings))
  {
    write-output "No new settings found."
  }
  else
  {
    echo $appendSettings
    add-content $globalPath ("`n# Additional settings added from $env:COMPUTERNAME on " + (Get-Date -displayhint date) + "`n" + $appendSettings)
  }
  set-content $localPath $redirectAutoText -force
}

Revert to Eclipse default settings

Just remove .metadata from your eclipse workspace You can find it C:\Users\username\workspace

how to extract only the year from the date in sql server 2008?

year(table_column)

Example:

select * from mytable where year(transaction_day)='2013' 

How can I find and run the keytool

Alternatively you can do the following :

  • copy the bat file below in any folder already present in your PATH environment variable
  • then simply use keytool command in any Windows shell

Actual location of keytool is defined in the bat file. In case the location is wrong the bat file will scan your system to detect potential locations in ProgramFiles (sub)folders.

Also find keytool2.bat, a convinient shortcut for "keytool -v -list -keystore", which is widely used to quickly check the content of a jks file.

keytool.bat :


:: 
:: 
:: "keytool alias" script by Céphas
:: easy method : add the known keytool.exe folder to your personal PATH variable (run : C:\Windows\System32\rundll32.exe sysdm.cpl,EditEnvironmentVariables)
:: else, add the folder containing this bat script to your personal path or put this script in any folder already defined in your path
::
:: also see keytool2.bat that automatically adds the following parameters in the keytool command line : -v -list -keystore, for quick display of jks content
:: 
:: 
@echo off
set THIS_SCRIPT=%~f0
rem  setlocal enableDelayedExpansion : necessary for paths containing special chars
setlocal enableDelayedExpansion

rem  set PATH to keytool.exe ; path must include the final \
rem  ^ is escape char for paths containing & \ < > ^ | 
set PATH_TO=C:\Program Files\Java\jre1.8.0_45\bin\
set PROG_NAME=keytool.exe

rem full_path, with "", to work with paths containing special chars
set FULL_KT_PATH="!PATH_TO!!PROG_NAME!"

rem checks if keytool.exe exists
(dir %FULL_KT_PATH%>nul 2>nul && set KT_FOUND=yes) || set KT_FOUND=no

if %KT_FOUND%==yes (
    rem keytool found => launching it with all supplied parameters
    rem 
    rem
    %FULL_KT_PATH% %*
    rem
    rem
) else (
    rem keytool not found, trying to find it in %ProgramFiles%

    echo.
    echo Keytool not found in expected location, scan in progess ...
    echo.

    cd "%ProgramFiles(x86)%" 2>nul && dir /B /S keytool.exe 2>nul

    cd "%ProgramFiles%" 2>nul && dir /B /S keytool.exe 2>nul

    echo.
    echo *********
    echo Path to program keytool.exe not properly defined, or keytool/java missing on this system
    echo If any location has been found during above scan, fix variable "PATH_TO" in %THIS_SCRIPT% accordingly
    echo *********
    echo.
    pause
    
)    

keytool2.bat :


:: 
:: 
:: "keytool2 alias" script by Céphas
:: easy method : add the known keytool.exe folder to your personal PATH variable (run : C:\Windows\System32\rundll32.exe sysdm.cpl,EditEnvironmentVariables)
:: else, add the folder containing this bat script to your personal path or put this script in any folder already defined in your path
::
:: keytool2 automatically adds the following parameters in the keytool command line : -v -list -keystore
:: thus, to quickly display the full content of a jks file, usage is simply : keytool2 \path\to\your\keystore.jks [-alias your_alias]
:: 
:: 
@echo off
set THIS_SCRIPT=%~f0
rem  setlocal enableDelayedExpansion : necessary for paths containing special chars
setlocal enableDelayedExpansion

rem  set PATH to keytool.exe ; path must include the final \
rem  ^ is escape char for paths containing & \ < > ^ | 
set PATH_TO=C:\Program Files\Java\jre1.8.0_45\bin\
set PROG_NAME=keytool.exe


rem full_path, with "", to work with paths containing special chars
set FULL_KT_PATH="!PATH_TO!!PROG_NAME!"

rem checks if keytool.exe exists
(dir %FULL_KT_PATH%>nul 2>nul && set KT_FOUND=yes) || set KT_FOUND=no

if %KT_FOUND%==yes (
    rem keytool found => launching it with all supplied parameters
    rem 
    rem
    %FULL_KT_PATH% -v -list -keystore %*
    rem
    rem
) else (
    rem keytool not found, trying to find it in %ProgramFiles%

    echo.
    echo Keytool not found in expected location, scan in progess ...
    echo.

    cd "%ProgramFiles(x86)%" 2>nul && dir /B /S keytool.exe 2>nul

    cd "%ProgramFiles%" 2>nul && dir /B /S keytool.exe 2>nul

    echo.
    echo *********
    echo Path to program keytool.exe not properly defined, or keytool/java missing on this system
    echo If any location has been found during above scan, fix variable "PATH_TO" in %THIS_SCRIPT% accordingly
    echo *********
    echo.
    pause
    
)    

How can I view the shared preferences file using Android Studio?

If you're using an emulator you can see the sharedPrefs.xml file on the terminal with this commands:

  • adb root
  • cat /data/data/<project name>/shared_prefs/<xml file>

after that you can use adb unroot if you dont want to keep the virtual device rooted.

File Upload ASP.NET MVC 3.0

I am giving you the simple and easy method to understand and learn.

First you have to write the following code in your .Cshtml file.

<input name="Image" type="file" class="form-control" id="resume" />

then in your controller put following code:

if (i > 0) {
    HttpPostedFileBase file = Request.Files["Image"];


    if (file != null && file.ContentLength > 0) {
        if (!string.IsNullOrEmpty(file.FileName)) {
            string extension = Path.GetExtension(file.FileName);

            switch ((extension.ToLower())) {
                case ".doc":
                    break;
                case ".docx":
                    break;
                case ".pdf":
                    break;
                default:
                    ViewBag.result = "Please attach file with extension .doc , .docx , .pdf";
                    return View();
            }

            if (!Directory.Exists(Server.MapPath("~") + "\\Resume\\")) {
                System.IO.Directory.CreateDirectory(Server.MapPath("~") + "\\Resume\\");
            }

            string documentpath = Server.MapPath("~") + "\\Resume\\" + i + "_" + file.FileName;
            file.SaveAs(documentpath);
            string filename = i + "_" + file.FileName;
            result = _objbalResume.UpdateResume(filename, i);
            Attachment at = new Attachment(documentpath);

            //ViewBag.result = (ans == true ? "Thanks for contacting us.We will reply as soon as possible" : "There is some problem. Please try again later.");
        }
    } else {
        ...
    }
}

For this you have to make BAL and DAL layer as per your Database.

PHP Fatal error: Uncaught exception 'Exception'

Just adding a bit of extra information here in case someone has the same issue as me.

I use namespaces in my code and I had a class with a function that throws an Exception.

However my try/catch code in another class file was completely ignored and the normal PHP error for an uncatched exception was thrown.

Turned out I forgot to add "use \Exception;" at the top, adding that solved the error.

CSS performance relative to translateZ(0)

CSS transformations create a new stacking context and containing block, as described in the spec. In plain English, this means that fixed position elements with a transformation applied to them will act more like absolutely positioned elements, and z-index values are likely to get screwed with.

If you take a look at this demo, you'll see what I mean. The second div has a transformation applied to it, meaning that it creates a new stacking context, and the pseudo elements are stacked on top rather than below.

So basically, don't do that. Apply a 3D transformation only when you need the optimization. -webkit-font-smoothing: antialiased; is another way to tap into 3D acceleration without creating these problems, but it only works in Safari.

How to create a temporary directory?

Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.

How to Run Terminal as Administrator on Mac Pro

You can run a command as admin using

sudo <command>

You can also switch to root and every command will be run as root

sudo su

How to set a value to a file input in HTML?

Not an answer to your question (which others have answered), but if you want to have some edit functionality of an uploaded file field, what you probably want to do is:

  • show the current value of this field by just printing the filename or URL, a clickable link to download it, or if it's an image: just show it, possibly as thumbnail
  • the <input> tag to upload a new file
  • a checkbox that, when checked, deletes the currently uploaded file. note that there's no way to upload an 'empty' file, so you need something like this to clear out the field's value

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

Supplement to Iman Mahmoudinasab's answer

For SQL Server 2016, this is where to find the files:

https://www.microsoft.com/en-us/download/details.aspx?id=52676

Note that the files are in the list but you may need to scroll down to see/select it.

From SQL Server 2017 onwards, things change:

"Beginning with SQL Server 2017 SMO is distributed as the Microsoft.SqlServer.SqlManagementObjects NuGet package to allow users to develop applications with SMO."

Source: https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/installing-smo?view=sql-server-2017

How can I copy the output of a command directly into my clipboard?

For those using bash installed on their windows system (known as Windows Subsystem for Linux (WSL)), attempting xclip will give an error:

Error: Can't open display: (null)

Instead, recall that linux subsystem has access to windows executables. It's possible to use clip.exe like

echo hello | clip.exe

which allows you to use the paste command (ctrl-v).

How to get all selected values of a multiple select box?

My template helper looks like this:

 'submit #update': function(event) {
    event.preventDefault();
    var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
    var array_opts = Object.values(obj_opts);  //convert to array
    var stray = array_opts.map((o)=> o.text ); //to filter your bits: text, value or selected
    //do stuff
}

How and where to use ::ng-deep?

Just an update:

You should use ::ng-deep instead of /deep/ which seems to be deprecated.

Per documentation:

The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

You can find it here

How to randomly select rows in SQL?

SELECT * FROM TABLENAME ORDER BY random() LIMIT 5; 

How to do a GitHub pull request

I've started a project to help people making their first GitHub pull request. You can do the hands-on tutorial to make your first PR here

The workflow is simple as

  • Fork the repo in github
  • Get clone url by clicking on clone repo button
  • Go to terminal and run git clone <clone url you copied earlier>
  • Make a branch for changes you're makeing git checkout -b branch-name
  • Make necessary changes
  • Commit your changes git commit
  • Push your changes to your fork on GitHub git push origin branch-name
  • Go to your fork on GitHub to see a Compare and pull request button
  • Click on it and give necessary details

JQuery, Spring MVC @RequestBody and JSON - making it work together

In case you are willing to use Curl for the calls with JSON 2 and Spring 3.2.0 in hand checkout the FAQ here. As AnnotationMethodHandlerAdapter is deprecated and replaced by RequestMappingHandlerAdapter.

Pass array to mvc Action via AJAX

I have had issues in the past when attempting to perform a POST (not sure if that is exactly what you are doing, but I recall when passing an array in, traditional must be set to true.

 var arrayOfValues = new Array();

 //Populate arrayOfValues 
 $.ajax({ 
      type: "POST",
      url: "<%= Url.Action("MyAction","Controller")%>",
      traditional: true,
      data: { 'arrayOfValues': arrayOfValues }              
 });

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

For me this has worked-

ALTER TABLE table_name ALTER COLUMN column_name VARCHAR(50)

http://localhost/phpMyAdmin/ unable to connect

http://localhost:(port number of phpmyadmin)/phpmyadmin/

For example: http://localhost:8080/phpmyadmin/

It works great!

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

Running shell command and capturing the output

Your Mileage May Vary, I attempted @senderle's spin on Vartec's solution in Windows on Python 2.6.5, but I was getting errors, and no other solutions worked. My error was: WindowsError: [Error 6] The handle is invalid.

I found that I had to assign PIPE to every handle to get it to return the output I expected - the following worked for me.

import subprocess

def run_command(cmd):
    """given shell command, returns communication tuple of stdout and stderr"""
    return subprocess.Popen(cmd, 
                            stdout=subprocess.PIPE, 
                            stderr=subprocess.PIPE, 
                            stdin=subprocess.PIPE).communicate()

and call like this, ([0] gets the first element of the tuple, stdout):

run_command('tracert 11.1.0.1')[0]

After learning more, I believe I need these pipe arguments because I'm working on a custom system that uses different handles, so I had to directly control all the std's.

To stop console popups (with Windows), do this:

def run_command(cmd):
    """given shell command, returns communication tuple of stdout and stderr"""
    # instantiate a startupinfo obj:
    startupinfo = subprocess.STARTUPINFO()
    # set the use show window flag, might make conditional on being in Windows:
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    # pass as the startupinfo keyword argument:
    return subprocess.Popen(cmd,
                            stdout=subprocess.PIPE, 
                            stderr=subprocess.PIPE, 
                            stdin=subprocess.PIPE, 
                            startupinfo=startupinfo).communicate()

run_command('tracert 11.1.0.1')

Are querystring parameters secure in HTTPS (HTTP + SSL)?

Yes. The querystring is also encrypted with SSL. Nevertheless, as this article shows, it isn't a good idea to put sensitive information in the URL. For example:

URLs are stored in web server logs - typically the whole URL of each request is stored in a server log. This means that any sensitive data in the URL (e.g. a password) is being saved in clear text on the server

Replace Div with another Div

This should help you

HTML

<!-- pretty much i just need to click a link within the regions table and it changes to the neccesary div. -->

<table>
<tr class="thumb"></tr>
    <td><a href="#" class="showall">All Regions</a> (shows main map) (link)</td>   

<tr class="thumb"></tr>
<td>Northern Region (link)</td>
</tr>

<tr class="thumb"></tr>
<td>Southern Region (link)</td>
</tr>

<tr class="thumb"></tr>
<td>Eastern Region (link)</td>
</tr>
</table>
<br />

<div id="mainmapplace">
    <div id="mainmap">
        All Regions image
    </div>
</div>
<div id="region">
    <div class="replace">northern image</div>
    <div class="replace">southern image</div>
    <div class="replace">Eastern image</div>
</div>

JavaScript

var originalmap;
var flag = false;

$(function (){

    $(".replace").click(function(){
            flag = true;
            originalmap = $('#mainmap');
            $('#mainmap').replaceWith($(this));
        });

    $('.showall').click(
        function(){
            if(flag == true){
                $('#region').append($('#mainmapplace .replace'));                
                $('#mainmapplace').children().remove();
                $('#mainmapplace').append($(originalmap));
                //$('#mapplace').append();
            }
        }
    )

})

CSS

#mainmapplace{
    width: 100px;
    height: 100px;
    background: red;
}

#region div{
    width: 100px;
    height: 100px;
    background: blue;
    margin: 10px 0 0 0;
}

How can I disable mod_security in .htaccess file?

In .htaccess file at site root directory edit following line:

_x000D_
_x000D_
<ifmodule mod_security.c>_x000D_
_x000D_
SecFilterEngine Off_x000D_
SecFilterScanPOST Off_x000D_
_x000D_
</ifmodule>_x000D_
_x000D_
<IfModule mod_rewrite.c>_x000D_
RewriteEngine On_x000D_
RewriteBase /_x000D_
RewriteCond %{REQUEST_FILENAME} !-f_x000D_
RewriteCond %{REQUEST_FILENAME} !-d_x000D_
RewriteRule . /index.php [L]_x000D_
</IfModule>
_x000D_
_x000D_
_x000D_

Just keep the mod_security rules like SecFilterEngine and parts apart from each other. Its works for apache server

Split string with delimiters in C

This is a string splitting function that can handle multi-character delimiters. Note that if the delimiter is longer than the string that is being split, then buffer and stringLengths will be set to (void *) 0, and numStrings will be set to 0.

This algorithm has been tested, and works. (Disclaimer: It has not been tested for non-ASCII strings, and it assumes that the caller gave valid parameters)

void splitString(const char *original, const char *delimiter, char ** * buffer, int * numStrings, int * * stringLengths){
    const int lo = strlen(original);
    const int ld = strlen(delimiter);
    if(ld > lo){
        *buffer = (void *)0;
        *numStrings = 0;
        *stringLengths = (void *)0;
        return;
    }

    *numStrings = 1;

    for(int i = 0;i < (lo - ld);i++){
        if(strncmp(&original[i], delimiter, ld) == 0) {
            i += (ld - 1);
            (*numStrings)++;
        }
    }

    *stringLengths = (int *) malloc(sizeof(int) * *numStrings);

    int currentStringLength = 0;
    int currentStringNumber = 0;
    int delimiterTokenDecrementCounter = 0;
    for(int i = 0;i < lo;i++){
        if(delimiterTokenDecrementCounter > 0){
            delimiterTokenDecrementCounter--;
        } else if(i < (lo - ld)){
            if(strncmp(&original[i], delimiter, ld) == 0){
                (*stringLengths)[currentStringNumber] = currentStringLength;
                currentStringNumber++;
                currentStringLength = 0;
                delimiterTokenDecrementCounter = ld - 1;
            } else {
                currentStringLength++;
            }
        } else {
            currentStringLength++;
        }

        if(i == (lo - 1)){
            (*stringLengths)[currentStringNumber] = currentStringLength;
        }
    }

    *buffer = (char **) malloc(sizeof(char *) * (*numStrings));
    for(int i = 0;i < *numStrings;i++){
        (*buffer)[i] = (char *) malloc(sizeof(char) * ((*stringLengths)[i] + 1));
    }

    currentStringNumber = 0;
    currentStringLength = 0;
    delimiterTokenDecrementCounter = 0;
    for(int i = 0;i < lo;i++){
        if(delimiterTokenDecrementCounter > 0){
            delimiterTokenDecrementCounter--;
        } else if(currentStringLength >= (*stringLengths)[currentStringNumber]){
            (*buffer)[currentStringNumber][currentStringLength] = 0;
            delimiterTokenDecrementCounter = ld - 1;
            currentStringLength = 0;
            currentStringNumber++;
        } else {
            (*buffer)[currentStringNumber][currentStringLength] = (char)original[i];
            currentStringLength++;
        }
    }
    buffer[currentStringNumber][currentStringLength] = 0;
}

Sample code:

int main(){
    const char *string = "STRING-1 DELIM string-2 DELIM sTrInG-3";
    char **buffer;
    int numStrings;
    int * stringLengths;

    splitString(string, " DELIM ", &buffer, &numStrings, &stringLengths);

    for(int i = 0;i < numStrings;i++){
        printf("String: %s\n", buffer[i]);
    }
}

Libraries:

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

How to deal with missing src/test/java source folder in Android/Maven project?

Removing the m2 plugin from startup-up plugin's list and doing a Maven->Update Projects on all the projects worked for me.

Note** One should not create additional folders to avoid merging them while using SVN/Git based branches.

Mount current directory as a volume in Docker on Windows 10

Command prompt (Cmd.exe)

When the Docker CLI is used from the Windows Cmd.exe, use %cd% to mount the current directory:

echo test > test.txt
docker run --rm -v %cd%:/data busybox ls -ls /data/test.txt

Git Bash (MinGW)

When the Docker CLI is used from the Git Bash (MinGW), mounting the current directory may fail due to a POSIX path conversion: Docker mounted volume adds ;C to end of windows path when translating from linux style path.

Escape the POSIX paths by prefixing with /

To skip the path conversion, POSIX paths have to be prefixed with the slash (/) to have leading double slash (//), including /$(pwd)

touch test.txt
docker run --rm -v /$(pwd):/data busybox ls -la //data/test.txt

Disable the path conversion

Disable the POSIX path conversion in Git Bash (MinGW) by setting MSYS_NO_PATHCONV=1 environment variable at the command level

touch test.txt
MSYS_NO_PATHCONV=1 docker run --rm -v $(pwd):/data busybox ls -la /data/test.txt

or shell (system) level

export MSYS_NO_PATHCONV=1
touch test.txt
docker run --rm -v $(pwd):/data busybox ls -la /data/test.txt

Android Layout Weight

android:Layout_weight can be used when you don't attach a fix value to your width already like fill_parent etc.

Do something like this :

<Button>

Android:layout_width="0dp"
Android:layout_weight=1

-----other parameters
</Button>

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Update: I should have probably started with this as your projects are SNAPSHOTs. It is part of the SNAPSHOT semantics that Maven will check for updates on each build. Being a SNAPSHOT means that it is volatile and subject to change so updates should be checked for. However it's worth pointing out that the Maven super POM configures central to have snapshots disabled, so Maven shouldn't ever check for updates for SNAPSHOTs on central unless you've overridden that in your own pom/settings.


You can configure Maven to use a mirror for the central repository, this will redirect all requests that would normally go to central to your internal repository.

In your settings.xml you would add something like this to set your internal repository as as mirror for central:

<mirrors>
  <mirror>
    <id>ibiblio.org</id>
    <name>ibiblio Mirror of http://repo1.maven.org/maven2/</name>
    <url>http://path/to/my/repository</url>
    <mirrorOf>central</mirrorOf>
  </mirror>
</mirrors>

If you are using a repository manager like Nexus for your internal repository. You can set up a proxy repository for proxy central, so any requests that would normally go to Central are instead sent to your proxy repository (or a repository group containing the proxy), and subsequent requests are cached in the internal repository manager. You can even set the proxy cache timeout to -1, so it will never request for contents from central that are already on the proxy repository.


A more basic solution if you are only working with local repositories is to set the updatePolicy for the central repository to "never", this means Maven will only ever check for artifacts that aren't already in the local repository. This can then be overridden at the command line when needed by using the -U switch to force Maven to check for updates.

You would configure the repository (in your pom or a profile in the settings.xml) as follows:

<repository>
  <id>central</id>
  <url>http://repo1.maven.org/maven2</url>
  <updatePolicy>never</updatePolicy>
</repository>

Difference between require, include, require_once and include_once?

Whenever you are using require_once() can be use in a file to include another file when you need the called file only a single time in the current file. Here in the example I have an test1.php.

<?php  
echo "today is:".date("Y-m-d");  
?>  

and in another file that I have named test2.php

<?php  
require_once('test1.php');  
require_once('test1.php');  
?>

as you are watching the m requiring the the test1 file twice but the file will include the test1 once and for calling at the second time this will be ignored. And without halting will display the output a single time.

Whenever you are using 'include_once()` can be used in a file to include another file when you need the called file more than once in the current file. Here in the example I have a file named test3.php.

<?php  
echo "today is:".date("Y-m-d");  
?> 

And in another file that I have named test4.php

<?php  
include_once('test3.php');  
include_once('test3.php');  
?>

as you are watching the m including the test3 file will include the file a single time but halt the further execution.

Laravel 5.1 - Checking a Database Connection

Another Approach:

When Laravel tries to connect to database, if the connection fails or if it finds any errors it will return a PDOException error. We can catch this error and redirect the action

Add the following code in the app/filtes.php file.

App::error(function(PDOException $exception)
{
    Log::error("Error connecting to database: ".$exception->getMessage());

    return "Error connecting to database";
});

Hope this is helpful.

How to program a fractal?

Here is a codepen that I wrote for the Mandelbrot fractal using plain javascript and HTML.

Hopefully it is easy to understand the code.

The most complicated part is scale and translate the coordinate systems. Also complicated is making the rainbow palette.

function mandel(x,y) {
  var a=0; var b=0;
  for (i = 0; i<250; ++i) {
    // Complex z = z^2 + c
    var t = a*a - b*b;
    b = 2*a*b;
    a = t;
    a = a + x;
    b = b + y;
    var m = a*a + b*b;
    if (m > 10)  return i;
  }
  return 250;
}

enter image description here

How to hide collapsible Bootstrap 4 navbar on click

You can call $.collapse('hide'); with an event handler on the links.

_x000D_
_x000D_
$('.nav-link').on('click',function() {_x000D_
  $('.navbar-collapse').collapse('hide');_x000D_
});
_x000D_
.navbar-toggler .icon-bar {_x000D_
  margin: 7px;_x000D_
  display: block;_x000D_
  width: 22px;_x000D_
  height: 1px;_x000D_
  background-color: #cccccc;_x000D_
  border-radius: 1px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-toggleable-md fixed-top">_x000D_
  <button id="nav-btn" class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarDiv" aria-expanded="false" aria-label="Toggle navigation">_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
 </button>_x000D_
  <div class="container">_x000D_
    <a class="navbar-brand" href="#"><img src="Images/logo.png" width="60px"></a>_x000D_
    <div class="collapse navbar-collapse" id="navbarDiv">_x000D_
      <ul class="navbar-nav mr-auto">_x000D_
        <li class="nav-item active">_x000D_
          <a class="nav-link" href="#home">Home <span class="sr-only">(current)</span></a>_x000D_
        </li>_x000D_
        <li class="nav-item">_x000D_
          <a class="nav-link" href="#about-us">About</a>_x000D_
        </li>_x000D_
        <li class="nav-item">_x000D_
          <a class="nav-link" href="#pricing">Pricing</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Set UIButton title UILabel font size programmatically

I hope it will be help to you

[_button.titleLabel setFont:[UIFont systemFontOfSize:15]];  

good luck

Angular 4 - Select default value in dropdown [Reactive Forms]

As option, if you need just default text in dropdown without default value, try add <option disabled value="null">default text here</option> like this:

<select id="country" formControlName="country">
 <option disabled value="null">default text here</option>
 <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>

In Chrome and Firefox works fine.

How do I Convert DateTime.now to UTC in Ruby?

d = DateTime.now.utc

Oops!

That seems to work in Rails, but not vanilla Ruby (and of course that is what the question is asking)

d = Time.now.utc

Does work however.

Is there any reason you need to use DateTime and not Time? Time should include everything you need:

irb(main):016:0> Time.now
=> Thu Apr 16 12:40:44 +0100 2009

get specific row from spark dataframe

Following is a Java-Spark way to do it , 1) add a sequentially increment columns. 2) Select Row number using Id. 3) Drop the Column

import static org.apache.spark.sql.functions.*;
..

ds = ds.withColumn("rownum", functions.monotonically_increasing_id());
ds = ds.filter(col("rownum").equalTo(99));
ds = ds.drop("rownum");

N.B. monotonically_increasing_id starts from 0;

How do I provide a username and password when running "git clone [email protected]"?

git config --global core.askpass

Run this first before cloning the same way, should be fixed!

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

could not extract ResultSet in hibernate

For MySql take in mind that it's not a good idea to write camelcase. For example if the schema is like that:

CREATE TABLE IF NOT EXISTS `task`(
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `teaching_hours` DECIMAL(5,2) DEFAULT NULL,
    `isActive` BOOLEAN DEFAULT FALSE,
    `is_validated` BOOLEAN DEFAULT FALSE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You must be very careful cause isActive column will translate to isactive. So in your Entity class is should be like this:

 @Basic
 @Column(name = "isactive", nullable = true)
 public boolean isActive() {
     return isActive;
 }
 public void setActive(boolean active) {
     isActive = active;
 }

That was my problem at least that got me your error

This has nothing to do with MySql which is case insensitive, but rather is a naming strategy that spring will use to translate your tables. For more refer to this post

How can I pretty-print JSON using Go?

package cube

import (
    "encoding/json"
    "fmt"
    "github.com/magiconair/properties/assert"
    "k8s.io/api/rbac/v1beta1"
    v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "testing"
)

func TestRole(t *testing.T)  {
    clusterRoleBind := &v1beta1.ClusterRoleBinding{
        ObjectMeta: v1.ObjectMeta{
            Name: "serviceaccounts-cluster-admin",
        },
        RoleRef: v1beta1.RoleRef{
            APIGroup: "rbac.authorization.k8s.io",
            Kind:     "ClusterRole",
            Name:     "cluster-admin",
        },
        Subjects: []v1beta1.Subject{{
            Kind:     "Group",
            APIGroup: "rbac.authorization.k8s.io",
            Name:     "system:serviceaccounts",
        },
        },
    }
    b, err := json.MarshalIndent(clusterRoleBind, "", "  ")
    assert.Equal(t, nil, err)
    fmt.Println(string(b))
}

How it looks like

Call a stored procedure with another in Oracle

To invoke the procedure from the SQLPlus command line, try one of these:

CALL test_sp_1();
EXEC test_sp_1

Comparing two collections for equality irrespective of the order of items in them

In the case of no repeats and no order, the following EqualityComparer can be used to allow collections as dictionary keys:

public class SetComparer<T> : IEqualityComparer<IEnumerable<T>> 
where T:IComparable<T>
{
    public bool Equals(IEnumerable<T> first, IEnumerable<T> second)
    {
        if (first == second)
            return true;
        if ((first == null) || (second == null))
            return false;
        return first.ToHashSet().SetEquals(second);
    }

    public int GetHashCode(IEnumerable<T> enumerable)
    {
        int hash = 17;

        foreach (T val in enumerable.OrderBy(x => x))
            hash = hash * 23 + val.GetHashCode();

        return hash;
    }
}

Here is the ToHashSet() implementation I used. The hash code algorithm comes from Effective Java (by way of Jon Skeet).

Autoincrement VersionCode with gradle extra properties

Here comes a modernization of my previous answer which can be seen below. This one is running with Gradle 4.4 and Android Studio 3.1.1.

What this script does:

  • Creates a version.properties file if none exists (up vote Paul Cantrell's answer below, which is where I got the idea from if you like this answer)
  • For each build, debug release or any time you press the run button in Android Studio the VERSION_BUILD number increases.
  • Every time you assemble a release your Android versionCode for the play store increases and your patch number increases.
  • Bonus: After the build is done copies your apk to projectDir/apk to make it more accessible.

This script will create a version number which looks like v1.3.4 (123) and build an apk file like AppName-v1.3.4.apk.

Major version ?       ? Build version
             v1.3.4 (123)
  Minor version ^|^ Patch version

Major version: Has to be changed manually for bigger changes.

Minor version: Has to be changed manually for slightly less big changes.

Patch version: Increases when running gradle assembleRelease

Build version: Increases every build

Version Number: Same as Patch version, this is for the version code which Play Store needs to have increased for each new apk upload.

Just change the content in the comments labeled 1 - 3 below and the script should do the rest. :)

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.3'

    def versionPropsFile = file('version.properties')
    def value = 0
    Properties versionProps = new Properties()
    if (!versionPropsFile.exists()) {
        versionProps['VERSION_PATCH'] = "0"
        versionProps['VERSION_NUMBER'] = "0"
        versionProps['VERSION_BUILD'] = "-1" // I set it to minus one so the first build is 0 which isn't super important. 
        versionProps.store(versionPropsFile.newWriter(), null)
    }

    def runTasks = gradle.startParameter.taskNames
    if ('assembleRelease' in runTasks) {
        value = 1
    }

    def mVersionName = ""
    def mFileName = ""

    if (versionPropsFile.canRead()) {
        versionProps.load(new FileInputStream(versionPropsFile))

        versionProps['VERSION_PATCH'] = (versionProps['VERSION_PATCH'].toInteger() + value).toString()
        versionProps['VERSION_NUMBER'] = (versionProps['VERSION_NUMBER'].toInteger() + value).toString()
        versionProps['VERSION_BUILD'] = (versionProps['VERSION_BUILD'].toInteger() + 1).toString()

        versionProps.store(versionPropsFile.newWriter(), null)

        // 1: change major and minor version here
        mVersionName = "v1.0.${versionProps['VERSION_PATCH']}"
        // 2: change AppName for your app name
        mFileName = "AppName-${mVersionName}.apk"

        defaultConfig {
            minSdkVersion 21
            targetSdkVersion 27
            applicationId "com.example.appname" // 3: change to your package name
            versionCode versionProps['VERSION_NUMBER'].toInteger()
            versionName "${mVersionName} Build: ${versionProps['VERSION_BUILD']}"
        }

    } else {
        throw new FileNotFoundException("Could not read version.properties!")
    }

    if ('assembleRelease' in runTasks) {
        applicationVariants.all { variant ->
            variant.outputs.all { output ->
                if (output.outputFile != null && output.outputFile.name.endsWith('.apk')) {
                    outputFileName = mFileName
                }
            }
        }
    }

    task copyApkFiles(type: Copy){
        from 'build/outputs/apk/release'
        into '../apk'
        include mFileName
    }

    afterEvaluate {
        assembleRelease.doLast {
            tasks.copyApkFiles.execute()
        }
    }

    signingConfigs {
        ...
    }

    buildTypes {
        ...
    }
}

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

INITIAL ANSWER:

I want the versionName to increase automatically as well. So this is just an addition to the answer by CommonsWare which worked perfectly for me. This is what works for me

defaultConfig {
    versionCode code
    versionName "1.1." + code
    minSdkVersion 14
    targetSdkVersion 18
}

EDIT:

As I am a bit lazy I want my versioning to work as automatically as possible. What I want is to have a Build Version that increases with each build, while the Version Number and Version Name only increases when I make a release build.

This is what I have been using for the past year, the basics are from CommonsWare's answer and my previous answer, plus some more. This results in the following versioning:

Version Name: 1.0.5 (123) --> Major.Minor.Patch (Build), Major and Minor are changed manually.

In build.gradle:

...
android {
    compileSdkVersion 23
    buildToolsVersion '23.0.1'
    def versionPropsFile = file('version.properties')
    if (versionPropsFile.canRead()) {
        def Properties versionProps = new Properties()

        versionProps.load(new FileInputStream(versionPropsFile))

        def value = 0

        def runTasks = gradle.startParameter.taskNames
        if ('assemble' in runTasks || 'assembleRelease' in runTasks || 'aR' in runTasks) {
            value = 1;
        }

        def versionMajor = 1
        def versionMinor = 0
        def versionPatch = versionProps['VERSION_PATCH'].toInteger() + value
        def versionBuild = versionProps['VERSION_BUILD'].toInteger() + 1
        def versionNumber = versionProps['VERSION_NUMBER'].toInteger() + value

        versionProps['VERSION_PATCH'] = versionPatch.toString()
        versionProps['VERSION_BUILD'] = versionBuild.toString()
        versionProps['VERSION_NUMBER'] = versionNumber.toString()

        versionProps.store(versionPropsFile.newWriter(), null)

        defaultConfig {
            versionCode versionNumber
            versionName "${versionMajor}.${versionMinor}.${versionPatch} (${versionBuild}) Release"
            minSdkVersion 14
            targetSdkVersion 23
        }

        applicationVariants.all { variant ->
            variant.outputs.each { output ->
                def fileNaming = "apk/RELEASES"
                variant.outputs.each { output ->
                    def outputFile = output.outputFile
                    if (outputFile != null && outputFile.name.endsWith('.apk')) {
                        output.outputFile = new File(getProject().getRootDir(), "${fileNaming}-${versionMajor}.${versionMinor}.${versionPatch}-${outputFile.name}")
                    }
                }
            }
        }

    } else {
        throw new GradleException("Could not read version.properties!")
    }

    ...
}

...

Patch and versionCode is increased if you assemble your project through the terminal with 'assemble', 'assembleRelease' or 'aR' which creates a new folder in your project root called apk/RELEASE so you don't have to look through build/outputs/more/more/more to find your apk.

Your version properties would need to look like this:

VERSION_NUMBER=1
VERSION_BUILD=645
VERSION_PATCH=1

Obviously start with 0. :)

"Field has incomplete type" error

You are using a forward declaration for the type MainWindowClass. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

So, you either want:

// forward declaration, details unknown
class A;

class B {
  A *a;  // pointer to A, ok
};

Or, if you can't use a pointer or reference....

// declaration of A
#include "A.h"

class B {
  A a;  // ok, declaration of A is known
};

At some point, the compiler needs to know the details of A.

If you are only storing a pointer to A then it doesn't need those details when you declare B. It needs them at some point (whenever you actually dereference the pointer to A), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A.

// B.h
// header file

// forward declaration, details unknown
class A;

class B {
public: 
    void foo();
private:
  A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
    // here we need to know the declaration of A
    a->whatever();
}

How do I hide the PHP explode delimiter from submitted form results?

You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.

$fh = fopen("employees.txt", "r"); if ($fh) {     while (($line = fgets($fh)) !== false) {         $line = trim($line);         echo "<option value='".$line."'>".$line."</option>";     } } else {     // error opening the file, do something } 

Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?

And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.

assign headers based on existing row in dataframe in R

The cleanest way is use a function of janitor package that is built for exactly this purpose.

janitor::row_to_names(DF,1)

If you want to use any other row than the first one, pass it in the second parameter.

Execute a command line binary with Node.js

Since version 4 the closest alternative is child_process.execSync method:

const {execSync} = require('child_process');

let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');

?? Note that execSync call blocks event loop.

Maintain image aspect ratio when changing height

Most of images with intrinsic dimensions, that is a natural size, like a jpeg image. If the specified size defines one of both the width and the height, the missing value is determined using the intrinsic ratio... - see MDN.

But that doesn't work as expected if the images that are being set as direct flex items with the current Flexible Box Layout Module Level 1, as far as I know.

See these discussions and bug reports might be related:

  • Flexbugs #14 - Chrome/Flexbox Intrinsic Sizing not implemented correctly.
  • Firefox Bug 972595 - Flex containers should use "flex-basis" instead of "width" for computing intrinsic widths of flex items
  • Chromium Issue 249112 - In Flexbox, allow intrinsic aspect ratios to inform the main-size calculation.

As a workaround, you could wrap each <img> with a <div> or a <span>, or so.

jsFiddle

_x000D_
_x000D_
.slider {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.slider>div {_x000D_
  min-width: 0; /* why? see below. */_x000D_
}_x000D_
_x000D_
.slider>div>img {_x000D_
  max-width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<div class="slider">_x000D_
  <div><img src="https://picsum.photos/400/300?image=0" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=1" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=2" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=3" /></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

4.5 Implied Minimum Size of Flex Items

To provide a more reasonable default minimum size for flex items, this specification introduces a new auto value as the initial value of the min-width and min-height properties defined in CSS 2.1.


Alternatively, you can use CSS table layout instead, which you'll get similar results as flexbox, it will work on more browsers, even for IE8.

jsFiddle

_x000D_
_x000D_
.slider {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.slider>div {_x000D_
  display: table-cell;_x000D_
  vertical-align: top;_x000D_
}_x000D_
_x000D_
.slider>div>img {_x000D_
  max-width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<div class="slider">_x000D_
  <div><img src="https://picsum.photos/400/300?image=0" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=1" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=2" /></div>_x000D_
  <div><img src="https://picsum.photos/400/300?image=3" /></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I faced the same problem and solved it by adding:

System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");

before openConnection method.

How to program a delay in Swift 3

//Runs function after x seconds

public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) {
    runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}

public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) {
    let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    queue.asyncAfter(deadline: time, execute: after)
}

//Use:-

runThisAfterDelay(seconds: x){
  //write your code here
}

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

Find length of 2D array Python

Assuming input[row][col],

    rows = len(input)
    cols = map(len, input)  #list of column lengths

Breaking out of a for loop in Java

If for some reason you don't want to use the break instruction (if you think it will disrupt your reading flow next time you will read your programm, for example), you can try the following :

boolean test = true;
for (int i = 0; i < 1220 && test; i++) {
    System.out.println(i);
    if (i == 20) {
        test = false;
    }
 }

The second arg of a for loop is a boolean test. If the result of the test is true, the loop will stop. You can use more than just an simple math test if you like. Otherwise, a simple break will also do the trick, as others said :

for (int i = 0; i < 1220 ; i++) {
    System.out.println(i);
    if (i == 20) {
        break;
    }
 }

How can I return the current action in an ASP.NET MVC view?

Override this function in your controller

protected override void HandleUnknownAction(string actionName) 
{  TempData["actionName"] = actionName;
   View("urViewName").ExecuteResult(this.ControllerContext);
}

What is the difference between precision and scale?

If value is 9999.988 and Precision 4, scale 2 then it means 9999(it represents precision).99(scale is 2 so .988 is rounded to .99)

If value is 9999.9887 and precision is 4, scale is 2 then it means 9999.99

android: data binding error: cannot find symbol class

your model just have getter and setter in androidX. else not find your model in view and show this bug

public class User {

String name;

public String getName() {
    return name;
}
public User(String name) {
    this.name = name;
}

}

What is a "callable"?

callables implement the __call__ special method so any object with such a method is callable.

Where am I? - Get country

First, get the LocationManager. Then, call LocationManager.getLastKnownPosition. Then create a GeoCoder and call GeoCoder.getFromLocation. Do this is in a separate thread!! This will give you a list of Address objects. Call Address.getCountryName and you got it.

Keep in mind that the last known position can be a bit stale, so if the user just crossed the border, you may not know about it for a while.

How can I get Docker Linux container information from within the container itself?

You can communicate with docker from inside of a container using unix socket via Docker Remote API:

https://docs.docker.com/engine/reference/api/docker_remote_api/

In a container, you can find out a shortedned docker id by examining $HOSTNAME env var. According to doc, there is a small chance of collision, I think that for small number of container, you do not have to worry about it. I don't know how to get full id directly.

You can inspect container similar way as outlined in banyan answer:

GET /containers/4abbef615af7/json HTTP/1.1

Response:

HTTP/1.1 200 OK
Content-Type: application/json

{
         "Id": "4abbef615af7......  ",
         "Created": "2013.....",
         ...
}

Alternatively, you can transfer docker id to the container in a file. The file is located on "mounted volume" so it is transfered to container:

docker run -t -i -cidfile /mydir/host1.txt -v /mydir:/mydir ubuntu /bin/bash

The docker id (shortened) will be in file /mydir/host1.txt in the container.

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

package com.mycompany;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Car {

    @NotNull
    private String manufacturer;

    @NotNull
    @Size(min = 2, max = 14)
    private String licensePlate;

    @Min(2)
    private int seatCount;

    public Car(String manufacturer, String licencePlate, int seatCount) {
        this.manufacturer = manufacturer;
        this.licensePlate = licencePlate;
        this.seatCount = seatCount;
    }

    //getters and setters ...
}

@NotNull, @Size and @Min are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:

manufacturer shall never be null

licensePlate shall never be null and must be between 2 and 14 characters long

seatCount shall be at least 2.

How to print a int64_t type in C

//VC6.0 (386 & better)

    __int64 my_qw_var = 0x1234567890abcdef;

    __int32 v_dw_h;
    __int32 v_dw_l;

    __asm
        {
            mov eax,[dword ptr my_qw_var + 4]   //dwh
            mov [dword ptr v_dw_h],eax

            mov eax,[dword ptr my_qw_var]   //dwl
            mov [dword ptr v_dw_l],eax

        }
        //Oops 0.8 format
    printf("val = 0x%0.8x%0.8x\n", (__int32)v_dw_h, (__int32)v_dw_l);

Regards.

Android Studio - Unable to find valid certification path to requested target

It happened to me, and turned out it was because of Charles Proxy.

Charles Proxy is a HTTP debugging proxy server application

Solution (only if you have Charles Proxy installed):

  1. Shut down Charles Proxy;
  2. Restart Android Studio.

What properties can I use with event.target?

//Do it like---
function dragStart(this_,event) {
    var row=$(this_).attr('whatever');
    event.dataTransfer.setData("Text", row);
}

How to increase Bootstrap Modal Width?

I had a large grid that needed to be displayed in the modal and just applying the width on body was not working correctly as table was overflowing though it had bootstrap classes on it. I ended up applying same width on modal-body and modal-content :

<!--begin::Modal-->
<div class="modal fade" role="dialog" aria-labelledby="" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content" style="width:980px;">
            <div class="modal-header">
                <h5 class="modal-title" id="">Title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true" class="la la-remove"></span>
                </button>
            </div>
            <form class="m-form m-form--fit m-form--label-align-right">
                <div class="modal-body" style="width:980px;">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-brand m-btn" data-dismiss="modal">Close</button>

                </div>
            </form>
        </div>
    </div>
</div>

<!--end::Modal-->

EnterKey to press button in VBA Userform

This one worked for me

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = 13 Then
             Button1_Click
        End If
End Sub

How do I see the commit differences between branches in git?

I'd suggest the following to see the difference "in commits". For symmetric difference, repeat the command with inverted args:

git cherry -v master [your branch, or HEAD as default]

Create <div> and append <div> dynamically

    while(i<10){
               $('#Postsoutput').prepend('<div id="first'+i+'">'+i+'</div>');
               /* get the dynamic Div*/
               $('#first'+i).hide(1000);
               $('#first'+i).show(1000);
                i++;
                }

html tables & inline styles

This should do the trick:

<table width="400" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="50" height="40" valign="top" rowspan="3">
      <img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
    </td>
  </tr>
  <tr>
    <td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

UPDATE: Adjusted code per the comments:

After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.

Here is an example that will NOT WORK:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="300" bgcolor="#252525">&nbsp;
    </td>
    <td width="300" bgcolor="#454545">&nbsp;
    </td>
  </tr>
</table>

Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="600" colspan="2" bgcolor="#353535">&nbsp;
    </td>
  </tr>
</table>

Not a full tutorial, but I hope that helps steer you in the right direction in the future.

Here is the code you are after:

<table width="900" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="57" height="43" valign="top" rowspan="2">
      <img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
    </td>
  </tr>
  <tr>
    <td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.

Increase max_execution_time in PHP?

Is very easy, this work for me:

PHP:

set_time_limit(300); // Time in seconds, max_execution_time

Here is the PHP documentation

Encrypt Password in Configuration Files?

I think that the best approach is to ensure that your config file (containing your password) is only accessible to a specific user account. For example, you might have an application specific user appuser to which only trusted people have the password (and to which they su to).

That way, there's no annoying cryptography overhead and you still have a password which is secure.

EDIT: I am assuming that you are not exporting your application configuration outside of a trusted environment (which I'm not sure would make any sense, given the question)

Is it possible to have multiple statements in a python lambda expression?

Let me present to you a glorious but terrifying hack:

import types

def _obj():
  return lambda: None

def LET(bindings, body, env=None):
  '''Introduce local bindings.
  ex: LET(('a', 1,
           'b', 2),
          lambda o: [o.a, o.b])
  gives: [1, 2]

  Bindings down the chain can depend on
  the ones above them through a lambda.
  ex: LET(('a', 1,
           'b', lambda o: o.a + 1),
          lambda o: o.b)
  gives: 2
  '''
  if len(bindings) == 0:
    return body(env)

  env = env or _obj()
  k, v = bindings[:2]
  if isinstance(v, types.FunctionType):
    v = v(env)

  setattr(env, k, v)
  return LET(bindings[2:], body, env)

You can now use this LET form as such:

map(lambda x: LET(('_', x.sort()),
                  lambda _: x[1]),
    lst)

which gives: [345, 465, 333]

What is the python keyword "with" used for?

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with with using.

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

Batch script: how to check for admin rights

In the batch script Elevate.cmd (see this link), which I have written to get admin rights, I have done it the following way:

:checkPrivileges
  NET FILE 1>NUL 2>NUL
  if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

This is tested for Windows 7, 8, 8.1, 10 and even Windows XP and does not need any resource such as a special directory, file or registry key.

List method to delete last element in list as well as all elements

To delete the last element of the lists, you could use:

def deleteLast(self):
    if self.Ans:
        del self.Ans[-1]
    if self.masses:
        del self.masses[-1]

How to Generate Unique Public and Private Key via RSA

When you use a code like this:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   // Do something with the key...
   // Encrypt, export, etc.
}

.NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET

This means:

  1. Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.

  2. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).

To resolve these issues:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   try
   {
      // Do something with the key...
      // Encrypt, export, etc.
   }
   finally
   {
      rsa.PersistKeyInCsp = false;
   }
}

ALWAYS

How do you scroll up/down on the console of a Linux VM

Shift+Fn+ UP or DOWN on a Macbook will allow you to scroll.

PostgreSQL delete with inner join

DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

or

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

Using a dictionary to count the items in a list

L = ['apple','red','apple','red','red','pear']
d = {}
[d.__setitem__(item,1+d.get(item,0)) for item in L]
print d 

Gives {'pear': 1, 'apple': 2, 'red': 3}

How do you create nested dict in Python?

For arbitrary levels of nestedness:

In [2]: def nested_dict():
   ...:     return collections.defaultdict(nested_dict)
   ...:

In [3]: a = nested_dict()

In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})

In [5]: a['a']['b']['c'] = 1

In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
            {'a': defaultdict(<function __main__.nested_dict>,
                         {'b': defaultdict(<function __main__.nested_dict>,
                                      {'c': 1})})})

Gradle: How to Display Test Results in the Console in Real Time?

You can add a Groovy closure inside your build.gradle file that does the logging for you:

test {
    afterTest { desc, result -> 
        logger.quiet "Executing test ${desc.name} [${desc.className}] with result: ${result.resultType}"
    }
}

On your console it then reads like this:

:compileJava UP-TO-DATE
:compileGroovy
:processResources
:classes
:jar
:assemble
:compileTestJava
:compileTestGroovy
:processTestResources
:testClasses
:test
Executing test maturesShouldBeCharged11DollarsForDefaultMovie [movietickets.MovieTicketsTests] with result: SUCCESS
Executing test studentsShouldBeCharged8DollarsForDefaultMovie [movietickets.MovieTicketsTests] with result: SUCCESS
Executing test seniorsShouldBeCharged6DollarsForDefaultMovie [movietickets.MovieTicketsTests] with result: SUCCESS
Executing test childrenShouldBeCharged5DollarsAnd50CentForDefaultMovie [movietickets.MovieTicketsTests] with result: SUCCESS
:check
:build

Since version 1.1 Gradle supports much more options to log test output. With those options at hand you can achieve a similar output with the following configuration:

test {
    testLogging {
        events "passed", "skipped", "failed"
    }
}

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

your .key file contains illegal characters. you can check .key file like this:

# file server.key

output "server.key: UTF-8 Unicode (with BOM) text" means it is a plain text, not a key file. The correct output should be "server.key: PEM RSA private key".

use below command to remove illegal characters:

# tail -c +4 server.key > new_server.key

The new_server.key should be correct.

For more detail, you can click here, thanks for the post.

How do I get length of list of lists in Java?

import java.util.ArrayList;

public class TestClass {

public static void main(String[] args) {

    ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
    ArrayList<String> List_1 = new ArrayList<String>();
    List_1.add("1");
    List_1.add("2");
    listOLists.add(List_1);

    ArrayList<String> List_2 = new ArrayList<String>();
    List_2.add("4");
    List_2.add("5");
    List_2.add("10");
    List_2.add("11");
    listOLists.add(List_2);
    for (int i = 0; i < listOLists.size(); i++) {
        System.out.print("list " + i + " :");
        for (int j = 0; j < listOLists.get(i).size(); j++) {
            System.out.print(listOLists.get(i).get(j) + " ;");
        }
        System.out.println();
    }

}

}

I hope this solution gives a better picture of list if lists

CSS – why doesn’t percentage height work?

Another option is to add style to div

<div style="position: absolute; height:somePercentage%; overflow:auto(or other overflow value)">
 //to be scrolled 
</div>

And it means that an element is positioned relative to the nearest positioned ancestor.

Show/hide div if checkbox selected

<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox

<div id="div1" style="display:none;">NOTICE</div>

  <script type="text/javascript">
<!--
   function showMe (box) {
    var chboxs = document.getElementById("div1").style.display;
    var vis = "none";
        if(chboxs=="none"){
         vis = "block"; }
        if(chboxs=="block"){
         vis = "none"; }
    document.getElementById(box).style.display = vis;
}
  //-->
</script>

Bootstrap carousel multiple frames at once

This is a working twitter bootstrap 3.

Here is the javascript:

$('#myCarousel').carousel({
    interval: 10000
})

$('.carousel .item').each(function(){
    var next = $(this).next();

    if (!next.length) {
        next = $(this).siblings(':first');
    }

    next.children(':first-child').clone().appendTo($(this));

    if (next.next().length>0) {
        next.next().children(':first-child').clone().appendTo($(this));
    }
    else {
        $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
    }
});

And the css:

.carousel-inner .active.left  { left: -33%;             }
.carousel-inner .active.right { left: 33%;              }
.carousel-inner .next         { left: 33%               }
.carousel-inner .prev         { left: -33%              }
.carousel-control.left        { background-image: none; }
.carousel-control.right       { background-image: none; }
.carousel-inner .item         { background: white;      }

You can see it in action at this Jsfiddle

The reason i added this answer because the other ones don't work entirely. I found 2 bugs inside them, one of them was that the left arrow generated a strange effect and the other was about the text getting bold in some situations witch can be resolved by setting the background color so the bottom item wont be visible while the transition effect.

How do I concatenate a boolean to a string in Python?

answer = True
myvar = "the answer is " + str(answer)

or

myvar = "the answer is %s" % answer

How to delete Tkinter widgets from a window?

You can use forget method on the widget

from tkinter import *

root = Tk()

b = Button(root, text="Delete me", command=b.forget)
b.pack()

b['command'] = b.forget

root.mainloop()

Resize image proportionally with CSS?

Try

transform: scale(0.5, 0.5);
-ms-transform: scale(0.5, 0.5);
-webkit-transform: scale(0.5, 0.5);

How to return a part of an array in Ruby?

I like ranges for this:

def first_half(list)
  list[0...(list.length / 2)]
end

def last_half(list)
  list[(list.length / 2)..list.length]
end

However, be very careful about whether the endpoint is included in your range. This becomes critical on an odd-length list where you need to choose where you're going to break the middle. Otherwise you'll end up double-counting the middle element.

The above example will consistently put the middle element in the last half.

Can I invoke an instance method on a Ruby module without including it?

If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as

module Mods
  def self.foo
     puts "Mods.foo(self)"
  end
end

The module_function approach below will avoid breaking any classes which include all of Mods.

module Mods
  def foo
    puts "Mods.foo"
  end
end

class Includer
  include Mods
end

Includer.new.foo

Mods.module_eval do
  module_function(:foo)
  public :foo
end

Includer.new.foo # this would break without public :foo above

class Thing
  def bar
    Mods.foo
  end
end

Thing.new.bar  

However, I'm curious why a set of unrelated functions are all contained within the same module in the first place?

Edited to show that includes still work if public :foo is called after module_function :foo

VB.NET: Clear DataGridView

I had the same problem on gridview content clearing. The datasource i used was a datatable having no columns, and i added columns and rows programmatically to datatable. Then bind to datagridview. I tried the code related with gridview like gridView.Rows.Clear(), gridView.DataSource = Nothing

but it didn't work for me. Then try the below code related with datatable before binding it to datagridview each time.

  dtStore.Rows.Clear()
  dtStore.Columns.Clear()
  gridView.DataSource = dtStore

And is working fine, no replication in DataGridView

What are the different NameID format used for?

Refer to Section 8.3 of this SAML core pdf of oasis SAML specification.

SP and IdP usually communicate each other about a subject. That subject should be identified through a NAME-IDentifier , which should be in some format so that It is easy for the other party to identify it based on the Format.

All these

1.urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified [default]

2.urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress

3.urn:oasis:names:tc:SAML:2.0:nameid-format:persistent

4.urn:oasis:names:tc:SAML:2.0:nameid-format:transient

are format for the Name Identifiers.

The name format for a transient ID in SAML 1 is urn:mace:shibboleth:1.0:nameIdentifier and in SAML 2 is urn:oasis:names:tc:SAML:2.0:nameid-format:transient

Transient is for [section 8.3.8 of SAML Core]

Indicates that the content of the element is an identifier with transient semantics and SHOULD be treated as an opaque and temporary value by the relying party.

Unspecified can be used and it purely depends on the entities implementation on their own wish.

Reading HTML content from a UIWebView

if you want to extract the contents of an already-loaded UIWebView, -stringByEvaluatingJavaScriptFromString. For example:

NSString  *html = [webView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];

Hashmap with Streams in Java 8 Streams to collect value of Map

What you need to do is create a Stream out of the Map's .entrySet():

// Map<K, V> --> Set<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
map.entrySet().stream()

From the on, you can .filter() over these entries. For instance:

// Stream<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
.filter(entry -> entry.getKey() == 1)

And to obtain the values from it you .map():

// Stream<Map.Entry<K, V>> --> Stream<V>
.map(Map.Entry::getValue)

Finally, you need to collect into a List:

// Stream<V> --> List<V>
.collect(Collectors.toList())

If you have only one entry, use this instead (NOTE: this code assumes that there is a value; otherwise, use .orElse(); see the javadoc of Optional for more details):

// Stream<V> --> Optional<V> --> V
.findFirst().get()

Django: List field in model?

With my current reputation I have no ability to comment, so I choose answer referencing comments for sample code in reply by Prashant Gaur (thanks, Gaur - this was helpful!) - his sample is for python2, since python3 has no

unicode
method.

The replacement below for function

get_prep_value(self, value):
should work with Django running with python3 (I'll use this code soon - yet not tested). Note, though, that I'm passing
encoding='utf-8', errors='ignore'
parameters to
decode()
and
unicode() methods
. Encoding should match your Django settings.py configuration and passing
errors='ignore'
is optional (and may result in silent data loss instead of exception whith misconfigured django in rare cases).

import sys

...

    def get_prep_value(self, value):
        if value is None:
            return value
        if sys.version_info[0] >= 3:
            if isinstance(out_data, type(b'')):
                return value.decode(encoding='utf-8', errors='ignore')
        else:
            if isinstance(out_data, type(b'')):
                return unicode(value, encoding='utf-8', errors='ignore')
        return str(value)
...


OS specific instructions in CMAKE: How to?

Try that:

if(WIN32)
    set(ADDITIONAL_LIBRARIES wsock32)
else()
    set(ADDITIONAL_LIBRARIES "")
endif()

target_link_libraries(${PROJECT_NAME} bioutils ${ADDITIONAL_LIBRARIES})

You can find other useful variables here.

Want to move a particular div to right

You can use float on that particular div, e.g.

<div style="float:right;">

Float the div you want more space to have to the left as well:

<div style="float:left;">

If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

<div style="position:absolute; left:-500px; top:30px;"> 

etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

How to add a border to a widget in Flutter?

Here, as the Text widget does not have a property that allows us to define a border, we should wrap it with a widget that allows us to define a border. There are several solutions.
But the best solution is the use of BoxDecoration in the Container widget.

Why choose to use BoxDecoration ?
Because BoxDecoration offers more customization like the possibility to define :
First, the border and also define:

  • border Color
  • border width
  • border radius
  • shape
  • and more ...

An example :

   Container(
     child:Text(' Hello Word '),
     decoration: BoxDecoration(
          color: Colors.yellow,
          border: Border.all(
                color: Colors.red ,
                width: 2.0 ,
              ),
          borderRadius: BorderRadius.circular(15),
            ),
          ),

Output :

enter image description here

numpy: most efficient frequency counts for unique values in an array

Most of simple problems get complicated because simple functionality like order() in R that gives a statistical result in both and descending order is missing in various python libraries. But if we devise our thinking that all such statistical ordering and parameters in python are easily found in pandas, we can can result sooner than looking in 100 different places. Also, development of R and pandas go hand-in-hand because they were created for same purpose. To solve this problem I use following code that gets me by anywhere:

unique, counts = np.unique(x, return_counts=True)
d = {'unique':unique, 'counts':count}  # pass the list to a dictionary
df = pd.DataFrame(d) #dictionary object can be easily passed to make a dataframe
df.sort_values(by = 'count', ascending=False, inplace = True)
df = df.reset_index(drop=True) #optional only if you want to use it further

How do I view executed queries within SQL Server Management Studio?

More clear query, targeting Studio sql queries is :

SELECT text  FROM sys.dm_exec_sessions es
  INNER JOIN sys.dm_exec_connections ec
      ON es.session_id = ec.session_id
  CROSS APPLY sys.dm_exec_sql_text(ec.most_recent_sql_handle) 
  where program_name like '%Query'

How to count total lines changed by a specific author in a Git repository?

git-fame

https://github.com/oleander/git-fame-rb

This is a nice tool to get the count for all authors at once, including commit and modified files count:

sudo apt-get install ruby-dev
sudo gem install git_fame
cd /path/to/gitdir && git fame

There is also Python version at https://github.com/casperdcl/git-fame (mentioned by @fracz):

sudo apt-get install python-pip python-dev build-essential 
pip install --user git-fame
cd /path/to/gitdir && git fame

Sample output:

Total number of files: 2,053
Total number of lines: 63,132
Total number of commits: 4,330

+------------------------+--------+---------+-------+--------------------+
| name                   | loc    | commits | files | percent            |
+------------------------+--------+---------+-------+--------------------+
| Johan Sørensen         | 22,272 | 1,814   | 414   | 35.3 / 41.9 / 20.2 |
| Marius Mathiesen       | 10,387 | 502     | 229   | 16.5 / 11.6 / 11.2 |
| Jesper Josefsson       | 9,689  | 519     | 191   | 15.3 / 12.0 / 9.3  |
| Ole Martin Kristiansen | 6,632  | 24      | 60    | 10.5 / 0.6 / 2.9   |
| Linus Oleander         | 5,769  | 705     | 277   | 9.1 / 16.3 / 13.5  |
| Fabio Akita            | 2,122  | 24      | 60    | 3.4 / 0.6 / 2.9    |
| August Lilleaas        | 1,572  | 123     | 63    | 2.5 / 2.8 / 3.1    |
| David A. Cuadrado      | 731    | 111     | 35    | 1.2 / 2.6 / 1.7    |
| Jonas Ängeslevä        | 705    | 148     | 51    | 1.1 / 3.4 / 2.5    |
| Diego Algorta          | 650    | 6       | 5     | 1.0 / 0.1 / 0.2    |
| Arash Rouhani          | 629    | 95      | 31    | 1.0 / 2.2 / 1.5    |
| Sofia Larsson          | 595    | 70      | 77    | 0.9 / 1.6 / 3.8    |
| Tor Arne Vestbø        | 527    | 51      | 97    | 0.8 / 1.2 / 4.7    |
| spontus                | 339    | 18      | 42    | 0.5 / 0.4 / 2.0    |
| Pontus                 | 225    | 49      | 34    | 0.4 / 1.1 / 1.7    |
+------------------------+--------+---------+-------+--------------------+

But be warned: as mentioned by Jared in the comment, doing it on a very large repository will take hours. Not sure if that could be improved though, considering that it must process so much Git data.

Difference between spring @Controller and @RestController annotation

Instead of using @Controller and @ResponseBody, @RestController let's you expose Rest APIs in Spring 4.0 and above.

Validate phone number using angular js

Try this:

<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
    <div class="form-group" ng-class="{'has-error': registration.phone.$error.number}">
        <label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
        <div class="col-sm-9">
            <input type="number" 
                   class="form-control" 
                   ng-minlength="10" 
                   ng-maxlength="10"  
                   id="inputPhone" 
                   name="phone" 
                   placeholder="Phone" 
                   ng-model="user.phone"
                   ng-required="true">
            <span class="help-block" 
                  ng-show="registration.phone.$error.required || 
                           registration.phone.$error.number">
                           Valid phone number is required
            </span>
            <span class="help-block" 
                  ng-show="((registration.phone.$error.minlength ||
                           registration.phone.$error.maxlength) && 
                           registration.phone.$dirty) ">
                           phone number should be 10 digits
            </span>

How can I make a "color map" plot in matlab?

I also suggest using contourf(Z). For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.

So in my case, I prefer to use jucestain's answer. The default shading faceted of pcolor() is more suitable. However, pcolor() does not use the last row and column of the plotted matrix. For this, I used the padarray() function:

pcolor(padarray(Z,[1 1],0,'post'))

Sorry if that is not really related to the original post

Creating an index on a table variable

If Table variable has large data, then instead of table variable(@table) create temp table (#table).table variable doesn't allow to create index after insert.

 CREATE TABLE #Table(C1 int,       
  C2 NVarchar(100) , C3 varchar(100)
  UNIQUE CLUSTERED (c1) 
 ); 
  1. Create table with unique clustered index

  2. Insert data into Temp "#Table" table

  3. Create non clustered indexes.

     CREATE NONCLUSTERED INDEX IX1  ON #Table (C2,C3);
    

Parameter "stratify" from method "train_test_split" (scikit Learn)

Try running this code, it "just works":

from sklearn import cross_validation, datasets 

iris = datasets.load_iris()

X = iris.data[:,:2]
y = iris.target

x_train, x_test, y_train, y_test = cross_validation.train_test_split(X,y,train_size=.8, stratify=y)

y_test

array([0, 0, 0, 0, 2, 2, 1, 0, 1, 2, 2, 0, 0, 1, 0, 1, 1, 2, 1, 2, 0, 2, 2,
       1, 2, 1, 1, 0, 2, 1])

Bulk insert with SQLAlchemy ORM

All Roads Lead to Rome, but some of them crosses mountains, requires ferries but if you want to get there quickly just take the motorway.


In this case the motorway is to use the execute_batch() feature of psycopg2. The documentation says it the best:

The current implementation of executemany() is (using an extremely charitable understatement) not particularly performing. These functions can be used to speed up the repeated execution of a statement against a set of parameters. By reducing the number of server roundtrips the performance can be orders of magnitude better than using executemany().

In my own test execute_batch() is approximately twice as fast as executemany(), and gives the option to configure the page_size for further tweaking (if you want to squeeze the last 2-3% of performance out of the driver).

The same feature can easily be enabled if you are using SQLAlchemy by setting use_batch_mode=True as a parameter when you instantiate the engine with create_engine()

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

Find timestamp from DateTime:

private long ConvertToTimestamp(DateTime value)
{
    TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
    DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
    TimeZone localZone = TimeZone.CurrentTimeZone;
    System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
    NyTime = NyTime.AddHours(-1);
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    TimeSpan span = (NyTime - epoch);
    return (long)Convert.ToDouble(span.TotalSeconds);
}

Including a groovy script in another groovy

For late-comers, it appears that groovy now support the :load file-path command which simply redirects input from the given file, so it is now trivial to include library scripts.

It works as input to the groovysh & as a line in a loaded file:
groovy:000> :load file1.groovy

file1.groovy can contain:
:load path/to/another/file invoke_fn_from_file();

Position last flex item at the end of container

This flexbox principle also works horizontally

During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Setting an automatic left margin for the Last Item will do the work.

.last-item {
  margin-left: auto;
}

Code Example:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  width: 400px;_x000D_
  outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  margin: 5px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p class="last-item"></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Codepen Snippet

This can be very useful for Desktop Footers.

As Envato did here with the company logo.

Codepen Snippet

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.

  <configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <requestLimits>
               <headerLimits>
                  <add header="Content-type" sizeLimit="100" />
               </headerLimits>
            </requestLimits>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>

Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits

How to create a printable Twitter-Bootstrap page

In case someone is looking for a solution for Bootstrap v2.X.X here. I am leaving the solution I was using. This is not fully tested on all browsers however it could be a good start.

1) make sure the media attribute of bootstrap-responsive.css is screen.

<link href="/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen" />

2) create a print.css and make sure its media attribute print

<link href="/css/print.css" rel="stylesheet" media="print" />

3) inside print.css, add the "width" of your website in html & body

html, 
body {
    width: 1200px !important;
}

4.) reproduce the necessary media query classes in print.css because they were inside bootstrap-responsive.css and we have disabled it when printing.

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

Here is full version of print.css:

html, 
body {
    width: 1200px !important;
}

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

How to concatenate strings with padding in sqlite

The || operator is "concatenate" - it joins together the two strings of its operands.

From http://www.sqlite.org/lang_expr.html

For padding, the seemingly-cheater way I've used is to start with your target string, say '0000', concatenate '0000423', then substr(result, -4, 4) for '0423'.

Update: Looks like there is no native implementation of "lpad" or "rpad" in SQLite, but you can follow along (basically what I proposed) here: http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/

-- the statement below is almost the same as
-- select lpad(mycolumn,'0',10) from mytable

select substr('0000000000' || mycolumn, -10, 10) from mytable

-- the statement below is almost the same as
-- select rpad(mycolumn,'0',10) from mytable

select substr(mycolumn || '0000000000', 1, 10) from mytable

Here's how it looks:

SELECT col1 || '-' || substr('00'||col2, -2, 2) || '-' || substr('0000'||col3, -4, 4)

it yields

"A-01-0001"
"A-01-0002"
"A-12-0002"
"C-13-0002"
"B-11-0002"

Error handling in AngularJS http get then construct

You need to add an additional parameter:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })

How to use multiple databases in Laravel

Laravel has inbuilt support for multiple database systems, you need to provide connection details in config/database.php file

return [
    'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
'mysqlOne' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST_ONE', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_ONE', 'forge'),
            'username' => env('DB_USERNAME_ONE', 'forge'),
            'password' => env('DB_PASSWORD_ONE', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
];

Once you have this you can create two base model class for each connection and define the connection name in those models

//BaseModel.php
protected $connection = 'mysql';

//BaseModelOne.php
protected $connection = 'mysqlOne';

You can extend these models to create more models for tables in each DB.

JQuery ajax call default timeout value

As an aside, when trying to diagnose a similar bug I realised that jquery's ajax error callback returns a status of "timeout" if it failed due to a timeout.

Here's an example:

$.ajax({
    url: "/ajax_json_echo/",
    timeout: 500,
    error: function(jqXHR, textStatus, errorThrown) {
        alert(textStatus); // this will be "timeout"
    }
});

Here it is on jsfiddle.

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while(str.at(0) == ' ') { str.erase(0, 1);}
    while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
    return str ;
    } 
}

How to easily get network path to the file you are working on?

Here's how to get the filepath of the file in Excel 2010.

1) Right click on the Ribbon.
2) Click on "Customize the Ribbon"
3) On the right hand side, click "New Group." This will add a new tab to the Ribbon. If you want to, click on the "Rename" button the right side and name your tab. For example, I named the tab "Doc Path." This step is optional
4) Under "Choose Commands From" on the left hand side, choose "Commands Not in the Ribbon."
5) Select "Document Location" and "Add" it to your newly created group.
6) The filepath should now appear under the newly created tab on the ribbon.

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

The above answers are incorrect in that most over-ride the 'is this connection HTTPS' test to allow serving the pages over http irrespective of connection security.

The secure answer using an error-page on an NGINX specific http 4xx error code to redirect the client to retry the same request to https. (as outlined here https://serverfault.com/questions/338700/redirect-http-mydomain-com12345-to-https-mydomain-com12345-in-nginx )

The OP should use:

server {
  listen        12345;
  server_name   php.myadmin.com;

  root         /var/www/php;

  ssl           on;

  # If they come here using HTTP, bounce them to the correct scheme
  error_page 497 https://$server_name:$server_port$request_uri;

  [....]
}

How to obfuscate Python code effectively?

You can use the base64 module to encode strings to stop shoulder surfing, but it's not going to stop someone finding your code if they have access to your files.

You can then use the compile() function and the eval() function to execute your code once you've decoded it.

>>> import base64
>>> mycode = "print 'Hello World!'"
>>> secret = base64.b64encode(mycode)
>>> secret
'cHJpbnQgJ2hlbGxvIFdvcmxkICEn'
>>> mydecode = base64.b64decode(secret)
>>> eval(compile(mydecode,'<string>','exec'))
Hello World!

So if you have 30 lines of code you'll probably want to encrypt it doing something like this:

>>> f = open('myscript.py')
>>> encoded = base64.b64encode(f.read())

You'd then need to write a second script that does the compile() and eval() which would probably include the encoded script as a string literal encased in triple quotes. So it would look something like this:

import base64
myscript = """IyBUaGlzIGlzIGEgc2FtcGxlIFB5d
              GhvbiBzY3JpcHQKcHJpbnQgIkhlbG
              xvIiwKcHJpbnQgIldvcmxkISIK"""
eval(compile(base64.b64decode(myscript),'<string>','exec'))

Performing Breadth First Search recursively

If you use an array to back the binary tree, you can determine the next node algebraically. if i is a node, then its children can be found at 2i + 1 (for the left node) and 2i + 2 (for the right node). A node's next neighbor is given by i + 1, unless i is a power of 2

Here's pseudocode for a very naive implementation of breadth first search on an array backed binary search tree. This assumes a fixed size array and therefore a fixed depth tree. It will look at parentless nodes, and could create an unmanageably large stack.

bintree-bfs(bintree, elt, i)
    if (i == LENGTH)
        return false

    else if (bintree[i] == elt)
        return true

    else 
        return bintree-bfs(bintree, elt, i+1)        

Regex Explanation ^.*$

  • ^ matches position just before the first character of the string
  • $ matches position just after the last character of the string
  • . matches a single character. Does not matter what character it is, except newline
  • * matches preceding match zero or more times

So, ^.*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.

Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones and Matthew's last name is Jones. The pattern ^Matt.*Jones$ will match Matthew's last name is Jones. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.

Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.

How can I run an EXE program from a Windows Service using C#?

you can use from windows task scheduler for this purpose, there are many libraries like TaskScheduler that help you.

for example consider we want to scheduling a task that will executes once five seconds later:

using (var ts = new TaskService())
        {

            var t = ts.Execute("notepad.exe")
                .Once()
                .Starting(DateTime.Now.AddSeconds(5))
                .AsTask("myTask");

        }

notepad.exe will be executed five seconds later.

for details and more information please go to wiki

if you know which class and method in that assembly you need, you can invoke it yourself like this:

        Assembly assembly = Assembly.LoadFrom("yourApp.exe");
        Type[] types = assembly.GetTypes();
        foreach (Type t in types)
        {
            if (t.Name == "YourClass")
            {
                MethodInfo method = t.GetMethod("YourMethod",
                BindingFlags.Public | BindingFlags.Instance);
                if (method != null)
                {
                    ParameterInfo[] parameters = method.GetParameters();
                    object classInstance = Activator.CreateInstance(t, null);

                    var result = method.Invoke(classInstance, parameters.Length == 0 ? null : parameters);
                    
                    break;
                }
            }
                         
        }
    

How to get the top position of an element?

Try: $('#mytable').attr('offsetTop')

Defining Z order of views of RelativeLayout in Android

Please note, buttons and other elements in API 21 and greater have a high elevation, and therefore ignore the xml order of elements regardless of parent layout. Took me a while to figure that one out.

file_get_contents() how to fix error "Failed to open stream", "No such file"

just to extend Shankars and amals answers with simple unit testing:

/**
 *
 * workaround HTTPS problems with file_get_contents
 *
 * @param $url
 * @return boolean|string
 */
function curl_get_contents($url)
{
    $data = FALSE;
    if (filter_var($url, FILTER_VALIDATE_URL))
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $data = curl_exec($ch);
        curl_close($ch);
    }
    return $data;
}
// then in the unit tests:
public function test_curl_get_contents()
{
    $this->assertFalse(curl_get_contents(NULL));
    $this->assertFalse(curl_get_contents('foo'));
    $this->assertTrue(strlen(curl_get_contents('https://www.google.com')) > 0);
}

Ruby value of a hash key?

As an addition to e.g. @Intrepidd s answer, in certain situations you want to use fetch instead of []. For fetch not to throw an exception when the key is not found, pass it a default value.

puts "ok" if hash.fetch('key', nil) == 'X'

Reference: https://docs.ruby-lang.org/en/2.3.0/Hash.html .

ToList()-- does it create a new list?

Yes, it creates a new list. This is by design.

The list will contain the same results as the original enumerable sequence, but materialized into a persistent (in-memory) collection. This allows you to consume the results multiple times without incurring the cost of recomputing the sequence.

The beauty of LINQ sequences is that they are composable. Often, the IEnumerable<T> you get is the result of combining multiple filtering, ordering, and/or projection operations. Extension methods like ToList() and ToArray() allow you to convert the computed sequence into a standard collection.

How to access your website through LAN in ASP.NET

You may also need to enable the World Wide Web Service inbound firewall rule.

On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules

Find World Wide Web Services (HTTP Traffic-In) in the list and select to enable the rule. Change is pretty much immediate.

How can I use a C++ library from node.js?

There is a fresh answer to that question now. SWIG, as of version 3.0 seems to provide javascript interface generators for Node.js, Webkit and v8.

I've been using SWIG extensively for Java and Python for a while, and once you understand how SWIG works, there is almost no effort(compared to ffi or the equivalent in the target language) needed for interfacing C++ code to the languages that SWIG supports.

As a small example, say you have a library with the header myclass.h:

#include<iostream>

class MyClass {
        int myNumber;
public:
        MyClass(int number): myNumber(number){}
        void sayHello() {
                std::cout << "Hello, my number is:" 
                << myNumber <<std::endl;
        }
};

In order to use this class in node, you simply write the following SWIG interface file (mylib.i):

%module "mylib"
%{
#include "myclass.h"
%}
%include "myclass.h"

Create the binding file binding.gyp:

{
  "targets": [
    {
      "target_name": "mylib",
      "sources": [ "mylib_wrap.cxx" ]
    }
  ]
}

Run the following commands:

swig -c++ -javascript -node mylib.i
node-gyp build

Now, running node from the same folder, you can do:

> var mylib = require("./build/Release/mylib")
> var c = new mylib.MyClass(5)
> c.sayHello()
Hello, my number is:5

Even though we needed to write 2 interface files for such a small example, note how we didn't have to mention the MyClass constructor nor the sayHello method anywhere, SWIG discovers these things, and automatically generates natural interfaces.

What's the difference between an element and a node in XML?

A node can be a number of different kinds of things: some text, a comment, an element, an entity, etc. An element is a particular kind of node.

Remove a folder from git tracking

This works for me:

git rm -r --cached --ignore-unmatch folder_name

--ignore-unmatch is important here, without that option git will exit with error on the first file not in the index.

Reflection generic get field value

I post my solution in Kotlin, but it can work with java objects as well. I create a function extension so any object can use this function.

fun Any.iterateOverComponents() {

val fields = this.javaClass.declaredFields

fields.forEachIndexed { i, field ->

    fields[i].isAccessible = true
    // get value of the fields
    val value = fields[i].get(this)

    // print result
    Log.w("Msg", "Value of Field "
            + fields[i].name
            + " is " + value)
}}

Take a look at this webpage: https://www.geeksforgeeks.org/field-get-method-in-java-with-examples/

Int or Number DataType for DataAnnotation validation attribute

Try this attribute :

public class NumericAttribute : ValidationAttribute, IClientValidatable {

    public override bool IsValid(object value) {
        return value.ToString().All(c => (c >= '0' && c <= '9') || c == '-' || c == ' ');
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),
            ValidationType = "numeric"
        };
        yield return rule;
    }
}

And also you must register the attribute in the validator plugin:

if($.validator){
     $.validator.unobtrusive.adapters.add(
        'numeric', [], function (options) {
            options.rules['numeric'] = options.params;
            options.messages['numeric'] = options.message;
        }
    );
}

ActionBar text color

This is not the recommended solution as I am going in android apis here but as my application requires to change the theme dynmically on conditions xml not possible here, So I need to do this. But This solution is working very nice.

Solution:--

 /**
 * 
 * @author Kailash Dabhi
 * @email [email protected]
 *
 */ 
 public static void setActionbarTextColor(Activity activity, int color) {
    Field mActionViewField;
    try {
        mActionViewField = activity.getActionBar().getClass()
                .getDeclaredField("mActionView");
        mActionViewField.setAccessible(true);
        Object mActionViewObj = mActionViewField.get(activity
                .getActionBar());

        Field mTitleViewField = mActionViewObj.getClass().getDeclaredField(
                "mTitleView");
        mTitleViewField.setAccessible(true);
        Object mTitleViewObj = mTitleViewField.get(mActionViewObj);

        TextView mActionBarTitle = (TextView) mTitleViewObj;
        mActionBarTitle.setTextColor(color);
        // Log.i("field", mActionViewObj.getClass().getName());
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }

}

jQuery trigger file input

I have it working (=tested) in IE8+, recent FF and chrome:

$('#uploadInput').focus().trigger('click');

The key is focusing before firing the click (otherwise chrome ignores it).

Note: you do NEED to have your input displayed and visible (as in, not display:none and not visibility:hidden). I suggest (as many other have before) to absolutely position the input and throw it off screen.

#uploadInput {
    position: absolute;
    left: -9999px;
}

What is __stdcall?

__stdcall is used to put the function arguments in the stack. After the completion of the function it automatically deallocates the memory. This is used for fixed arguments.

void __stdcall fnname ( int, int* )
{
    ...
}

int main()
{
    CreateThread ( NULL, 0, fnname, int, int*...... )
}

Here the fnname has args it directly push into the stack.

How to add a filter class in Spring Boot?

There are three ways to add your filter,

  1. Annotate your filter with one of the Spring stereotypes such as @Component
  2. Register a @Bean with Filter type in Spring @Configuration
  3. Register a @Bean with FilterRegistrationBean type in Spring @Configuration

Either #1 or #2 will do if you want your filter applies to all requests without customization, use #3 otherwise. You don't need to specify component scan for #1 to work as long as you place your filter class in the same or sub-package of your SpringApplication class. For #3, use along with #2 is only necessary when you want Spring to manage your filter class such as have it auto wired dependencies. It works just fine for me to new my filter which doesn't need any dependency autowiring/injection.

Although combining #2 and #3 works fine, I was surprised it doesn't end up with two filters applying twice. My guess is that Spring combines the two beans as one when it calls the same method to create both of them. In case you want to use #3 alone with authowiring, you can AutowireCapableBeanFactory. The following is an example,

private @Autowired AutowireCapableBeanFactory beanFactory;

    @Bean
    public FilterRegistrationBean myFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        Filter myFilter = new MyFilter();
        beanFactory.autowireBean(myFilter);
        registration.setFilter(myFilter);
        registration.addUrlPatterns("/myfilterpath/*");
        return registration;
    }

Make a UIButton programmatically in Swift

UIButton with constraints in iOS 9.1/Xcode 7.1.1/Swift 2.1:

import UIKit
import MapKit

class MapViewController: UIViewController {  

    override func loadView() {
        mapView = MKMapView()  //Create a view...
        view = mapView         //assign it to the ViewController's (inherited) view property.
                               //Equivalent to self.view = mapView

        myButton = UIButton(type: .RoundedRect)  //RoundedRect is an alias for System (tested by printing out their rawValue's)
        //myButton.frame = CGRect(x:50, y:500, width:70, height:50)  //Doesn't seem to be necessary when using constraints.
        myButton.setTitle("Current\nLocation", forState: .Normal)
        myButton.titleLabel?.lineBreakMode = .ByWordWrapping  //If newline in title, split title onto multiple lines
        myButton.titleLabel?.textAlignment = .Center
        myButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        myButton.layer.cornerRadius = 6   //For some reason, a button with type RoundedRect has square corners
        myButton.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5) //Make the color partially transparent
        //Attempt to add padding around text. Shrunk the frame when I tried it.  Negative values had no effect.
        //myButton.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
        myButton.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)  //Add padding around text.

        myButton.addTarget(self, action: "getCurrentLocation:", forControlEvents: .TouchUpInside)
        mapView.addSubview(myButton)

        //Button Constraints:
        myButton.translatesAutoresizingMaskIntoConstraints = false //***
        //bottomLayoutGuide(for tab bar) and topLayoutGuide(for status bar) are properties of the ViewController
        //To anchor above the tab bar on the bottom of the screen:
        let bottomButtonConstraint = myButton.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20) //Implied call of self.bottomLayoutGuide. Anchor 20 points **above** the top of the tab bar.
        //To anchor to the blue guide line that is inset from the left 
        //edge of the screen in InterfaceBuilder:
        let margins = view.layoutMarginsGuide  //Now the guide is a property of the View.
        let leadingButtonConstraint = myButton.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

        bottomButtonConstraint.active = true
        leadingButtonConstraint.active = true
    }


    func getCurrentLocation(sender: UIButton) {
        print("Current Location button clicked!")
    }

The button is anchored to the bottom left corner, above the tab bar.

Eclipse Problems View not showing Errors anymore

On Ganymede, check the configuration of the Problem view:

('Configure content') It can be set on 'any element in the same project' and you might currently select an element from the project.

Or it might be set on a working set, and this working set has been modified

Make sure that 'Match any configuration' is selected.

How do I delete everything in Redis?

redis-cli -h <host> -p <port> flushall

It will remove all data from client connected(with host and port)

How to make rounded percentages add up to 100%

I have implemented the method from Varun Vohra's answer here for both lists and dicts.

import math
import numbers
import operator
import itertools


def round_list_percentages(number_list):
    """
    Takes a list where all values are numbers that add up to 100,
    and rounds them off to integers while still retaining a sum of 100.

    A total value sum that rounds to 100.00 with two decimals is acceptable.
    This ensures that all input where the values are calculated with [fraction]/[total]
    and the sum of all fractions equal the total, should pass.
    """
    # Check input
    if not all(isinstance(i, numbers.Number) for i in number_list):
        raise ValueError('All values of the list must be a number')

    # Generate a key for each value
    key_generator = itertools.count()
    value_dict = {next(key_generator): value for value in number_list}
    return round_dictionary_percentages(value_dict).values()


def round_dictionary_percentages(dictionary):
    """
    Takes a dictionary where all values are numbers that add up to 100,
    and rounds them off to integers while still retaining a sum of 100.

    A total value sum that rounds to 100.00 with two decimals is acceptable.
    This ensures that all input where the values are calculated with [fraction]/[total]
    and the sum of all fractions equal the total, should pass.
    """
    # Check input
    # Only allow numbers
    if not all(isinstance(i, numbers.Number) for i in dictionary.values()):
        raise ValueError('All values of the dictionary must be a number')
    # Make sure the sum is close enough to 100
    # Round value_sum to 2 decimals to avoid floating point representation errors
    value_sum = round(sum(dictionary.values()), 2)
    if not value_sum == 100:
        raise ValueError('The sum of the values must be 100')

    # Initial floored results
    # Does not add up to 100, so we need to add something
    result = {key: int(math.floor(value)) for key, value in dictionary.items()}

    # Remainders for each key
    result_remainders = {key: value % 1 for key, value in dictionary.items()}
    # Keys sorted by remainder (biggest first)
    sorted_keys = [key for key, value in sorted(result_remainders.items(), key=operator.itemgetter(1), reverse=True)]

    # Otherwise add missing values up to 100
    # One cycle is enough, since flooring removes a max value of < 1 per item,
    # i.e. this loop should always break before going through the whole list
    for key in sorted_keys:
        if sum(result.values()) == 100:
            break
        result[key] += 1

    # Return
    return result

How do you tell if a checkbox is selected in Selenium for Java?

For the event where there are multiple check-boxes from which you'd like to select/deselect only a few, the following work with the Chrome Driver (somehow failed for IE Driver):

NOTE: My check-boxes didn't have an ID associated with them, which would be the best way to identify them according to the Documentation. Note the ! sign at the beginning of the statement.

if(!driver.findElement(By.xpath("//input[@type='checkbox' and @name='<name>']")).isSelected()) 
{
  driver.findElement(By.xpath("//input[@type='checkbox' and @name= '<name>']")).click();
}

How do I change the formatting of numbers on an axis with ggplot?

Another option is to format your axis tick labels with commas is by using the package scales, and add

 scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = comma)

to your ggplot statement.

If you don't want to load the package, use:

scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = scales::comma)

how to show progress bar(circle) in an activity having a listview before loading the listview with data

I used this one for list view loading may helpful.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp" >

<LinearLayout
    android:id="@+id/progressbar_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal" >

        <ProgressBar
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|center_horizontal"
            android:text="Loading data..." />
    </LinearLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#C0C0C0" />
</LinearLayout>

<ListView
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="1dip"
    android:visibility="gone" />

</RelativeLayout>

and my MainActivity class is,

public class MainActivity extends Activity {
ListView listView;
LinearLayout layout;
List<String> stringValues;
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listView);
    layout = (LinearLayout) findViewById(R.id.progressbar_view);

    stringValues = new ArrayList<String>();

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, stringValues);

    listView.setAdapter(adapter);
    new Task().execute();
}

class Task extends AsyncTask<String, Integer, Boolean> {
    @Override
    protected void onPreExecute() {
        layout.setVisibility(View.VISIBLE);
        listView.setVisibility(View.GONE);
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        layout.setVisibility(View.GONE);
        listView.setVisibility(View.VISIBLE);
        adapter.notifyDataSetChanged();
        super.onPostExecute(result);
    }

    @Override
    protected Boolean doInBackground(String... params) {
        stringValues.add("String 1");
        stringValues.add("String 2");
        stringValues.add("String 3");
        stringValues.add("String 4");
        stringValues.add("String 5");

        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

this activity display progress for 3sec then it will display listview, instead of adding data statically to stringValues list you can get data from server in doInBackground() and display it.

How to set different colors in HTML in one statement?

Use the span tag

<style>
    .redText
    {
        color:red;
    }
    .blackText
    {
        color:black;
        font-weight:bold;
    }
</style>

<span class="redText">My Name is:</span>&nbsp;<span class="blackText">Tintincute</span>

It's also a good idea to avoid inline styling. Use a custom CSS class instead.

How do I escape special characters in MySQL?

For testing how to insert the double quotes in MySQL using the terminal, you can use the following way:

TableName(Name,DString) - > Schema
insert into TableName values("Name","My QQDoubleQuotedStringQQ")

After inserting the value you can update the value in the database with double quotes or single quotes:

update table TableName replace(Dstring, "QQ", "\"")

How does the compilation/linking process work?

GCC compiles a C/C++ program into executable in 4 steps.

For example, gcc -o hello hello.c is carried out as follows:

1. Pre-processing

Preprocessing via the GNU C Preprocessor (cpp.exe), which includes the headers (#include) and expands the macros (#define).

cpp hello.c > hello.i

The resultant intermediate file "hello.i" contains the expanded source code.

2. Compilation

The compiler compiles the pre-processed source code into assembly code for a specific processor.

gcc -S hello.i

The -S option specifies to produce assembly code, instead of object code. The resultant assembly file is "hello.s".

3. Assembly

The assembler (as.exe) converts the assembly code into machine code in the object file "hello.o".

as -o hello.o hello.s

4. Linker

Finally, the linker (ld.exe) links the object code with the library code to produce an executable file "hello".

    ld -o hello hello.o ...libraries...

How to change the text of a label?

Try this:

$('[id$=lblVessel]').text("NewText");

The id$= will match the elements that end with that text, which is how ASP.NET auto-generates IDs. You can make it safer using span[id=$=lblVessel] but usually this isn't necessary.

Android ListView Text Color

if you didnot set your activity style it shows you black background .if you want to make changes such as white background, black text of listview then it is difficult process.

ADD android:theme="@style/AppTheme" in Android Manifest.

Test if something is not undefined in JavaScript

Just check if response[0] is undefined:

if(response[0] !== undefined) { ... }

If you still need to explicitly check the title, do so after the initial check:

if(response[0] !== undefined && response[0].title !== undefined){ ... }

Android TabLayout Android Design

_x000D_
_x000D_
<?xml version="1.0" encoding="utf-8"?>_x000D_
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
    xmlns:app="http://schemas.android.com/apk/res-auto"_x000D_
    xmlns:tools="http://schemas.android.com/tools"_x000D_
    android:id="@+id/main_content"_x000D_
    android:layout_width="match_parent"_x000D_
    android:layout_height="match_parent"_x000D_
    android:fitsSystemWindows="true"_x000D_
    tools:context=".ui.MainActivity"_x000D_
    >_x000D_
    <android.support.design.widget.AppBarLayout_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="wrap_content"_x000D_
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">_x000D_
_x000D_
        <android.support.v7.widget.Toolbar_x000D_
            android:id="@+id/toolbar"_x000D_
            android:layout_width="match_parent"_x000D_
            android:layout_height="wrap_content"_x000D_
            android:layout_alignParentTop="true"_x000D_
            android:background="?attr/colorPrimary"_x000D_
            android:elevation="6dp"_x000D_
            android:minHeight="?attr/actionBarSize"_x000D_
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"_x000D_
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />_x000D_
_x000D_
        <android.support.design.widget.TabLayout_x000D_
            android:id="@+id/tabs"_x000D_
            android:layout_width="match_parent"_x000D_
            android:layout_height="wrap_content"_x000D_
            app:tabMode="fixed"_x000D_
            app:tabGravity="fill"_x000D_
            >_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tabItem"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_1" />_x000D_
_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tabItem2"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_2" />_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tabItem3"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_3" />_x000D_
            <android.support.design.widget.TabItem_x000D_
                android:id="@+id/tItemab4"_x000D_
                android:layout_width="wrap_content"_x000D_
                android:layout_height="wrap_content"_x000D_
                android:text="@string/tab_text_4" />_x000D_
        </android.support.design.widget.TabLayout>_x000D_
    </android.support.design.widget.AppBarLayout>_x000D_
    <android.support.v4.view.ViewPager_x000D_
        android:id="@+id/container"_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="match_parent"_x000D_
        android:layout_below="@id/tabs"_x000D_
        app:layout_behavior="@string/appbar_scrolling_view_behavior"_x000D_
        tools:ignore="NotSibling"/>_x000D_
</android.support.constraint.ConstraintLayout>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<?xml version="1.0" encoding="utf-8"?>_x000D_
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
    xmlns:tools="http://schemas.android.com/tools"_x000D_
    android:id="@+id/activity_main"_x000D_
    android:layout_width="match_parent"_x000D_
    android:layout_height="match_parent"_x000D_
    tools:context=".ui.MainActivity">_x000D_
    <include layout="@layout/tabs"></include>_x000D_
    <LinearLayout_x000D_
        android:orientation="vertical"_x000D_
        android:layout_width="match_parent"_x000D_
        android:layout_height="match_parent"_x000D_
        android:layout_marginBottom="@dimen/activity_vertical_margin"_x000D_
        android:layout_marginLeft="@dimen/activity_horizontal_margin"_x000D_
        android:layout_marginRight="@dimen/activity_horizontal_margin"_x000D_
        android:layout_marginTop="80dp">_x000D_
        <FrameLayout android:id="@+id/tabContent"_x000D_
            android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp">_x000D_
        </FrameLayout>_x000D_
    </LinearLayout>_x000D_
</RelativeLayout>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
public class MainActivity extends  AppCompatActivity{_x000D_
_x000D_
  private Toolbar toolbar;_x000D_
    private TabLayout tabLayout;_x000D_
    private ViewPagerAdapter adapter;_x000D_
_x000D_
    private final static int[] tabIcons = {_x000D_
            R.drawable.ic_action_car,_x000D_
            android.R.drawable.ic_menu_mapmode,_x000D_
            android.R.drawable.ic_dialog_email,_x000D_
            R.drawable.ic_action_settings_x000D_
    };_x000D_
_x000D_
protected void onCreate(Bundle savedInstanceState) {_x000D_
        super.onCreate(savedInstanceState);_x000D_
        setContentView(R.layout.activity_main);_x000D_
        _x000D_
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);_x000D_
       setSupportActionBar(toolbar);_x000D_
_x000D_
        ViewPager viewPager = (ViewPager)         findViewById(R.id.container);_x000D_
        setupViewPager(viewPager);_x000D_
_x000D_
_x000D_
        tabLayout = (TabLayout) findViewById(R.id.tabs);_x000D_
        tabLayout.setupWithViewPager(viewPager);_x000D_
        setupTabIcons();_x000D_
_x000D_
        _x000D_
        }_x000D_
            private void setupTabIcons() {_x000D_
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);_x000D_
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);_x000D_
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);_x000D_
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);_x000D_
    }_x000D_
_x000D_
    private void setupViewPager(ViewPager viewPager) {_x000D_
        adapter = new ViewPagerAdapter(getSupportFragmentManager());_x000D_
        adapter.addFrag(new CarFragment());_x000D_
        adapter.addFrag(new LocationFragment());_x000D_
        adapter.addFrag(new MessageFragment());_x000D_
        adapter.addFrag(new SettingsFragment());_x000D_
        viewPager.setAdapter(adapter);_x000D_
    }_x000D_
    _x000D_
    class ViewPagerAdapter extends FragmentPagerAdapter {_x000D_
        private final List<Fragment> mFragmentList = new ArrayList<>();_x000D_
        ViewPagerAdapter(FragmentManager manager) {_x000D_
            super(manager);_x000D_
        }_x000D_
_x000D_
        @Override_x000D_
        public Fragment getItem(int position) {_x000D_
            return mFragmentList.get(position);_x000D_
        }_x000D_
_x000D_
        @Override_x000D_
        public int getCount() {_x000D_
            return mFragmentList.size();_x000D_
        }_x000D_
_x000D_
        void addFrag(Fragment fragment) {_x000D_
            mFragmentList.add(fragment);_x000D_
_x000D_
        }_x000D_
_x000D_
    }_x000D_
        }
_x000D_
_x000D_
_x000D_

TypeError: Cannot read property 'then' of undefined

TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.

If you are calling a Python service, the code will look like below:

this.updateTalentSupplier=function(supplierObj){
  var promise = $http({
    method: 'POST',
      url: bbConfig.BWS+'updateTalentSupplier/',
      data:supplierObj,
      withCredentials: false,
      contentType:'application/json',
      dataType:'json'
    });
    return promise; //Promise is returned 
}

We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.

redirect to current page in ASP.Net

Why Server.Transfer? Response.Redirect(Request.RawUrl) would get you what you need.

How to solve error: "Clock skew detected"?

I am going to answer my own question.

I added the following lines of code to my Makefile and it fixed the "clock skew" problem:

clean:  
    find . -type f | xargs touch
    rm -rf $(OBJS)

HTML5 Canvas: Zooming

Canvas zoom and pan

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<canvas id="myCanvas" width="" height=""_x000D_
style="border:1px solid #d3d3d3;">_x000D_
Your browser does not support the canvas element._x000D_
</canvas>_x000D_
_x000D_
<script>_x000D_
console.log("canvas")_x000D_
var ox=0,oy=0,px=0,py=0,scx=1,scy=1;_x000D_
var canvas = document.getElementById("myCanvas");_x000D_
canvas.onmousedown=(e)=>{px=e.x;py=e.y;canvas.onmousemove=(e)=>{ox-=(e.x-px);oy-=(e.y-py);px=e.x;py=e.y;} } _x000D_
_x000D_
canvas.onmouseup=()=>{canvas.onmousemove=null;}_x000D_
canvas.onwheel =(e)=>{let bfzx,bfzy,afzx,afzy;[bfzx,bfzy]=StoW(e.x,e.y);scx-=10*scx/e.deltaY;scy-=10*scy/e.deltaY;_x000D_
[afzx,afzy]=StoW(e.x,e.y);_x000D_
ox+=(bfzx-afzx);_x000D_
oy+=(bfzy-afzy);_x000D_
}_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
function draw(){_x000D_
window.requestAnimationFrame(draw);_x000D_
ctx.clearRect(0,0,canvas.width,canvas.height);_x000D_
for(let i=0;i<=100;i+=10){_x000D_
let sx=0,sy=i;_x000D_
let ex=100,ey=i;_x000D_
[sx,sy]=WtoS(sx,sy);_x000D_
[ex,ey]=WtoS(ex,ey);_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(sx, sy);_x000D_
ctx.lineTo(ex, ey);_x000D_
ctx.stroke();_x000D_
}_x000D_
for(let i=0;i<=100;i+=10){_x000D_
let sx=i,sy=0;_x000D_
let ex=i,ey=100;_x000D_
[sx,sy]=WtoS(sx,sy);_x000D_
[ex,ey]=WtoS(ex,ey);_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(sx, sy);_x000D_
ctx.lineTo(ex, ey);_x000D_
ctx.stroke();_x000D_
}_x000D_
}_x000D_
draw()_x000D_
function WtoS(wx,wy){_x000D_
let sx=(wx-ox)*scx;_x000D_
let sy=(wy-oy)*scy;_x000D_
return[sx,sy];_x000D_
}_x000D_
function StoW(sx,sy){_x000D_
let wx=sx/scx+ox;_x000D_
let wy=sy/scy+oy;_x000D_
return[wx,wy];_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Draw a line in a div

If the div has some content inside, this will be the best practice to have a line over or under the div and maintaining the content spacing with the div

.div_line_bottom{
 border-bottom: 1px solid #ff0000;
 padding-bottom:20px;
}

.div_line_top{
border-top: 1px solid #ff0000;
padding-top:20px;
}

What does auto do in margin:0 auto?

When you have specified a width on the object that you have applied margin: 0 auto to, the object will sit centrally within it's parent container.

Specifying auto as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first parameter 0 indicates that the top and bottom margins will both be set to 0.

margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;

Therefore, to give you an example, if the parent is 100px and the child is 50px, then the auto property will determine that there's 50px of free space to share between margin-left and margin-right:

var freeSpace = 100 - 50;
var equalShare = freeSpace / 2;

Which would give:

margin-left:25;
margin-right:25;

Have a look at this jsFiddle. You do not have to specify the parent width, only the width of the child object.

OnItemCLickListener not working in listview

If you want to use both the simple click and long click on list view items better way to implement that would be to use context menu for long click. Avoid using setItemLongClickListener especially if you have multiple row layouts for your listview.

Difference between acceptance test and functional test?

The difference is between testing the problem and the solution. Software is a solution to a problem, both can be tested.

The functional test confirms the software performs a function within the boundaries of how you've solved the problem. This is an integral part of developing software, comparable to the testing that is done on mass produced product before it leaves the factory. A functional test verifies that the product actually works as you (the developer) think it does.

Acceptance tests verify the product actually solves the problem it was made to solve. This can best be done by the user (customer), for instance performing his/her tasks that the software assists with. If the software passes this real world test, it's accepted to replace the previous solution. This acceptance test can sometimes only be done properly in production, especially if you have anonymous customers (e.g. a website). Thus a new feature will only be accepted after days or weeks of use.

Functional testing - test the product, verifying that it has the qualities you've designed or build (functions, speed, errors, consistency, etc.)

Acceptance testing - test the product in its context, this requires (simulation of) human interaction, test it has the desired effect on the original problem(s).

If condition inside of map() React

This one I found simple solutions:

row = myArray.map((cell, i) => {

    if (i == myArray.length - 1) {
      return <div> Test Data 1</div>;
    }
    return <div> Test Data 2</div>;
  });

C++ performance vs. Java/C#

I like Orion Adrian's answer, but there is another aspect to it.

The same question was posed decades ago about assembly language vs. "human" languages like FORTRAN. And part of the answer is similar.

Yes, a C++ program is capable of being faster than C# on any given (non-trivial?) algorithm, but the program in C# will often be as fast or faster than a "naive" implementation in C++, and an optimized version in C++ will take longer to develop, and might still beat the C# version by a very small margin. So, is it really worth it?

You'll have to answer that question on a one-by-one basis.

That said, I'm a long time fan of C++, and I think it's an incredibly expressive and powerful language -- sometimes underappreciated. But in many "real life" problems (to me personally, that means "the kind I get paid to solve"), C# will get the job done sooner and safer.

The biggest penalty you pay? Many .NET and Java programs are memory hogs. I have seen .NET and Java apps take "hundreds" of megabytes of memory, when C++ programs of similar complexity barely scratch the "tens" of MBs.

Zoom in on a point (using scale and translate)

Here's an approach I use for tighter control over how things are drawn

_x000D_
_x000D_
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var scale = 1;
var xO = 0;
var yO = 0;

draw();

function draw(){
    // Clear screen
    ctx.clearRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);

    // Original coordinates
    const xData = 50, yData = 50, wData = 100, hData = 100;
    
    // Transformed coordinates
    const x = xData * scale + xO,
     y = yData * scale + yO,
     w = wData * scale,
     h = hData * scale;

    // Draw transformed positions
    ctx.fillStyle = "black";
    ctx.fillRect(x,y,w,h);
}

canvas.onwheel = function (e){
    e.preventDefault();

    const r = canvas.getBoundingClientRect(),
      xNode =  e.pageX - r.left,
      yNode =  e.pageY - r.top;

    const newScale = scale * Math.exp(-Math.sign(e.deltaY) * 0.2),
      scaleFactor = newScale/scale;

    xO = xNode - scaleFactor * (xNode - xO);
    yO = yNode - scaleFactor * (yNode - yO);
    scale = newScale;

    draw();
}
_x000D_
<canvas id="canvas" width="600" height="200"></canvas>
_x000D_
_x000D_
_x000D_

AttributeError: Module Pip has no attribute 'main'

It appears that pip did a refactor and moved main to internal. There is a comprehensive discussion about it here: https://github.com/pypa/pip/issues/5240

A workaround for me was to change

import pip
pip.main(...)

to

from pip._internal import main
main(...)

I recommend reading through the discussion, I'm not sure this is the best approach, but it worked for my purposes.

Jinja2 template variable if None Object set a default value

You can simply add "default none" to your variable as the form below mentioned:

{{ your_var | default('NONE', boolean=true) }}

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

ActiveMQ or RabbitMQ or ZeroMQ or

I'm using zeroMQ. I wanted a simple message passing system and I don't need the complication of a broker. I also don't want a huge Java oriented enterprise system.

If you want a fast, simple system and you need to support multiple languages (I use C and .net) then I'd recommend looking at 0MQ.

How do I add indices to MySQL tables?

It's worth noting that multiple field indexes can drastically improve your query performance. So in the above example we assume ProductID is the only field to lookup but were the query to say ProductID = 1 AND Category = 7 then a multiple column index helps. This is achieved with the following:

ALTER TABLE `table` ADD INDEX `index_name` (`col1`,`col2`)

Additionally the index should match the order of the query fields. In my extended example the index should be (ProductID,Category) not the other way around.

fork and exec in bash

How about:

(sleep 5; echo "Hello World") &

How can I list (ls) the 5 last modified files in a directory?

The accepted answer lists only the filenames, but to get the top 5 files one can also use:

ls -lht | head -6

where:

-l outputs in a list format

-h makes output human readable (i.e. file sizes appear in kb, mb, etc.)

-t sorts output by placing most recently modified file first

head -6 will show 5 files because ls prints the block size in the first line of output.

I think this is a slightly more elegant and possibly more useful approach.

Example output:

total 26960312 -rw-r--r--@ 1 user staff 1.2K 11 Jan 11:22 phone2.7.py -rw-r--r--@ 1 user staff 2.7M 10 Jan 15:26 03-cookies-1.pdf -rw-r--r--@ 1 user staff 9.2M 9 Jan 16:21 Wk1_sem.pdf -rw-r--r--@ 1 user staff 502K 8 Jan 10:20 lab-01.pdf -rw-rw-rw-@ 1 user staff 2.0M 5 Jan 22:06 0410-1.wmv

How do I run a batch file from my Java Application?

I had the same issue. However sometimes CMD failed to run my files. That's why i create a temp.bat on my desktop, next this temp.bat is going to run my file, and next the temp file is going to be deleted.

I know this is a bigger code, however worked for me in 100% when even Runtime.getRuntime().exec() failed.

// creating a string for the Userprofile (either C:\Admin or whatever)
String userprofile = System.getenv("USERPROFILE");

BufferedWriter writer = null;
        try {
            //create a temporary file
            File logFile = new File(userprofile+"\\Desktop\\temp.bat");   
            writer = new BufferedWriter(new FileWriter(logFile));

            // Here comes the lines for the batch file!
            // First line is @echo off
            // Next line is the directory of our file
            // Then we open our file in that directory and exit the cmd
            // To seperate each line, please use \r\n
            writer.write("cd %ProgramFiles(x86)%\\SOME_FOLDER \r\nstart xyz.bat \r\nexit");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e) {
            }

        }

        // running our temp.bat file
        Runtime rt = Runtime.getRuntime();
        try {

            Process pr = rt.exec("cmd /c start \"\" \""+userprofile+"\\Desktop\\temp.bat" );
            pr.getOutputStream().close();
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);

        }
        // deleting our temp file
        File databl = new File(userprofile+"\\Desktop\\temp.bat");
        databl.delete();

Standardize data columns in R

The normalize function from the BBMisc package was the right tool for me since it can deal with NA values.

Here is how to use it:

Given the following dataset,

    ASR_API     <- c("CV",  "F",    "IER",  "LS-c", "LS-o")
    Human       <- c(NA,    5.8,    12.7,   NA, NA)
    Google      <- c(23.2,  24.2,   16.6,   12.1,   28.8)
    GoogleCloud <- c(23.3,  26.3,   18.3,   12.3,   27.3)
    IBM     <- c(21.8,  47.6,   24.0,   9.8,    25.3)
    Microsoft   <- c(29.1,  28.1,   23.1,   18.8,   35.9)
    Speechmatics    <- c(19.1,  38.4,   21.4,   7.3,    19.4)
    Wit_ai      <- c(35.6,  54.2,   37.4,   19.2,   41.7)
    dt     <- data.table(ASR_API,Human, Google, GoogleCloud, IBM, Microsoft, Speechmatics, Wit_ai)
> dt
   ASR_API Human Google GoogleCloud  IBM Microsoft Speechmatics Wit_ai
1:      CV    NA   23.2        23.3 21.8      29.1         19.1   35.6
2:       F   5.8   24.2        26.3 47.6      28.1         38.4   54.2
3:     IER  12.7   16.6        18.3 24.0      23.1         21.4   37.4
4:    LS-c    NA   12.1        12.3  9.8      18.8          7.3   19.2
5:    LS-o    NA   28.8        27.3 25.3      35.9         19.4   41.7

normalized values can be obtained like this:

> dtn <- normalize(dt, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
> dtn
   ASR_API      Human     Google GoogleCloud         IBM  Microsoft Speechmatics      Wit_ai
1:      CV         NA  0.3361245   0.2893457 -0.28468670  0.3247336  -0.18127203 -0.16032655
2:       F -0.7071068  0.4875320   0.7715885  1.59862532  0.1700986   1.55068347  1.31594762
3:     IER  0.7071068 -0.6631646  -0.5143923 -0.12409420 -0.6030768   0.02512682 -0.01746131
4:    LS-c         NA -1.3444981  -1.4788780 -1.16064578 -1.2680075  -1.24018782 -1.46198764
5:    LS-o         NA  1.1840062   0.9323361 -0.02919864  1.3762521  -0.15435044  0.32382788

where hand calculated method just ignores colmuns containing NAs:

> dt %>% mutate(normalizedHuman = (Human - mean(Human))/sd(Human)) %>% 
+ mutate(normalizedGoogle = (Google - mean(Google))/sd(Google)) %>% 
+ mutate(normalizedGoogleCloud = (GoogleCloud - mean(GoogleCloud))/sd(GoogleCloud)) %>% 
+ mutate(normalizedIBM = (IBM - mean(IBM))/sd(IBM)) %>% 
+ mutate(normalizedMicrosoft = (Microsoft - mean(Microsoft))/sd(Microsoft)) %>% 
+ mutate(normalizedSpeechmatics = (Speechmatics - mean(Speechmatics))/sd(Speechmatics)) %>% 
+ mutate(normalizedWit_ai = (Wit_ai - mean(Wit_ai))/sd(Wit_ai))
  ASR_API Human Google GoogleCloud  IBM Microsoft Speechmatics Wit_ai normalizedHuman normalizedGoogle
1      CV    NA   23.2        23.3 21.8      29.1         19.1   35.6              NA        0.3361245
2       F   5.8   24.2        26.3 47.6      28.1         38.4   54.2              NA        0.4875320
3     IER  12.7   16.6        18.3 24.0      23.1         21.4   37.4              NA       -0.6631646
4    LS-c    NA   12.1        12.3  9.8      18.8          7.3   19.2              NA       -1.3444981
5    LS-o    NA   28.8        27.3 25.3      35.9         19.4   41.7              NA        1.1840062
  normalizedGoogleCloud normalizedIBM normalizedMicrosoft normalizedSpeechmatics normalizedWit_ai
1             0.2893457   -0.28468670           0.3247336            -0.18127203      -0.16032655
2             0.7715885    1.59862532           0.1700986             1.55068347       1.31594762
3            -0.5143923   -0.12409420          -0.6030768             0.02512682      -0.01746131
4            -1.4788780   -1.16064578          -1.2680075            -1.24018782      -1.46198764
5             0.9323361   -0.02919864           1.3762521            -0.15435044       0.32382788

(normalizedHuman is made a list of NAs ...)

regarding the selection of specific columns for calculation, a generic method can be employed like this one:

data_vars <- df_full %>% dplyr::select(-ASR_API,-otherVarNotToBeUsed)
meta_vars <- df_full %>% dplyr::select(ASR_API,otherVarNotToBeUsed)
data_varsn <- normalize(data_vars, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
dtn <- cbind(meta_vars,data_varsn)

Jquery mouseenter() vs mouseover()

This example demonstrates the difference between the mousemove, mouseenter and mouseover events:

https://jsfiddle.net/z8g613yd/

HTML:

<div onmousemove="myMoveFunction()">
    <p>onmousemove: <br> <span id="demo">Mouse over me!</span></p>
</div>

<div onmouseenter="myEnterFunction()">
    <p>onmouseenter: <br> <span id="demo2">Mouse over me!</span></p>
</div>

<div onmouseover="myOverFunction()">
    <p>onmouseover: <br> <span id="demo3">Mouse over me!</span></p>
</div>

CSS:

div {
    width: 200px;
    height: 100px;
    border: 1px solid black;
    margin: 10px;
    float: left;
    padding: 30px;
    text-align: center;
    background-color: lightgray;
}

p {
    background-color: white;
    height: 50px;
}

p span {
    background-color: #86fcd4;
    padding: 0 20px;
}

JS:

var x = 0;
var y = 0;
var z = 0;

function myMoveFunction() {
    document.getElementById("demo").innerHTML = z += 1;
}

function myEnterFunction() {
    document.getElementById("demo2").innerHTML = x += 1;
}

function myOverFunction() {
    document.getElementById("demo3").innerHTML = y += 1;
}
  • onmousemove : occurs every time the mouse pointer is moved over the div element.
  • onmouseenter : only occurs when the mouse pointer enters the div element.
  • onmouseover : occurs when the mouse pointer enters the div element, and its child elements (p and span).

How do I run Python script using arguments in windows command line

import sys

def hello(a, b):
    print  'hello and that\'s your sum: {0}'.format(a + b)

if __name__ == '__main__':
    hello(int(sys.argv[1]), int(sys.argv[2]))

Moreover see @thibauts answer about how to call python script.

PHP Undefined Index

The checking of the presence of the member before assigning it is, in my opinion, quite ugly.

Kohana has a useful function to make selecting parameters simple.

You can make your own like so...

function arrayGet($array, $key, $default = NULL)
{
    return isset($array[$key]) ? $array[$key] : $default;
}

And then do something like...

$page = arrayGet($_GET, 'p', 1);

how to run a winform from console application?

Here is the best method that I've found: First, set your projects output type to "Windows Application", then P/Invoke AllocConsole to create a console window.

internal static class NativeMethods
{
    [DllImport("kernel32.dll")]
    internal static extern Boolean AllocConsole();
}

static class Program
{

    static void Main(string[] args) {
        if (args.Length == 0) {
            // run as windows app
            Application.EnableVisualStyles();
            Application.Run(new Form1()); 
        } else {
            // run as console app
            NativeMethods.AllocConsole();
            Console.WriteLine("Hello World");
            Console.ReadLine();
        }
    }

}

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

Another way

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

And in your css do this

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

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

Using a dictionary to select function to execute

#!/usr/bin/python

def thing_a(arg=None):
    print 'thing_a', arg

def thing_b(arg=None):
    print 'thing_b', arg

ghetto_switch_statement = {
    'do_thing_a': thing_a,
    'do_thing_b': thing_b
}

ghetto_switch_statement['do_thing_a']("It's lovely being an A")
ghetto_switch_statement['do_thing_b']("Being a B isn't too shabby either")

print "Available methods are: ", ghetto_switch_statement.keys()

update query with join on two tables

Try this one

UPDATE employee 
set EMPLOYEE.MAIDEN_NAME = 
  (SELECT ADD1 
   FROM EMPS 
   WHERE EMP_CODE=EMPLOYEE.EMP_CODE);
WHERE EMPLOYEE.EMP_CODE >='00' 
AND EMPLOYEE.EMP_CODE <='ZZ';

How to scroll to top of the page in AngularJS?

You can use

$window.scrollTo(x, y);

where x is the pixel along the horizontal axis and y is the pixel along the vertical axis.

  1. Scroll to top

    $window.scrollTo(0, 0);
    
  2. Focus on element

    $window.scrollTo(0, angular.element('put here your element').offsetTop);   
    

Example

Update:

Also you can use $anchorScroll

Example

Python: Number of rows affected by cursor.execute("SELECT ...)

From PEP 249, which is usually implemented by Python database APIs:

Cursor Objects should respond to the following methods and attributes:

[…]

.rowcount
This read-only attribute specifies the number of rows that the last .execute*() produced (for DQL statements like 'select') or affected (for DML statements like 'update' or 'insert').

But be careful—it goes on to say:

The attribute is -1 in case no .execute*() has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface. [7]

Note:
Future versions of the DB API specification could redefine the latter case to have the object return None instead of -1.

So if you've executed your statement, and it works, and you're certain your code will always be run against the same version of the same DBMS, this is a reasonable solution.

Using Get-childitem to get a list of files modified in the last 3 days

Very similar to previous responses, but the is from the current directory, looks at any file and only for ones that are 4 days old. This is what I needed for my research and the above answers were all very helpful. Thanks.

Get-ChildItem -Path . -Recurse| ? {$_.LastWriteTime -gt (Get-Date).AddDays(-4)}

Convert or extract TTC font to TTF - how to?

This is what worked for me for extracting TTFs from .dfont and .ttc files from Mac OS X: http://transfonter.org/ttc-unpack

The resulting TTFs work fine in Windows 7.

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

Since we're in the PowerShell area, it's extra useful if we can return a proper PowerShell object ...

I personally like this method of parsing, for the terseness:

((quser) -replace '^>', '') -replace '\s{2,}', ',' | ConvertFrom-Csv

Note: this doesn't account for disconnected ("disc") users, but works well if you just want to get a quick list of users and don't care about the rest of the information. I just wanted a list and didn't care if they were currently disconnected.

If you do care about the rest of the data it's just a little more complex:

(((quser) -replace '^>', '') -replace '\s{2,}', ',').Trim() | ForEach-Object {
    if ($_.Split(',').Count -eq 5) {
        Write-Output ($_ -replace '(^[^,]+)', '$1,')
    } else {
        Write-Output $_
    }
} | ConvertFrom-Csv

I take it a step farther and give you a very clean object on my blog.

I ended up making this into a module.

bower proxy configuration

Are you using Windows? Just set the environment variable http_proxy...

set http_proxy=http://your-proxy-address.com:port

... and bower will pick this up. Rather than dealing with a unique config file in your project folder - right? (side-note: when-the-F! will windows allow us to create a .file using explorer? c'mon windows!)

How does java do modulus calculations with negative numbers?

I don't think Java returns 51 in this case. I am running Java 8 on a Mac and I get:

-13 % 64 = -13

Program:

public class Test {
    public static void main(String[] args) {
        int i = -13;
        int j = 64;
        System.out.println(i % j);
    }
}

Java - Check if JTextField is empty or not

Try with keyListener in your textfield

jTextField.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if (text.getText().length() >= 1) {
                button.setEnabled(true);
            } else {
                button.setEnabled(false);
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }

    });

How do I force make/GCC to show me the commands?

Since GNU Make version 4.0, the --trace argument is a nice way to tell what and why a makefile do, outputing lines like:

makefile:8: target 'foo.o' does not exist

or

makefile:12: update target 'foo' due to: bar

How to get the MD5 hash of a file in C++?

Using Crypto++, you could do the following:

#include <sha.h>
#include <iostream> 

SHA256 sha; 
while ( !f.eof() ) { 
   char buff[4096];
   int numchars = f.read(...); 
   sha.Update(buff, numchars); 
}
char hash[size]; 
sha.Final(hash); 
cout << hash <<endl; 

I have a need for something very similar, because I can't read in multi-gigabyte files just to compute a hash. In theory I could memory map them, but I have to support 32bit platforms - that's still problematic for large files.

How do I detect unsigned integer multiply overflow?

You can't access the overflow flag from C/C++.

Some compilers allow you to insert trap instructions into the code. On GCC the option is -ftrapv.

The only portable and compiler independent thing you can do is to check for overflows on your own. Just like you did in your example.

However, -ftrapv seems to do nothing on x86 using the latest GCC. I guess it's a leftover from an old version or specific to some other architecture. I had expected the compiler to insert an INTO opcode after each addition. Unfortunately it does not do this.

Convert YYYYMMDD to DATE

In your case it should be:

Select convert(datetime,convert(varchar(10),GRADUATION_DATE,120)) as
'GRADUATION_DATE' from mydb

Checking for an empty file in C++

How about (not elegant way though )

int main( int argc, char* argv[] )
{
    std::ifstream file;
    file.open("example.txt");

    bool isEmpty(true);
    std::string line;

    while( file >> line ) 
        isEmpty = false;

        std::cout << isEmpty << std::endl;
}

How do I discover memory usage of my application in Android?

Yes, you can get memory info programmatically and decide whether to do memory intensive work.

Get VM Heap Size by calling:

Runtime.getRuntime().totalMemory();

Get Allocated VM Memory by calling:

Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

Get VM Heap Size Limit by calling:

Runtime.getRuntime().maxMemory()

Get Native Allocated Memory by calling:

Debug.getNativeHeapAllocatedSize();

I made an app to figure out the OutOfMemoryError behavior and monitor memory usage.

https://play.google.com/store/apps/details?id=net.coocood.oomresearch

You can get the source code at https://github.com/coocood/oom-research