Programs & Examples On #Hsm

Hardware Security Modules are devices designed to protect cryptographic key material and accelerate certain operations.

Redirect to external URL with return in laravel

For Laravel 5.x / 6.x / 7.x use:

return redirect()->away('https://www.google.com');

as stated in the docs:

Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

Improve SQL Server query performance on large tables

I know that you said that adding indexes is not an option but that would be the only option to eliminate the table scan you have. When you do a scan, SQL Server reads all 2 million rows on the table to fulfill your query.

this article provides more info but remember: Seek = good, Scan = bad.

Second, can't you eliminate the select * and select only the columns you need? Third, no "where" clause? Even if you have a index, since you are reading everything the best you will get is a index scan (which is better than a table scan, but it is not a seek, which is what you should aim for)

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We faced the same problem:

ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log

In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

The type initializer for 'MyClass' threw an exception

In my case I had this failing on Logger.Create inside a class library that was being used by my main (console) app. The problem was I had forgotten to add a reference to NLog.dll in my console app. Adding the reference with the correct .NET Framework library version fixed the problem.

Oracle - how to remove white spaces?

I have used below command to remove white space in Oracle

My Table Name is - NG_CAP_SENDER_INFO_MTR

My Column Name is - SENINFO_FROM

UPDATE NG_CAP_SENDER_INFO_MTR SET SENINFO_FROM = TRIM(SENINFO_FROM); 

Already Answer on StackOverflow LTRIM RTRIM

And its working fine

stop all instances of node.js server

Windows & GitBash Terminal I needed to use this command inside Windows / Webstorm / GitBash terminal

cmd "/C TASKKILL /IM node.exe /F"

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

for me, just press cmd+, then go to account ,chose your developer account refresh(XCODE6) OR download all (XCODE7) will fix.

Convert String to Double - VB

Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
    ' text is convertible to Double, and value contains the Double value now
Else
    ' Cannot convert text to Double
End If

Where can I find the .apk file on my device, when I download any app and install?

You can use a file browser with an backup function, for example the ES File Explorer Long tap a item and select create backup

Shell script to delete directories older than n days

find supports -delete operation, so:

find /base/dir/* -ctime +10 -delete;

I think there's a catch that the files need to be 10+ days older too. Haven't tried, someone may confirm in comments.

The most voted solution here is missing -maxdepth 0 so it will call rm -rf for every subdirectory, after deleting it. That doesn't make sense, so I suggest:

find /base/dir/* -maxdepth 0  -type d -ctime +10 -exec rm -rf {} \;

The -delete solution above doesn't use -maxdepth 0 because find would complain the dir is not empty. Instead, it implies -depth and deletes from the bottom up.

How connect Postgres to localhost server using pgAdmin on Ubuntu?

if you open the psql console in a terminal window, by typing

$ psql

you're super user username will be shown before the =#, for example:

elisechant=#$

That will be the user name you should use for localhost.

What does the CSS rule "clear: both" do?

The clear property indicates that the left, right or both sides of an element can not be adjacent to earlier floated elements within the same block formatting context. Cleared elements are pushed below the corresponding floated elements. Examples:

clear: none; Element remains adjacent to floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-none {_x000D_
  clear: none;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-none">clear: none;</div>
_x000D_
_x000D_
_x000D_

clear: left; Element pushed below left floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-left {_x000D_
  clear: left;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-left">clear: left;</div>
_x000D_
_x000D_
_x000D_

clear: right; Element pushed below right floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-right {_x000D_
  clear: right;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-right">clear: right;</div>
_x000D_
_x000D_
_x000D_

clear: both; Element pushed below all floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-both {_x000D_
  clear: both;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-both">clear: both;</div>
_x000D_
_x000D_
_x000D_

clear does not affect floats outside the current block formatting context

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.inline-block {_x000D_
  display: inline-block;_x000D_
  background: #BDF;_x000D_
}_x000D_
.inline-block .float-left {_x000D_
  height: 60px;_x000D_
}_x000D_
.clear-both {_x000D_
  clear: both;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="inline-block">_x000D_
  <div>display: inline-block;</div>_x000D_
  <div class="float-left">float: left;</div>_x000D_
  <div class="clear-both">clear: both;</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

HTTP client timeout and server timeout

go to the url about:config and paste each line:

network.http.keep-alive.timeout;10
network.http.connection-retry-timeout;10
network.http.pipelining.read-timeout;5
network.http.connection-timeout;10

Can you change what a symlink points to after it is created?

Technically, there's no built-in command to edit an existing symbolic link. It can be easily achieved with a few short commands.

Here's a little bash/zsh function I wrote to update an existing symbolic link:

# -----------------------------------------
# Edit an existing symbolic link
#
# @1 = Name of symbolic link to edit
# @2 = Full destination path to update existing symlink with 
# -----------------------------------------
function edit-symlink () {
    if [ -z "$1" ]; then
        echo "Name of symbolic link you would like to edit:"
        read LINK
    else
        LINK="$1"
    fi
    LINKTMP="$LINK-tmp"
    if [ -z "$2" ]; then
        echo "Full destination path to update existing symlink with:"
        read DEST
    else
        DEST="$2"
    fi
    ln -s $DEST $LINKTMP
    rm $LINK
    mv $LINKTMP $LINK
    printf "Updated $LINK to point to new destination -> $DEST"
}

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

I tried the accepted answer which prevented the body from scrolling but had the issue of scrolling to the top. This should solve both issues.

As a side note, it appears overflow:hidden doesn't work on body for iOS Safari only as iOS Chrome works fine.

var scrollPos = 0;

$('.modal')
    .on('show.bs.modal', function (){
        scrollPos = $('body').scrollTop();
        $('body').css({
            overflow: 'hidden',
            position: 'fixed',
            top : -scrollPos
        });
    })
    .on('hide.bs.modal', function (){
        $('body').css({
            overflow: '',
            position: '',
            top: ''
        }).scrollTop(scrollPos);
    });

Inserting values into a SQL Server database using ado.net via C#

Remove the comma

... Gender,Contact, " + ") VALUES ...
                  ^-----------------here

"fatal: Not a git repository (or any of the parent directories)" from git status

I just got this message and there is a very simple answer before trying the others. At the parent directory, type git init

This will initialize the directory for git. Then git add and git commit should work.

Hide options in a select list using jQuery

$("option_you_want_to_hide").addClass('hidden')

Then, in your css make sure you have

.hidden{
    display:none;
}

How to change the color of a button?

You can change the value in the XML like this:

<Button
    android:background="#FFFFFF"
     ../>

Here, you can add any other color, from the resources or hex.

Similarly, you can also change these values form the code like this:

demoButton.setBackgroundColor(Color.WHITE);

Another easy way is to make a drawable, customize the corners and shape according to your preference and set the background color and stroke of the drawable. For eg.

button_background.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="2dp" android:color="#ff207d94" />
    <corners android:radius="5dp" />
    <solid android:color="#FFFFFF" />
</shape>

And then set this shape as the background of your button.

<Button
    android:background="@drawable/button_background.xml"
     ../>

Hope this helps, good luck!

Java dynamic array sizes?

It is a good practice get the amount you need to store first then initialize the array.

for example, you would ask the user how many data he need to store and then initialize it, or query the component or argument of how many you need to store. if you want a dynamic array you could use ArrayList() and use al.add(); function to keep adding, then you can transfer it to a fixed array.

//Initialize ArrayList and cast string so ArrayList accepts strings (or anything
ArrayList<string> al = new ArrayList(); 
//add a certain amount of data
for(int i=0;i<x;i++)
{
  al.add("data "+i); 
}

//get size of data inside
int size = al.size(); 
//initialize String array with the size you have
String strArray[] = new String[size]; 
//insert data from ArrayList to String array
for(int i=0;i<size;i++)
{
  strArray[i] = al.get(i);
}

doing so is redundant but just to show you the idea, ArrayList can hold objects unlike other primitive data types and are very easy to manipulate, removing anything from the middle is easy as well, completely dynamic.same with List and Stack

.gitignore for Visual Studio Projects and Solutions

On Visual Studio 2015 Update 3, and with Git extension updated as of today (2016-10-24), the .gitignore generated by Visual Studio is:

## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
[Xx]64/
[Xx]86/
[Bb]uild/
bld/
[Bb]in/
[Oo]bj/

# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUNIT
*.VisualState.xml
TestResult.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

# DNX
project.lock.json
artifacts/

*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db

# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# JustCode is a .NET coding add-in
.JustCode

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml

# TODO: Un-comment the next line if you do not want to checkin 
# your web deploy settings because they may include unencrypted
# passwords
#*.pubxml
*.publishproj

# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets

# Microsoft Azure Build Output
csx/
*.build.csdef

# Microsoft Azure Emulator
ecf/
rcf/

# Microsoft Azure ApplicationInsights config file
ApplicationInsights.config

# Windows Store app package directory
AppPackages/
BundleArtifacts/

# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/

# Others
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm

# SQL Server files
*.mdf
*.ldf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings

# Microsoft Fakes
FakesAssemblies/

# GhostDoc plugin setting file
*.GhostDoc.xml

# Node.js Tools for Visual Studio
.ntvs_analysis.dat

# Visual Studio 6 build log
*.plg

# Visual Studio 6 workspace options file
*.opt

# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions

# LightSwitch generated files
GeneratedArtifacts/
ModelManifest.xml

# Paket dependency manager
.paket/paket.exe

# FAKE - F# Make
.fake/

Measuring the distance between two coordinates in PHP

Quite old question, but for those interested in a PHP code that returns the same results as Google Maps, the following does the job:

/**
 * Computes the distance between two coordinates.
 *
 * Implementation based on reverse engineering of
 * <code>google.maps.geometry.spherical.computeDistanceBetween()</code>.
 *
 * @param float $lat1 Latitude from the first point.
 * @param float $lng1 Longitude from the first point.
 * @param float $lat2 Latitude from the second point.
 * @param float $lng2 Longitude from the second point.
 * @param float $radius (optional) Radius in meters.
 *
 * @return float Distance in meters.
 */
function computeDistance($lat1, $lng1, $lat2, $lng2, $radius = 6378137)
{
    static $x = M_PI / 180;
    $lat1 *= $x; $lng1 *= $x;
    $lat2 *= $x; $lng2 *= $x;
    $distance = 2 * asin(sqrt(pow(sin(($lat1 - $lat2) / 2), 2) + cos($lat1) * cos($lat2) * pow(sin(($lng1 - $lng2) / 2), 2)));

    return $distance * $radius;
}

I've tested with various coordinates and it works perfectly.

I think it should be faster then some alternatives too. But didn't test that.

Hint: Google Maps uses 6378137 as Earth radius. So using it with other algorithms might work as well.

What does '?' do in C++?

You can just rewrite it as:

int qempty(){ return(f==r);}

Which does the same thing as said in the other answers.

How to convert an Stream into a byte[] in C#?

Call next function like

byte[] m_Bytes = StreamHelper.ReadToEnd (mystream);

Function:

public static byte[] ReadToEnd(System.IO.Stream stream)
{
    long originalPosition = 0;

    if(stream.CanSeek)
    {
         originalPosition = stream.Position;
         stream.Position = 0;
    }

    try
    {
        byte[] readBuffer = new byte[4096];

        int totalBytesRead = 0;
        int bytesRead;

        while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
        {
            totalBytesRead += bytesRead;

            if (totalBytesRead == readBuffer.Length)
            {
                int nextByte = stream.ReadByte();
                if (nextByte != -1)
                {
                    byte[] temp = new byte[readBuffer.Length * 2];
                    Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                    Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                    readBuffer = temp;
                    totalBytesRead++;
                }
            }
        }

        byte[] buffer = readBuffer;
        if (readBuffer.Length != totalBytesRead)
        {
            buffer = new byte[totalBytesRead];
            Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
        }
        return buffer;
    }
    finally
    {
        if(stream.CanSeek)
        {
             stream.Position = originalPosition; 
        }
    }
}

Python: printing a file to stdout

f = open('file.txt', 'r')
print f.read()
f.close()

From http://docs.python.org/tutorial/inputoutput.html

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

Printing to the console in Google Apps Script?

In a google script project you can create html files (example: index.html) or gs files (example:code.gs). The .gs files are executed on the server and you can use Logger.log as @Peter Herrman describes. However if the function is created in a .html file it is being executed on the user's browser and you can use console.log. The Chrome browser console can be viewed by Ctrl Shift J on Windows/Linux or Cmd Opt J on Mac

If you want to use Logger.log on an html file you can use a scriptlet to call the Logger.log function from the html file. To do so you would insert <? Logger.log(something) ?> replacing something with whatever you want to log. Standard scriptlets, which use the syntax <? ... ?>, execute code without explicitly outputting content to the page.

Java 8 Iterable.forEach() vs foreach loop

The better practice is to use for-each. Besides violating the Keep It Simple, Stupid principle, the new-fangled forEach() has at least the following deficiencies:

  • Can't use non-final variables. So, code like the following can't be turned into a forEach lambda:
Object prev = null;
for(Object curr : list)
{
    if( prev != null )
        foo(prev, curr);
    prev = curr;
}
  • Can't handle checked exceptions. Lambdas aren't actually forbidden from throwing checked exceptions, but common functional interfaces like Consumer don't declare any. Therefore, any code that throws checked exceptions must wrap them in try-catch or Throwables.propagate(). But even if you do that, it's not always clear what happens to the thrown exception. It could get swallowed somewhere in the guts of forEach()

  • Limited flow-control. A return in a lambda equals a continue in a for-each, but there is no equivalent to a break. It's also difficult to do things like return values, short circuit, or set flags (which would have alleviated things a bit, if it wasn't a violation of the no non-final variables rule). "This is not just an optimization, but critical when you consider that some sequences (like reading the lines in a file) may have side-effects, or you may have an infinite sequence."

  • Might execute in parallel, which is a horrible, horrible thing for all but the 0.1% of your code that needs to be optimized. Any parallel code has to be thought through (even if it doesn't use locks, volatiles, and other particularly nasty aspects of traditional multi-threaded execution). Any bug will be tough to find.

  • Might hurt performance, because the JIT can't optimize forEach()+lambda to the same extent as plain loops, especially now that lambdas are new. By "optimization" I do not mean the overhead of calling lambdas (which is small), but to the sophisticated analysis and transformation that the modern JIT compiler performs on running code.

  • If you do need parallelism, it is probably much faster and not much more difficult to use an ExecutorService. Streams are both automagical (read: don't know much about your problem) and use a specialized (read: inefficient for the general case) parallelization strategy (fork-join recursive decomposition).

  • Makes debugging more confusing, because of the nested call hierarchy and, god forbid, parallel execution. The debugger may have issues displaying variables from the surrounding code, and things like step-through may not work as expected.

  • Streams in general are more difficult to code, read, and debug. Actually, this is true of complex "fluent" APIs in general. The combination of complex single statements, heavy use of generics, and lack of intermediate variables conspire to produce confusing error messages and frustrate debugging. Instead of "this method doesn't have an overload for type X" you get an error message closer to "somewhere you messed up the types, but we don't know where or how." Similarly, you can't step through and examine things in a debugger as easily as when the code is broken into multiple statements, and intermediate values are saved to variables. Finally, reading the code and understanding the types and behavior at each stage of execution may be non-trivial.

  • Sticks out like a sore thumb. The Java language already has the for-each statement. Why replace it with a function call? Why encourage hiding side-effects somewhere in expressions? Why encourage unwieldy one-liners? Mixing regular for-each and new forEach willy-nilly is bad style. Code should speak in idioms (patterns that are quick to comprehend due to their repetition), and the fewer idioms are used the clearer the code is and less time is spent deciding which idiom to use (a big time-drain for perfectionists like myself!).

As you can see, I'm not a big fan of the forEach() except in cases when it makes sense.

Particularly offensive to me is the fact that Stream does not implement Iterable (despite actually having method iterator) and cannot be used in a for-each, only with a forEach(). I recommend casting Streams into Iterables with (Iterable<T>)stream::iterator. A better alternative is to use StreamEx which fixes a number of Stream API problems, including implementing Iterable.

That said, forEach() is useful for the following:

  • Atomically iterating over a synchronized list. Prior to this, a list generated with Collections.synchronizedList() was atomic with respect to things like get or set, but was not thread-safe when iterating.

  • Parallel execution (using an appropriate parallel stream). This saves you a few lines of code vs using an ExecutorService, if your problem matches the performance assumptions built into Streams and Spliterators.

  • Specific containers which, like the synchronized list, benefit from being in control of iteration (although this is largely theoretical unless people can bring up more examples)

  • Calling a single function more cleanly by using forEach() and a method reference argument (ie, list.forEach (obj::someMethod)). However, keep in mind the points on checked exceptions, more difficult debugging, and reducing the number of idioms you use when writing code.

Articles I used for reference:

EDIT: Looks like some of the original proposals for lambdas (such as http://www.javac.info/closures-v06a.html Google Cache) solved some of the issues I mentioned (while adding their own complications, of course).

How to know user has clicked "X" or the "Close" button?

How to detect if the form closed by click on X button or by calling Close() in code?

You cannot rely on close reason of the form closing event args, because if the user click X button on title bar or close the form using Alt + F4 or use system menu to close the form or the form get closed by calling Close() method, all all above cases, the close reason will be Closed by User which is not desired result.

To distinguish if the form closed by X button or by Close method, you can use either of the following options:

  • Handle WM_SYSCOMMAND and check for SC_CLOSE and set a flag.
  • Check the StackTrace to see if any of the frames contain Close method call.

Example 1 - Handle WM_SYSCOMMAND

public bool ClosedByXButtonOrAltF4 {get; private set;}
private const int SC_CLOSE = 0xF060;
private const int WM_SYSCOMMAND = 0x0112;
protected override void WndProc(ref Message msg)
{
    if (msg.Msg == WM_SYSCOMMAND && msg.WParam.ToInt32() == SC_CLOSE)
        ClosedByXButtonOrAltF4 = true;
    base.WndProc(ref msg);
}
protected override void OnShown(EventArgs e)
{
    ClosedByXButtonOrAltF4 = false;
}   
protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (ClosedByXButtonOrAltF4)
        MessageBox.Show("Closed by X or Alt+F4");
    else
        MessageBox.Show("Closed by calling Close()");
}

Example 2 - Checking StackTrace

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (new StackTrace().GetFrames().Any(x => x.GetMethod().Name == "Close"))
        MessageBox.Show("Closed by calling Close()");
    else
        MessageBox.Show("Closed by X or Alt+F4");
}

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

FWIW, sp_test will not be returning anything but an integer (all SQL Server stored procs just return an integer) and no result sets on the wire (since no SELECT statements). To get the output of the PRINT statements, you normally use the InfoMessage event on the connection (not the command) in ADO.NET.

Fragment MyFragment not attached to Activity

simple solution and work 100%

if (getActivity() == null || !isAdded()) return;

Check if list is empty in C#

If the list implementation you're using is IEnumerable<T> and Linq is an option, you can use Any:

if (!list.Any()) {

}

Otherwise you generally have a Length or Count property on arrays and collection types respectively.

How to stop VBA code running?

I do this a lot. A lot. :-)

I have got used to using "DoEvents" more often, but still tend to set things running without really double checking a sure stop method.

Then, today, having done it again, I thought, "Well just wait for the end in 3 hours", and started paddling around in the ribbon. Earlier, I had noticed in the "View" section of the Ribbon a "Macros" pull down, and thought I have a look to see if I could see my interminable Macro running....

I now realise you can also get this up using Alt-F8.

Then I thought, well what if I "Step into" a different Macro, would that rescue me? It did :-) It also works if you step into your running Macro (but you still lose where you're upto), unless you are a very lazy programmer like me and declare lots of "Global" variables, in which case the Global data is retained :-)

K

Xcode 6: Keyboard does not show up in simulator

In the new simulator Hardware option is removed,

If you want to find a Keyboard option manually, Then click on the I/O section,

I/O -> Keyboard ->Toggle Software Keyboard(?K)

enter image description here

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

Use FontAwesome or Glyphicons with css :before

Re: using icon in :before – recent Font Awesome builds include the .fa-icon() mixin for SASS and LESS. This will automatically include the font-family as well as some rendering tweaks (e.g. -webkit-font-smoothing). Thus you can do, e.g.:

// Add "?" icon to header.
h1:before {
    .fa-icon();
    content: "\f059";
}

How many bytes in a JavaScript string?

The answer from Lauri Oherd works well for most strings seen in the wild, but will fail if the string contains lone characters in the surrogate pair range, 0xD800 to 0xDFFF. E.g.

byteCount(String.fromCharCode(55555))
// URIError: URI malformed

This longer function should handle all strings:

function bytes (str) {
  var bytes=0, len=str.length, codePoint, next, i;

  for (i=0; i < len; i++) {
    codePoint = str.charCodeAt(i);

    // Lone surrogates cannot be passed to encodeURI
    if (codePoint >= 0xD800 && codePoint < 0xE000) {
      if (codePoint < 0xDC00 && i + 1 < len) {
        next = str.charCodeAt(i + 1);

        if (next >= 0xDC00 && next < 0xE000) {
          bytes += 4;
          i++;
          continue;
        }
      }
    }

    bytes += (codePoint < 0x80 ? 1 : (codePoint < 0x800 ? 2 : 3));
  }

  return bytes;
}

E.g.

bytes(String.fromCharCode(55555))
// 3

It will correctly calculate the size for strings containing surrogate pairs:

bytes(String.fromCharCode(55555, 57000))
// 4 (not 6)

The results can be compared with Node's built-in function Buffer.byteLength:

Buffer.byteLength(String.fromCharCode(55555), 'utf8')
// 3

Buffer.byteLength(String.fromCharCode(55555, 57000), 'utf8')
// 4 (not 6)

How do you get assembler output from C/C++ source in gcc?

I don't see this possibility among answers, probably because the question is from 2008, but in 2018 you can use Matt Goldbolt's online website https://godbolt.org

You can also locally git clone and run his project https://github.com/mattgodbolt/compiler-explorer

How do you create a Swift Date object?

Swift doesn't have its own Date type, but you to use the existing Cocoa NSDate type, e.g:

class Date {

    class func from(year: Int, month: Int, day: Int) -> Date {
        let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!

        var dateComponents = DateComponents()
        dateComponents.year = year
        dateComponents.month = month
        dateComponents.day = day

        let date = gregorianCalendar.date(from: dateComponents)!
        return date
    }

    class func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone.default
        dateFormatter.dateFormat = format

        let date = dateFormatter.date(from: string)!
        return date
    }
}

Which you can use like:

var date = Date.parse("2014-05-20")
var date = Date.from(year: 2014, month: 05, day: 20)

Change the "No file chosen":

HTML

  <div class="fileUpload btn btn-primary">
    <label class="upload">
      <input name='Image' type="file"/>
    Upload Image
    </label>
  </div>

CSS

input[type="file"]
{
  display: none;
}
.fileUpload input.upload 
{
    display: inline-block;
}

Note: Btn btn-primary is a class of bootstrap button. However the button may look weired in position. Hope you can fix it by inline css.

npm install errors with Error: ENOENT, chmod

I got this error while trying to install a grunt plugin. i found i had an outdated version of npm and the error went away after updating npm to the latest version

npm install -g npm

How to replace blank (null ) values with 0 for all records?

If you're trying to do this with a query, then here is your answer:

SELECT ISNULL([field], 0) FROM [table]

Edit

ISNULL function was used incorrectly - this modified version uses IIF

SELECT IIF(ISNULL([field]), 0, [field]) FROM [table]

If you want to replace the actual values in the table, then you'll need to do it this way:

UPDATE [table] SET [FIELD] = 0 WHERE [FIELD] IS NULL

Handling Enter Key in Vue.js

Event Modifiers

You can refer to event modifiers in vuejs to prevent form submission on enter key.

It is a very common need to call event.preventDefault() or event.stopPropagation() inside event handlers.

Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.

To address this problem, Vue provides event modifiers for v-on. Recall that modifiers are directive postfixes denoted by a dot.

<form v-on:submit.prevent="<method>">
  ...
</form>

As the documentation states, this is syntactical sugar for e.preventDefault() and will stop the unwanted form submission on press of enter key.

Here is a working fiddle.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#myApp',_x000D_
  data: {_x000D_
    emailAddress: '',_x000D_
    log: ''_x000D_
  },_x000D_
  methods: {_x000D_
    validateEmailAddress: function(e) {_x000D_
      if (e.keyCode === 13) {_x000D_
        alert('Enter was pressed');_x000D_
      } else if (e.keyCode === 50) {_x000D_
        alert('@ was pressed');_x000D_
      }      _x000D_
      this.log += e.key;_x000D_
    },_x000D_
    _x000D_
    postEmailAddress: function() {_x000D_
   this.log += '\n\nPosting';_x000D_
    },_x000D_
    noop () {_x000D_
      // do nothing ?_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
html, body, #editor {_x000D_
  margin: 0;_x000D_
  height: 100%;_x000D_
  color: #333;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
<form v-on:submit.prevent="noop">_x000D_
  <input type="text" v-model="emailAddress" v-on:keyup="validateEmailAddress" />_x000D_
  <button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
  <br /><br />_x000D_
  _x000D_
  <textarea v-model="log" rows="4"></textarea>  _x000D_
</form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between using constructor vs getInitialState in React / React Native?

If you are writing React-Native class with ES6, following format will be followed. It includes life cycle methods of RN for the class making network calls.

import React, {Component} from 'react';
import {
     AppRegistry, StyleSheet, View, Text, Image
     ToastAndroid
} from 'react-native';
import * as Progress from 'react-native-progress';

export default class RNClass extends Component{
     constructor(props){
          super(props);

          this.state= {
               uri: this.props.uri,
               loading:false
          }
     }

     renderLoadingView(){
          return(
               <View style={{justifyContent:'center',alignItems:'center',flex:1}}>
                    <Progress.Circle size={30} indeterminate={true} />
                    <Text>
                        Loading Data...
                    </Text>
               </View>
          );
     }

     renderLoadedView(){
          return(
               <View>

               </View>
          );
     }

     fetchData(){
          fetch(this.state.uri)
               .then((response) => response.json())
               .then((result)=>{

               })
               .done();

               this.setState({
                         loading:true
               });
               this.renderLoadedView();
     }

     componentDidMount(){
          this.fetchData();
     }

     render(){
          if(!this.state.loading){
               return(
                    this.renderLoadingView()
               );
          }

          else{

               return(
                    this.renderLoadedView()
               );
          }
     }
}

var style = StyleSheet.create({

});

ASP.NET DateTime Picker

Try bootstrap-datepicker if you are using bootstrap.

How to add additional fields to form before submit?

May be useful for some:

(a function that allow you to add the data to the form using an object, with override for existing inputs, if there is) [pure js]

(form is a dom el, and not a jquery object [jqryobj.get(0) if you need])

function addDataToForm(form, data) {
    if(typeof form === 'string') {
        if(form[0] === '#') form = form.slice(1);
        form = document.getElementById(form);
    }

    var keys = Object.keys(data);
    var name;
    var value;
    var input;

    for (var i = 0; i < keys.length; i++) {
        name = keys[i];
        // removing the inputs with the name if already exists [overide]
        // console.log(form);
        Array.prototype.forEach.call(form.elements, function (inpt) {
             if(inpt.name === name) {
                 inpt.parentNode.removeChild(inpt);
             }
        });

        value = data[name];
        input = document.createElement('input');
        input.setAttribute('name', name);
        input.setAttribute('value', value);
        input.setAttribute('type', 'hidden');

        form.appendChild(input);
    }

    return form;
}

Use :

addDataToForm(form, {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can use it like that too

var form = addDataToForm('myFormId', {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can add # if you like too ("#myformid").

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

You can Use KeyPress instead of KeyUp or KeyDown its more efficient and here's how to handle

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Enter)
        {
            e.Handled = true;
            button1.PerformClick();
        }
    }

hope it works

How to convert list data into json in java

Using gson it is much simpler. Use following code snippet:

 // create a new Gson instance
 Gson gson = new Gson();
 // convert your list to json
 String jsonCartList = gson.toJson(cartList);
 // print your generated json
 System.out.println("jsonCartList: " + jsonCartList);

Converting back from JSON string to your Java object

 // Converts JSON string into a List of Product object
 Type type = new TypeToken<List<Product>>(){}.getType();
 List<Product> prodList = gson.fromJson(jsonCartList, type);

 // print your List<Product>
 System.out.println("prodList: " + prodList);

How to check if user input is not an int value

Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
            sc.next(); // discard
            continue;
        }
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");

        }
    break;
  }

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

You need to grant access to the user from any hostname.

This is how you add new privilege from phpmyadmin

Goto Privileges > Add a new User

enter image description here

Select Any Host for the desired username

enter image description here

How do I remove objects from an array in Java?

EDIT:

The point with the nulls in the array has been cleared. Sorry for my comments.

Original:

Ehm... the line

array = list.toArray(array);

replaces all gaps in the array where the removed element has been with null. This might be dangerous, because the elements are removed, but the length of the array remains the same!

If you want to avoid this, use a new Array as parameter for toArray(). If you don`t want to use removeAll, a Set would be an alternative:

        String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };

        System.out.println(Arrays.toString(array));

        Set<String> asSet = new HashSet<String>(Arrays.asList(array));
        asSet.remove("a");
        array = asSet.toArray(new String[] {});

        System.out.println(Arrays.toString(array));

Gives:

[a, bc, dc, a, ef]
[dc, ef, bc]

Where as the current accepted answer from Chris Yester Young outputs:

[a, bc, dc, a, ef]
[bc, dc, ef, null, ef]

with the code

    String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };

    System.out.println(Arrays.toString(array));

    List<String> list = new ArrayList<String>(Arrays.asList(array));
    list.removeAll(Arrays.asList("a"));
    array = list.toArray(array);        

    System.out.println(Arrays.toString(array));

without any null values left behind.

Remove table row after clicking table row delete button

Following solution is working fine.

HTML:

<table>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
</table>

JQuery:

function SomeDeleteRowFunction(btndel) {
    if (typeof(btndel) == "object") {
        $(btndel).closest("tr").remove();
    } else {
        return false;
    }
}

I have done bins on http://codebins.com/bin/4ldqpa9

how to display a javascript var in html body

You can do the same on document ready event like below

<script>
$(document).ready(function(){
 var number = 112;
    $("yourClass/Element/id...").html(number);
// $("yourClass/Element/id...").text(number);
});
</script>

or you can simply do it using document.write(number);.

Using python's mock patch.object to change the return value of a method called within another method

This can be done with something like this:

# foo.py
class Foo:
    def method_1():
        results = uses_some_other_method()


# testing.py
from mock import patch

@patch('Foo.uses_some_other_method', return_value="specific_value"):
def test_some_other_method(mock_some_other_method):
    foo = Foo()
    the_value = foo.method_1()
    assert the_value == "specific_value"

Here's a source that you can read: Patching in the wrong place

how to align img inside the div to the right?

<div style="width:300px; text-align:right;">
        <img src="someimgage.gif">
</div>

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

I had the exact same error.

It was because i didn't run setup_xampp.bat

This is a better solution than going through config files and changing ports.

Rollback a Git merge

git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705

But may have unexpected side-effects. See --mainline parent-number option in git-scm.com/docs/git-revert

Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !

Laravel Mail::send() sending to multiple to or bcc addresses

Try this:

$toemail = explode(',', str_replace(' ', '', $request->toemail));

jQuery OR Selector?

If you're looking to use the standard construct of element = element1 || element2 where JavaScript will return the first one that is truthy, you could do exactly that:

element = $('#someParentElement .somethingToBeFound') || $('#someParentElement .somethingElseToBeFound');

which would return the first element that is actually found. But a better way would probably be to use the jQuery selector comma construct (which returns an array of found elements) in this fashion:

element = $('#someParentElement').find('.somethingToBeFound, .somethingElseToBeFound')[0];

which will return the first found element.

I use that from time to time to find either an active element in a list or some default element if there is no active element. For example:

element = $('ul#someList').find('li.active, li:first')[0] 

which will return any li with a class of active or, should there be none, will just return the last li.

Either will work. There are potential performance penalties, though, as the || will stop processing as soon as it finds something truthy whereas the array approach will try to find all elements even if it has found one already. Then again, using the || construct could potentially have performance issues if it has to go through several selectors before finding the one it will return, because it has to call the main jQuery object for each one (I really don't know if this is a performance hit or not, it just seems logical that it could be). In general, though, I use the array approach when the selector is a rather long string.

Why do we always prefer using parameters in SQL statements?

You are right, this is related to SQL injection, which is a vulnerability that allows a malicioius user to execute arbitrary statements against your database. This old time favorite XKCD comic illustrates the concept:

Her daughter is named Help I'm trapped in a driver's license factory.


In your example, if you just use:

var query = "SELECT empSalary from employee where salary = " + txtSalary.Text;
// and proceed to execute this query

You are open to SQL injection. For example, say someone enters txtSalary:

1; UPDATE employee SET salary = 9999999 WHERE empID = 10; --
1; DROP TABLE employee; --
// etc.

When you execute this query, it will perform a SELECT and an UPDATE or DROP, or whatever they wanted. The -- at the end simply comments out the rest of your query, which would be useful in the attack if you were concatenating anything after txtSalary.Text.


The correct way is to use parameterized queries, eg (C#):

SqlCommand query =  new SqlCommand("SELECT empSalary FROM employee 
                                    WHERE salary = @sal;");
query.Parameters.AddWithValue("@sal", txtSalary.Text);

With that, you can safely execute the query.

For reference on how to avoid SQL injection in several other languages, check bobby-tables.com, a website maintained by a SO user.

VBA Check if variable is empty

To check if a Variant is Null, you need to do it like:

Isnull(myvar) = True

or

Not Isnull(myvar)

What's the difference between ".equals" and "=="?

public static void main(String[] args){
        String s1 = new String("hello");
        String s2 = new String("hello");

        System.out.println(s1.equals(s2));
        ////
        System.out.println(s1 == s2);

    System.out.println("-----------------------------");

        String s3 = "hello";
        String s4 = "hello";

        System.out.println(s3.equals(s4));
        ////
        System.out.println(s3 == s4);
    }

Here in this code u can campare the both '==' and '.equals'

here .equals is used to compare the reference objects and '==' is used to compare state of objects..

How to override and extend basic Django admin templates?

for app index add this line to somewhere common py file like url.py

admin.site.index_template = 'admin/custom_index.html'

for app module index : add this line to admin.py

admin.AdminSite.app_index_template = "servers/servers-home.html"

for change list : add this line to admin class:

change_list_template = "servers/servers_changelist.html"

for app module form template : add this line to your admin class

change_form_template = "servers/server_changeform.html"

etc. and find other in same admin's module classes

How to remove duplicates from a list?

IMHO best way how to do it these days:

Suppose you have a Collection "dups" and you want to create another Collection containing the same elements but with all duplicates eliminated. The following one-liner does the trick.

Collection<collectionType> noDups = new HashSet<collectionType>(dups);

It works by creating a Set which, by definition, cannot contain duplicates.

Based on oracle doc.

Is there a way to know your current username in mysql?

Use this query:

SELECT USER();

Or

SELECT CURRENT_USER;

how to concat two columns into one with the existing column name in mysql?

Just Remove * from your select clause, and mention all column names explicitly and omit the FIRSTNAME column. After this write CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME. The above query will give you the only one FIRSTNAME column.

GoTo Next Iteration in For Loop in java

As mentioned in all other answers, the keyword continue will skip to the end of the current iteration.

Additionally you can label your loop starts and then use continue [labelname]; or break [labelname]; to control what's going on in nested loops:

loop1: for (int i = 1; i < 10; i++) {
    loop2: for (int j = 1; j < 10; j++) {
        if (i + j == 10)
            continue loop1;

        System.out.print(j);
    }
    System.out.println();
}

Using Python 3 in virtualenv

You can specify specific Version of Python while creating environment.
It's mentioned in virtualenv.py

virtualenv --python=python3.5 envname

In some cases this has to be the full path to the executable:

virtualenv --python=/Users/username/.pyenv/versions/3.6.0/bin/python3.6 envname

How -p works

parser.add_option(
    '-p', '--python',
    dest='python',
    metavar='PYTHON_EXE',
    help='The Python interpreter to use, e.g., --python=python3.5 will use the python3.5 '
    'interpreter to create the new environment.  The default is the interpreter that '
    'virtualenv was installed with (%s)' % sys.executable)

RecyclerView - Get view at particular position

You can use below

mRecyclerview.getChildAt(pos);

Convert comma separated string of ints to int array

If you don't want to have the current error handling behaviour, it's really easy:

return text.Split(',').Select(x => int.Parse(x));

Otherwise, I'd use an extra helper method (as seen this morning!):

public static int? TryParseInt32(string text)
{
    int value;
    return int.TryParse(text, out value) ? value : (int?) null;
}

and:

return text.Split(',').Select<string, int?>(TryParseInt32)
                      .Where(x => x.HasValue)
                      .Select(x => x.Value);

or if you don't want to use the method group conversion:

return text.Split(',').Select(t => t.TryParseInt32(t)
                      .Where(x => x.HasValue)
                      .Select(x => x.Value);

or in query expression form:

return from t in text.Split(',')
       select TryParseInt32(t) into x
       where x.HasValue
       select x.Value;

How to run DOS/CMD/Command Prompt commands from VB.NET?

Imports System.IO
Public Class Form1
    Public line, counter As String
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        counter += 1
        If TextBox1.Text = "" Then
            MsgBox("Enter a DNS address to ping")
        Else
            'line = ":start" + vbNewLine
            'line += "ping " + TextBox1.Text
            'MsgBox(line)
            Dim StreamToWrite As StreamWriter
            StreamToWrite = New StreamWriter("C:\Desktop\Ping" + counter + ".bat")
            StreamToWrite.Write(":start" + vbNewLine + _
                                "Ping -t " + TextBox1.Text)
            StreamToWrite.Close()
            Dim p As New System.Diagnostics.Process()
            p.StartInfo.FileName = "C:\Desktop\Ping" + counter + ".bat"
            p.Start()
        End If
    End Sub
End Class

This works as well

Hash function that produces short hashes?

It is now 2019 and there are better options. Namely, xxhash.

~ echo test | xxhsum                                                           
2d7f1808da1fa63c  stdin

How can I change a button's color on hover?

a.button:hover{
    background: #383;  }

works for me but in my case

#buttonClick:hover {
background-color:green;  }

Update multiple columns in SQL

Your query is nearly correct. The T-SQL for this is:

UPDATE  Table1
SET     Field1 = Table2.Field1,
        Field2 = Table2.Field2,
        other columns...
FROM    Table2
WHERE   Table1.ID = Table2.ID

Iterating through a List Object in JSP

change the code to the following

<%! List eList = (ArrayList)session.getAttribute("empList");%>
....
<table>
    <%
    for(int i=0; i<eList.length;i++){%>
        <tr>
            <td><%= ((Employee)eList[i]).getEid() %></td>
            <td><%= ((Employee)eList[i]).getEname() %></td>  
        </tr>
      <%}%>
</table>

How to emit an event from parent to child?

As far as I know, there are 2 standard ways you can do that.

1. @Input

Whenever the data in the parent changes, the child gets notified about this in the ngOnChanges method. The child can act on it. This is the standard way of interacting with a child.

Parent-Component
public inputToChild: Object;

Parent-HTML
<child [data]="inputToChild"> </child>       

Child-Component: @Input() data;

ngOnChanges(changes: { [property: string]: SimpleChange }){
   // Extract changes to the input property by its name
   let change: SimpleChange = changes['data']; 
// Whenever the data in the parent changes, this method gets triggered. You 
// can act on the changes here. You will have both the previous value and the 
// current value here.
}
  1. Shared service concept

Creating a service and using an observable in the shared service. The child subscribes to it and whenever there is a change, the child will be notified. This is also a popular method. When you want to send something other than the data you pass as the input, this can be used.

SharedService
subject: Subject<Object>;

Parent-Component
constructor(sharedService: SharedService)
this.sharedService.subject.next(data);

Child-Component
constructor(sharedService: SharedService)
this.sharedService.subject.subscribe((data)=>{

// Whenever the parent emits using the next method, you can receive the data 
in here and act on it.})

Prevent Android activity dialog from closing on outside touch

When using dialog as an activity in the onCreate add this

setFinishOnTouchOutside(false);

How to remove an item from an array in AngularJS scope?

To remove a element from scope use:

// remove an item
    $scope.remove = function(index) {
        $scope.items.splice(index, 1);
    };

From enter link description here

How do I fix "Expected to return a value at the end of arrow function" warning?

A map() creates an array, so a return is expected for all code paths (if/elses).

If you don't want an array or to return data, use forEach instead.

How to convert integer to string in C?

Making your own itoa is also easy, try this :

char* itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char* p = b;
    if(i<0){
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

or use the standard sprintf() function.

Insert text with single quotes in PostgreSQL

According to PostgreSQL documentation (4.1.2.1. String Constants):

 To include a single-quote character within a string constant, write two 
 adjacent single quotes, e.g. 'Dianne''s horse'.

See also the standard_conforming_strings parameter, which controls whether escaping with backslashes works.

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

Old question, but I'd like to provide my own solution which turn out to be the fastest, use normal list instead of np.array as input (or transfer to list firstly), based on my bench test.

Check it out if you encounter it as well.

def count(a):
    results = {}
    for x in a:
        if x not in results:
            results[x] = 1
        else:
            results[x] += 1
    return results

For example,

>>>timeit count([1,1,1,2,2,2,5,25,1,1]) would return:

100000 loops, best of 3: 2.26 µs per loop

>>>timeit count(np.array([1,1,1,2,2,2,5,25,1,1]))

100000 loops, best of 3: 8.8 µs per loop

>>>timeit count(np.array([1,1,1,2,2,2,5,25,1,1]).tolist())

100000 loops, best of 3: 5.85 µs per loop

While the accepted answer would be slower, and the scipy.stats.itemfreq solution is even worse.


A more indepth testing did not confirm the formulated expectation.

from zmq import Stopwatch
aZmqSTOPWATCH = Stopwatch()

aDataSETasARRAY = ( 100 * abs( np.random.randn( 150000 ) ) ).astype( np.int )
aDataSETasLIST  = aDataSETasARRAY.tolist()

import numba
@numba.jit
def numba_bincount( anObject ):
    np.bincount(    anObject )
    return

aZmqSTOPWATCH.start();np.bincount(    aDataSETasARRAY );aZmqSTOPWATCH.stop()
14328L

aZmqSTOPWATCH.start();numba_bincount( aDataSETasARRAY );aZmqSTOPWATCH.stop()
592L

aZmqSTOPWATCH.start();count(          aDataSETasLIST  );aZmqSTOPWATCH.stop()
148609L

Ref. comments below on cache and other in-RAM side-effects that influence a small dataset massively repetitive testing results.

Use of True, False, and None as return values in Python functions

In the case of your fictional getattr function, if the requested attribute always should be available but isn't then throw an error. If the attribute is optional then return None.

Entity Framework - Include Multiple Levels of Properties

I'm going to add my solution to my particular problem. I had two collections at the same level I needed to include. The final solution looked like this.

var recipe = _bartendoContext.Recipes
    .Include(r => r.Ingredients)
    .ThenInclude(r => r.Ingredient)
    .Include(r => r.Ingredients)
    .ThenInclude(r => r.MeasurementQuantity)
    .FirstOrDefault(r => r.Id == recipeId);
if (recipe?.Ingredients == null) return 0m;
var abv = recipe.Ingredients.Sum(ingredient => ingredient.Ingredient.AlcoholByVolume * ingredient.MeasurementQuantity.Quantity);
return abv;

This is calculating the percent alcohol by volume of a given drink recipe. As you can see I just included the ingredients collection twice then included the ingredient and quantity onto that.

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

While you could try these settings in config file

<system.web>
    <httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
    <pages validateRequest="false" />
</system.web>

I would avoid using characters like '&' in URL path replacing them with underscores.

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

Very simple :

In your Super POM parent or setting.xml, use

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

It's my tips

how to print float value upto 2 decimal place without rounding off

The only easy way to do this is to use snprintf to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:

char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);

Creating a 3D sphere in Opengl using Visual C++

Here's the code:

glPushMatrix();
glTranslatef(18,2,0);
glRotatef(angle, 0, 0, 0.7);
glColor3ub(0,255,255);
glutWireSphere(3,10,10);
glPopMatrix();

Open a local HTML file using window.open in Chrome

First, make sure that the source page and the target page are both served through the file URI scheme. You can't force an http page to open a file page (but it works the other way around).

Next, your script that calls window.open() should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open() won't work.

You can test this right here in this question page. Run these in Chrome's JavaScript console:

// Does nothing
window.open('http://google.com');

// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });

// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });

You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    </head>
    <body>
        <h5>Feel the presha</h5>
        <h3>Come play my game, I'll test ya</h3>
        <h1>Psycho- somatic- addict- insane!</h1>
    </body>
</html>

Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.

How do I find what Java version Tomcat6 is using?

To find it from Windows OS,

  1. Open command prompt and change the directory to tomcat/tomee /bin directory.
  2. Type catalina.bat version
  3. It should print jre version details along with other informative details.

    Using CATALINA_BASE: "C:\User\software\enterprise-server-tome...

    Using CATALINA_HOME: "C:\User\software\enterprise-server-tome...

    Using CATALINA_TMPDIR: "C:\User\software\enterprise-server-tome...

    Using JRE_HOME: "C:\Program Files\Java\jdk1.8.0_25"

    Using CLASSPATH: "C:\User\software\enterprise-server-tome...

    Server version: Apache Tomcat/8.5.11

    Server built: Jan 10 2017 21:02:52 UTC

    Server number: 8.5.11.0

    OS Name: Windows 7

    OS Version: 6.1

    Architecture: amd64

    JVM Version: 1.8.0_25-b18

    JVM Vendor: Oracle Corporation

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

These solutions work, but they work for your code ONLY on your machine. I would add a couple of lines to your code that look like this:

import sys
if "C:\\My_Python_Lib" not in sys.path:
    sys.path.append("C:\\My_Python_Lib")

That should take care of your problems

Case-insensitive search in Rails model

If you are using Postegres and Rails 4+, then you have the option of using column type CITEXT, which will allow case insensitive queries without having to write out the query logic.

The migration:

def change
  enable_extension :citext
  change_column :products, :name, :citext
  add_index :products, :name, unique: true # If you want to index the product names
end

And to test it out you should expect the following:

Product.create! name: 'jOgGers'
=> #<Product id: 1, name: "jOgGers">

Product.find_by(name: 'joggers')
=> #<Product id: 1, name: "jOgGers">

Product.find_by(name: 'JOGGERS')
=> #<Product id: 1, name: "jOgGers">

"Initializing" variables in python?

I know you have already accepted another answer, but I think the broader issue needs to addressed - programming style that is suitable to the current language.

Yes, 'initialization' isn't needed in Python, but what you are doing isn't initialization. It is just an incomplete and erroneous imitation of initialization as practiced in other languages. The important thing about initialization in static typed languages is that you specify the nature of the variables.

In Python, as in other languages, you do need to give variables values before you use them. But giving them values at the start of the function isn't important, and even wrong if the values you give have nothing to do with values they receive later. That isn't 'initialization', it's 'reuse'.

I'll make some notes and corrections to your code:

def main():
   # doc to define the function
   # proper Python indentation
   # document significant variables, especially inputs and outputs
   # grade_1, grade_2, grade_3, average - id these
   # year - id this
   # fName, lName, ID, converted_ID 

   infile = open("studentinfo.txt", "r") 
   # you didn't 'intialize' this variable

   data = infile.read()  
   # nor this  

   fName, lName, ID, year = data.split(",")
   # this will produce an error if the file does not have the right number of strings
   # 'year' is now a string, even though you 'initialized' it as 0

   year = int(year)
   # now 'year' is an integer
   # a language that requires initialization would have raised an error
   # over this switch in type of this variable.

   # Prompt the user for three test scores
   grades = eval(input("Enter the three test scores separated by a comma: "))
   # 'eval' ouch!
   # you could have handled the input just like you did the file input.

   grade_1, grade_2, grade_3 = grades   
   # this would work only if the user gave you an 'iterable' with 3 values
   # eval() doesn't ensure that it is an iterable
   # and it does not ensure that the values are numbers. 
   # What would happen with this user input: "'one','two','three',4"?

   # Create a username 
   uName = (lName[:4] + fName[:2] + str(year)).lower()

   converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
   # earlier you 'initialized' converted_ID
   # initialization in a static typed language would have caught this typo
   # pseudo-initialization in Python does not catch typos
   ....

How do I get Flask to run on port 80?

Easiest and Best Solution

Save your .py file in a folder. This case my folder name is test. In the command prompt run the following

c:\test> set FLASK_APP=application.py
c:\test> set FLASK_RUN_PORT=8000
c:\test> flask run

----------------- Following will be returned ----------------

 * Serving Flask app "application.py"
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/Aug/2019 09:40:04] "[37mGET / HTTP/1.1[0m" 200 -
127.0.0.1 - - [23/Aug/2019 09:40:04] "[33mGET /favicon.ico HTTP/1.1[0m" 404 -

Now on your browser type: http://127.0.0.1:8000. Thanks

How to tell Jackson to ignore a field during serialization if its value is null?

in my case

@JsonInclude(Include.NON_EMPTY)

made it work.

Assembly Language - How to do Modulo?

If you don't care too much about performance and want to use the straightforward way, you can use either DIV or IDIV.

DIV or IDIV takes only one operand where it divides a certain register with this operand, the operand can be register or memory location only.

When operand is a byte: AL = AL / operand, AH = remainder (modulus).

Ex:

MOV AL,31h ; Al = 31h

DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h

when operand is a word: AX = (AX) / operand, DX = remainder (modulus).

Ex:

MOV AX,9031h ; Ax = 9031h

DIV BX ; Ax=1808h & Dx(remainder)= 01h

How to completely uninstall Visual Studio 2010?

The only real clean way to uninstall VS (Visual Studio, whatever version it is) is to completely reinstall the whole OS. If you don't, more compatibility problems might surface.

Permanent solution

Starting from scratch (clean install, VS never installed on the OS), the best way to avoid all those problems is to install and run VS from a VM (virtual machine) as stated by Default in the comments above. This way, and as long as Microsoft doesn't do anything to improve its whole platform to be more user-friendly, switching from a version to another will be quick and easy and the main partition of the HDD (or SSD in my case) won't be filed with all the garbage that VS leaves behind.

Of course, the disadvantage is speed. The program will be slower in pretty much every way. But honestly, who uses VS for its speed? Even on the latest enthusiast-platforms, it takes ages to install. Even if VS might start up faster on a high-end SSD, it's just slow.

Run Function After Delay

You can add timeout function in jQuery (Show alert after 3 seconds):

$(document).ready(function($) {
    setTimeout(function() {
     alert("Hello");
    }, 3000);
});

Getting Python error "from: can't read /var/mail/Bio"

No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py, you have to execute it as python script.py, otherwise the default shell will execute it and it will bail out at the from keyword. (Incidentally, from is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).

Another possibility is to add the following line to the top of the script:

#!/usr/bin/env python

This will instruct your shell to execute the script via python instead of trying to interpret it on its own.

How to skip "are you sure Y/N" when deleting files in batch files

You have the following options on Windows command line:

net use [DeviceName [/home[{Password | *}] [/delete:{yes | no}]]

Try like:

net use H: /delete /y

Angular - res.json() is not a function

Had a similar problem where we wanted to update from deprecated Http module to HttpClient in Angular 7. But the application is large and need to change res.json() in a lot of places. So I did this to have the new module with back support.

return this.http.get(this.BASE_URL + url)
      .toPromise()
      .then(data=>{
        let res = {'results': JSON.stringify(data),
        'json': ()=>{return data;}
      };
       return res; 
      })
      .catch(error => {
        return Promise.reject(error);
      });

Adding a dummy "json" named function from the central place so that all other services can still execute successfully before updating them to accommodate a new way of response handling i.e. without "json" function.

How to capture no file for fs.readFileSync()?

I use an immediately invoked lambda for these scenarios:

const config = (() => {
  try {
    return JSON.parse(fs.readFileSync('config.json'));
  } catch (error) {
    return {};
  }
})();

async version:

const config = await (async () => {
  try {
    return JSON.parse(await fs.readFileAsync('config.json'));
  } catch (error) {
    return {};
  }
})();

why windows 7 task scheduler task fails with error 2147942667

For a more generic answer, convert the error value to hex, then lookup the hex value at Windows Task Scheduler Error and Success Constants

Getting files by creation date in .NET

            DirectoryInfo dirinfo = new DirectoryInfo(strMainPath);
            String[] exts = new string[] { "*.jpeg", "*.jpg", "*.gif", "*.tiff", "*.bmp","*.png", "*.JPEG", "*.JPG", "*.GIF", "*.TIFF", "*.BMP","*.PNG" };
            ArrayList files = new ArrayList();
            foreach (string ext in exts)
                files.AddRange(dirinfo.GetFiles(ext).OrderBy(x => x.CreationTime).ToArray());

What is the .idea folder?

There is no problem in deleting this. It's not only the WebStorm IDE creating this file, but also PhpStorm and all other of JetBrains' IDEs.

It is safe to delete it but if your project is from GitLab or GitHub then you will see a warning.

Why would I use dirname(__FILE__) in an include or include_once statement?

If you want code is running on multiple servers with different environments,then we have need to use dirname(FILE) in an include or include_once statement. reason is follows. 1. Do not give absolute path to include files on your server. 2. Dynamically calculate the full path like absolute path.

Use a combination of dirname(FILE) and subsequent calls to itself until you reach to the home of your '/myfile.php'. Then attach this variable that contains the path to your included files.

How to check if image exists with given url?

To handle the lazy loading with image existence check I followed this in jQuery-

$('[data-src]').each(function() {
  var $image_place_holder_element = $(this);
  var image_url = $(this).data('src');
  $("<div class='hidden-classe' />").load(image_url, function(response, status, xhr) {
    if (!(status == "error")) {
      $image_place_holder_element.removeClass('image-placeholder');
      $image_place_holder_element.attr('src', image_url);
    }
  }).remove();
});

Reason: if I am using $image_place_holder_element.load() method it will be adding the response to the element, so random div and removing it appeared me a good solution. Hope it works for someone trying to implement lazy loading along with url check.

How to select the last column of dataframe

df.T.iloc[-1]

df.T.tail(1)

pd.Series(df.values[:, -1], name=df.columns[-1])

Run a single test method with maven

This command works !! mvn "-DTest=JoinTeamTestCases#validateJoinTeam" test Note that "-DTest" starts with UPPER CASE 'T'.

SQL SELECT from multiple tables

SELECT pid, cid, pname, name1, name2 
FROM customer1 c1, product p 
WHERE p.cid=c1.cid 
UNION SELECT pid, cid, pname, name1, name2 
FROM customer2 c2, product p 
WHERE p.cid=c2.cid;

How to retrieve images from MySQL database and display in an html tag

You need to retrieve and disect the information into what you need.

while($row = mysql_fetch_array($result)) {
 echo "img src='",$row['filename'],"' width='175' height='200' />";
}

Convert timestamp to readable date/time PHP

$epoch = 1483228800;
$dt = new DateTime("@$epoch");  // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00

In the examples above "r" and "Y-m-d H:i:s" are PHP date formats, other examples:

Format Output

r              -----    Wed, 15 Mar 2017 12:00:00 +0100 (RFC 2822 date)
c              -----    2017-03-15T12:00:00+01:00 (ISO 8601 date)
M/d/Y          -----    Mar/15/2017
d-m-Y          -----    15-03-2017
Y-m-d H:i:s    -----    2017-03-15 12:00:00

Interfaces — What's the point?

I share your sense that Interfaces are not necessary. Here is a quote from Cwalina pg 80 Framework Design Guidelines "I often here people saying that interfaces specify contracts. I believe this a dangerous myth. Interfaces by themselves do not specify much. ..." He and co-author Abrams managed 3 releases of .Net for Microsoft. He goes on to say that the 'contract' is "expressed" in an implementation of the class. IMHO watching this for decades, there were many people warning Microsoft that taking the engineering paradigm to the max in OLE/COM might seem good but its usefulness is more directly to hardware. Especially in a big way in the 80s and 90s getting interoperating standards codified. In our TCP/IP Internet world there is little appreciation of the hardware and software gymnastics we would jump through to get solutions 'wired up' between and among mainframes, minicomputers, and microprocessors of which PCs were just a small minority. So coding to interfaces and their protocols made computing work. And interfaces ruled. But what does solving making X.25 work with your application have in common with posting recipes for the holidays? I have been coding C++ and C# for many years and I never created one once.

Multiline strings in VB.NET

If you need an XML literal in VB.Net with an line code variable, this is how you would do it:

<Tag><%= New XCData(T.Property) %></Tag>

How to check a string against null in java?

Of course user351809, stringname.equalsignorecase(null) will throw NullPointerException.
See, you have a string object stringname, which follows 2 possible conditions:-

  1. stringname has a some non-null string value (say "computer"):
    Your code will work fine as it takes the form
    "computer".equalsignorecase(null)
    and you get the expected response as false.
  2. stringname has a null value:
    Here your code will get stuck, as
    null.equalsignorecase(null)
    However, seems good at first look and you may hope response as true,
    but, null is not an object that can execute the equalsignorecase() method.

Hence, you get the exception due to case 2.
What I suggest you is to simply use stringname == null

Why is jquery's .ajax() method not sending my session cookie?

I am operating in cross-domain scenario. During login remote server is returning Set-Cookie header along with Access-Control-Allow-Credentials set to true.

The next ajax call to remote server should use this cookie.

CORS's Access-Control-Allow-Credentials is there to allow cross-domain logging. Check https://developer.mozilla.org/En/HTTP_access_control for examples.

For me it seems like a bug in JQuery (or at least feature-to-be in next version).

UPDATE:

  1. Cookies are not set automatically from AJAX response (citation: http://aleembawany.com/2006/11/14/anatomy-of-a-well-designed-ajax-login-experience/)

    Why?

  2. You cannot get value of the cookie from response to set it manually (http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-getresponseheader)

    I'm confused..

    There should exist a way to ask jquery.ajax() to set XMLHttpRequest.withCredentials = "true" parameter.

ANSWER: You should use xhrFields param of http://api.jquery.com/jQuery.ajax/

The example in the documentation is:

$.ajax({
   url: a_cross_domain_url,
   xhrFields: {
      withCredentials: true
   }
});

It's important as well that server answers correctly to this request. Copying here great comments from @Frédéric and @Pebbl:

Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding. The above example would fail if the header was wildcarded as: Access-Control-Allow-Origin: *

So when the request is:

Origin: http://foo.example
Cookie: pageAccess=2

Server should respond with:

Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Credentials: true

[payload]

Otherwise payload won't be returned to script. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials

Return index of greatest value in an array

_x000D_
_x000D_
 var arr=[0,6,7,7,7];_x000D_
 var largest=[0];_x000D_
 //find the largest num;_x000D_
 for(var i=0;i<arr.length;i++){_x000D_
   var comp=(arr[i]-largest[0])>0;_x000D_
      if(comp){_x000D_
   largest =[];_x000D_
   largest.push(arr[i]);_x000D_
   }_x000D_
 }_x000D_
 alert(largest )//7_x000D_
 _x000D_
 //find the index of 'arr'_x000D_
 var arrIndex=[];_x000D_
 for(var i=0;i<arr.length;i++){_x000D_
    var comp=arr[i]-largest[0]==0;_x000D_
 if(comp){_x000D_
 arrIndex.push(i);_x000D_
 }_x000D_
 }_x000D_
 alert(arrIndex);//[2,3,4]
_x000D_
_x000D_
_x000D_

get everything between <tag> and </tag> with php

$regex = '#<code>(.*?)</code>#';

Using # as the delimiter instead of / because then we don't need to escape the / in </code>

As Phoenix posted below, .*? is used to make the .* ("anything") match as few characters as possible before it comes across a </code> (known as a "non-greedy quantifier"). That way, if your string is

<code>hello</code> something <code>again</code>

you'll match hello and again instead of just matching hello</code> something <code>again.

How to get the azure account tenant Id?

Use the Azure CLI

az account get-access-token --query tenant --output tsv

How to serialize Object to JSON?

One can use the Jackson library as well.

Add Maven Dependency:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId> 
  <artifactId>jackson-core</artifactId>
</dependency>

Simply do this:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString( serializableObject );

Angular JS - angular.forEach - How to get key of the object?

The first parameter to the iterator in forEach is the value and second is the key of the object.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});

In your example, the outer forEach is actually:

angular.forEach($scope.filters, function(filterObj , filterKey)

Postgresql query between date ranges

Just in case somebody land here... since 8.1 you can simply use:

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'

From the docs:

BETWEEN SYMMETRIC is the same as BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right. If it is not, those two arguments are automatically swapped, so that a nonempty range is always implied.

Oracle query execution time

I'd recommend looking at consistent gets/logical reads as a better proxy for 'work' than run time. The run time can be skewed by what else is happening on the database server, how much stuff is in the cache etc.

But if you REALLY want SQL executing time, the V$SQL view has both CPU_TIME and ELAPSED_TIME.

Is < faster than <=?

They have the same speed. Maybe in some special architecture what he/she said is right, but in the x86 family at least I know they are the same. Because for doing this the CPU will do a substraction (a - b) and then check the flags of the flag register. Two bits of that register are called ZF (zero Flag) and SF (sign flag), and it is done in one cycle, because it will do it with one mask operation.

Adding +1 to a variable inside a function

points is not within the function's scope. You can grab a reference to the variable by using nonlocal:

points = 0
def test():
    nonlocal points
    points += 1

If points inside test() should refer to the outermost (module) scope, use global:

points = 0
def test():
    global points
    points += 1

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

What is an opaque response, and what purpose does it serve?

There's also solution for Node JS app. CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.

The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".

This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example to avoid a direct visit from the browser. https://robwu.nl/cors-anywhere.html

Calculate average in java

Instead of:

int count = 0;
for (int i = 0; i<args.length -1; ++i)
    count++;
System.out.println(count);

 }

you can just

int count = args.length;

The average is the sum of your args divided by the number of your args.

int res = 0;
int count = args.lenght;

for (int a : args)
{
res += a;
}
res /= count;

you can make this code shorter too, i'll let you try and ask if you need help!

This is my first answerso tell me if something wrong!

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

Use the auto keyword in C++ STL

If you want a code that is readable by all programmers (c++, java, and others) use the original old form instead of cryptographic new features

atp::ta::DataDrawArrayInfo* ddai;
for(size_t i = 0; i < m_dataDraw->m_dataDrawArrayInfoList.size(); i++) {
    ddai = m_dataDraw->m_dataDrawArrayInfoList[i];
    //...
}

How do I clone a github project to run locally?

I use @Thiho answer but i get this error:

'git' is not recognized as an internal or external command

For solving that i use this steps:

I add the following paths to PATH:

  • C:\Program Files\Git\bin\

  • C:\Program Files\Git\cmd\

In windows 7:

  1. Right-click "Computer" on the Desktop or Start Menu.
  2. Select "Properties".
  3. On the very far left, click the "Advanced system settings" link.
  4. Click the "Environment Variables" button at the bottom.
  5. Double-click the "Path" entry under "System variables".
  6. At the end of "Variable value", insert a ; if there is not already one, and then C:\Program Files\Git\bin\;C:\Program Files\Git\cmd. Do not put a space between ; and the entry.

Finally close and re-open your console.

Allow all remote connections, MySQL

As pointed out by Ryan above, the command you need is

GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password'; 

However, note that the documentation indicates that in order for this to work, another user account from localhost must be created for the same user; otherwise, the anonymous account created automatically by mysql_install_db takes precedence because it has a more specific host column.

In other words; in order for user user to be able to connect from any server; 2 accounts need to be created as follows:

GRANT ALL ON *.* to user@localhost IDENTIFIED BY 'password'; 
GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password'; 

Read the full documentation here.

And here's the relevant piece for reference:

After connecting to the server as root, you can add new accounts. The following statements use GRANT to set up four new accounts:

mysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'admin'@'localhost';
mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
mysql> CREATE USER 'dummy'@'localhost';

The accounts created by these statements have the following properties:

Two of the accounts have a user name of monty and a password of some_pass. Both accounts are superuser accounts with full privileges to do anything. The 'monty'@'localhost' account can be used only when connecting from the local host. The 'monty'@'%' account uses the '%' wildcard for the host part, so it can be used to connect from any host.

It is necessary to have both accounts for monty to be able to connect from anywhere as monty. Without the localhost account, the anonymous-user account for localhost that is created by mysql_install_db would take precedence when monty connects from the local host. As a result, monty would be treated as an anonymous user. The reason for this is that the anonymous-user account has a more specific Host column value than the 'monty'@'%' account and thus comes earlier in the user table sort order. (user table sorting is discussed in Section 6.2.4, “Access Control, Stage 1: Connection Verification”.)

Is there a Google Chrome-only CSS hack?

Sure is:

@media screen and (-webkit-min-device-pixel-ratio:0)
{ 
    #element { properties:value; } 
}

And a little fiddle to see it in action - http://jsfiddle.net/Hey7J/

Must add tho... this is generally bad practice, you shouldn't really be at the point where you start to need individual browser hacks to make you CSS work. Try using reset style sheets at the start of your project, to help avoid this.

Also, these hacks may not be future proof.

Converting int to bytes in Python 3

I was curious about performance of various methods for a single int in the range [0, 255], so I decided to do some timing tests.

Based on the timings below, and from the general trend I observed from trying many different values and configurations, struct.pack seems to be the fastest, followed by int.to_bytes, bytes, and with str.encode (unsurprisingly) being the slowest. Note that the results show some more variation than is represented, and int.to_bytes and bytes sometimes switched speed ranking during testing, but struct.pack is clearly the fastest.

Results in CPython 3.7 on Windows:

Testing with 63:
bytes_: 100000 loops, best of 5: 3.3 usec per loop
to_bytes: 100000 loops, best of 5: 2.72 usec per loop
struct_pack: 100000 loops, best of 5: 2.32 usec per loop
chr_encode: 50000 loops, best of 5: 3.66 usec per loop

Test module (named int_to_byte.py):

"""Functions for converting a single int to a bytes object with that int's value."""

import random
import shlex
import struct
import timeit

def bytes_(i):
    """From Tim Pietzcker's answer:
    https://stackoverflow.com/a/21017834/8117067
    """
    return bytes([i])

def to_bytes(i):
    """From brunsgaard's answer:
    https://stackoverflow.com/a/30375198/8117067
    """
    return i.to_bytes(1, byteorder='big')

def struct_pack(i):
    """From Andy Hayden's answer:
    https://stackoverflow.com/a/26920966/8117067
    """
    return struct.pack('B', i)

# Originally, jfs's answer was considered for testing,
# but the result is not identical to the other methods
# https://stackoverflow.com/a/31761722/8117067

def chr_encode(i):
    """Another method, from Quuxplusone's answer here:
    https://codereview.stackexchange.com/a/210789/140921

    Similar to g10guang's answer:
    https://stackoverflow.com/a/51558790/8117067
    """
    return chr(i).encode('latin1')

converters = [bytes_, to_bytes, struct_pack, chr_encode]

def one_byte_equality_test():
    """Test that results are identical for ints in the range [0, 255]."""
    for i in range(256):
        results = [c(i) for c in converters]
        # Test that all results are equal
        start = results[0]
        if any(start != b for b in results):
            raise ValueError(results)

def timing_tests(value=None):
    """Test each of the functions with a random int."""
    if value is None:
        # random.randint takes more time than int to byte conversion
        # so it can't be a part of the timeit call
        value = random.randint(0, 255)
    print(f'Testing with {value}:')
    for c in converters:
        print(f'{c.__name__}: ', end='')
        # Uses technique borrowed from https://stackoverflow.com/q/19062202/8117067
        timeit.main(args=shlex.split(
            f"-s 'from int_to_byte import {c.__name__}; value = {value}' " +
            f"'{c.__name__}(value)'"
        ))

Best way to verify string is empty or null

Just to show java 8's stance to remove null values.

String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
    ...
}

Makes sense if you can use Optional<String>.

Center an element with "absolute" position and undefined width in CSS?

Flexbox can be used to center an absolute positioned div.

display: flex;
align-items: center;
justify-content: center;

_x000D_
_x000D_
.relative {
  width: 275px;
  height: 200px;
  background: royalblue;
  color: white;
  margin: auto;
  position: relative;
}

.absolute-block {
  position: absolute;
  height: 36px;
  background: orange;
  padding: 0px 10px;
  bottom: -5%;
  border: 1px solid black;
}

.center-text {
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 1px 2px 10px 2px rgba(0, 0, 0, 0.3);
}
_x000D_
<div class="relative center-text">
  Relative Block
  <div class="absolute-block center-text">Absolute Block</div>
</div>
_x000D_
_x000D_
_x000D_

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

Getting the ID of the element that fired an event

In the case of delegated event handlers, where you might have something like this:

<ul>
    <li data-id="1">
        <span>Item 1</span>
    </li>
    <li data-id="2">
        <span>Item 2</span>
    </li>
    <li data-id="3">
        <span>Item 3</span>
    </li>
    <li data-id="4">
        <span>Item 4</span>
    </li>
    <li data-id="5">
        <span>Item 5</span>
    </li>
</ul>

and your JS code like so:

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target),
            itemId = $target.data('id');

        //do something with itemId
    });
});

You'll more than likely find that itemId is undefined, as the content of the LI is wrapped in a <span>, which means the <span> will probably be the event target. You can get around this with a small check, like so:

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target).is('li') ? $(event.target) : $(event.target).closest('li'),
            itemId = $target.data('id');

        //do something with itemId
    });
});

Or, if you prefer to maximize readability (and also avoid unnecessary repetition of jQuery wrapping calls):

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target),
            itemId;

        $target = $target.is('li') ? $target : $target.closest('li');
        itemId = $target.data('id');

        //do something with itemId
    });
});

When using event delegation, the .is() method is invaluable for verifying that your event target (among other things) is actually what you need it to be. Use .closest(selector) to search up the DOM tree, and use .find(selector) (generally coupled with .first(), as in .find(selector).first()) to search down it. You don't need to use .first() when using .closest(), as it only returns the first matching ancestor element, while .find() returns all matching descendants.

VBA copy rows that meet criteria to another sheet

You need to specify workseet. Change line

If Worksheet.Cells(i, 1).Value = "X" Then

to

If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then

UPD:

Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

   'Find the last used row in a Column: column A in this example
   With Worksheets("Sheet2")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

   MsgBox (LastRow)
   'first row number where you need to paste values in Sheet1'
   With Worksheets("Sheet1")
      j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
   End With 

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

Is it possible to CONTINUE a loop from an exception?

The CONTINUE statement is a new feature in 11g.

Here is a related question: 'CONTINUE' keyword in Oracle 10g PL/SQL

Can jQuery check whether input content has changed?

You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):

$(document).ready(function() {  
    $("#fieldId").bind("keyup keydown keypress change blur", function() {
        if ($(this).val() != jQuery.data(this, "lastvalue") {
         alert("changed");
        }
        jQuery.data(this, "lastvalue", $(this).val());
    });
});

This would work pretty good against a long list of items too. Using jQuery.data means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc") to track many fields.

UPDATE: Added blur to the bind list.

Explanation of "ClassCastException" in Java

Straight from the API Specifications for the ClassCastException:

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.

Object i = Integer.valueOf(42);
String s = (String)i;            // ClassCastException thrown here.

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

What is an efficient way to implement a singleton pattern in Java?

Sometimes a simple "static Foo foo = new Foo();" is not enough. Just think of some basic data insertion you want to do.

On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is

public class Singleton {

    private static Singleton instance = null;

    static {
          instance = new Singleton();
          // do some of your instantiation stuff here
    }

    private Singleton() {
          if(instance!=null) {
                  throw new ErrorYouWant("Singleton double-instantiation, should never happen!");
          }
    }

    public static getSingleton() {
          return instance;
    }

}

Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the static { } - block. that's the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.

Is there anyway to exclude artifacts inherited from a parent POM?

Redefine the dependency (in the child pom) with scope system pointing to an empty jar :

<dependency>
    <groupId>dependency.coming</groupId>
    <artifactId>from.parent</artifactId>
    <version>0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/empty.jar</systemPath>
</dependency>

The jar can contain just a single empty file :

touch empty.txt
jar cvf empty.txt

JWT (JSON Web Token) automatic prolongation of expiration

Today, lots of people opt for doing session management with JWTs without being aware of what they are giving up for the sake of perceived simplicity. My answer elaborates on the 2nd part of the questions:

What is the real benefit then? Why not have only one token (not JWT) and keep the expiration on the server?

Are there other options? Is using JWT not suited for this scenario?

JWTs are capable of supporting basic session management with some limitations. Being self-describing tokens, they don't require any state on the server-side. This makes them appealing. For instance, if the service doesn't have a persistence layer, it doesn't need to bring one in just for session management.

However, statelessness is also the leading cause of their shortcomings. Since they are only issued once with fixed content and expiration, you can't do things you would like to with a typical session management setup.

Namely, you can't invalidate them on-demand. This means you can't implement a secure logout as there is no way to expire already issued tokens. You also can't implement idle timeout for the same reason. One solution is to keep a blacklist, but that introduces state.

I wrote a post explaining these drawbacks in more detail. To be clear, you can work around these by adding more complexity (sliding sessions, refresh tokens, etc.)

As for other options, if your clients only interact with your service via a browser, I strongly recommend using a cookie-based session management solution. I also compiled a list authentication methods currently widely used on the web.

How to clear the logs properly for a Docker container?

You can set up logrotate to clear the logs periodically.

Example file in /etc/logrotate.d/docker-logs

/var/lib/docker/containers/*/*.log {
 rotate 7
 daily
 compress
 size=50M
 missingok
 delaycompress
 copytruncate
}

How to combine two lists in R

c can be used on lists (and not only on vectors):

# you have
l1 = list(2, 3)
l2 = list(4)

# you want
list(2, 3, 4)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

# you can do
c(l1, l2)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

If you have a list of lists, you can do it (perhaps) more comfortably with do.call, eg:

do.call(c, list(l1, l2))

Add a border outside of a UIView (instead of inside)

Increase the width and height of view's frame with border width before adding the border:

float borderWidth = 2.0f
CGRect frame = self.frame;
frame.width += borderWidth;
frame.height += borderWidth;
 self.layer.borderColor = [UIColor yellowColor].CGColor;
 self.layer.borderWidth = 2.0f;

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Can local storage ever be considered secure?

Well, the basic premise here is: no, it is not secure yet.

Basically, you can't run crypto in JavaScript: JavaScript Crypto Considered Harmful.

The problem is that you can't reliably get the crypto code into the browser, and even if you could, JS isn't designed to let you run it securely. So until browsers have a cryptographic container (which Encrypted Media Extensions provide, but are being rallied against for their DRM purposes), it will not be possible to do securely.

As far as a "Better way", there isn't one right now. Your only alternative is to store the data in plain text, and hope for the best. Or don't store the information at all. Either way.

Either that, or if you need that sort of security, and you need local storage, create a custom application...

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html

geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.

ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()

GUI-based or Web-based JSON editor that works like property explorer

Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.

Based on JSON Schema

Commercial (No endorsement intended or implied, may or may not meet requirement)

jQuery

YAML

See Also

Disable button in angular with two conditions?

It sounds like you need an OR instead:

<button type="submit" [disabled]="!validate || !SAForm.valid">Add</button>

This will disable the button if not validate or if not SAForm.valid.

Change a Rails application to production

By default server runs on development environment: $ rails s

If you're running on production environment: $ rails s -e production or $ RAILS_ENV=production rails s

How can I get Android Wifi Scan Results into a list?

Find a complete working example below:

The code by @Android is very good but has few issues, namely:

  1. Populating to ListView code needs to be moved to onReceive of BroadCastReceiver where only the result will be available. In the case result is obtained at 2nd attempt.
  2. BroadCastReceiver needs to be unregistered after the results are obtained.
  3. size = size -1 seems unnecessary.

Find below the modified code of @Android as a working example:

WifiScanner.java which is the Main Activity

package com.arjunandroid.wifiscanner;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class WifiScanner extends Activity implements View.OnClickListener{


    WifiManager wifi;
    ListView lv;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<String> arraylist = new ArrayList<>();
    ArrayAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getActionBar().setTitle("Widhwan Setup Wizard");

        setContentView(R.layout.activity_wifi_scanner);

        buttonScan = (Button) findViewById(R.id.scan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.wifilist);


        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }
        this.adapter =  new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arraylist);
        lv.setAdapter(this.adapter);

        scanWifiNetworks();
    }

    public void onClick(View view)
    {
        scanWifiNetworks();
    }

    private void scanWifiNetworks(){

        arraylist.clear();
        registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        wifi.startScan();

        Log.d("WifScanner", "scanWifiNetworks");

        Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();

    }

    BroadcastReceiver wifi_receiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context c, Intent intent)
        {
            Log.d("WifScanner", "onReceive");
            results = wifi.getScanResults();
            size = results.size();
            unregisterReceiver(this);

            try
            {
                while (size >= 0)
                {
                    size--;
                    arraylist.add(results.get(size).SSID);
                    adapter.notifyDataSetChanged();
                }
            }
            catch (Exception e)
            {
                Log.w("WifScanner", "Exception: "+e);

            }


        }
    };

}

activity_wifi_scanner.xml which is the layout file for the Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/wifilist"
        android:layout_width="match_parent"
        android:layout_height="312dp"
        android:layout_weight="0.97" />


    <Button
        android:id="@+id/scan"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="bottom"
        android:layout_margin="15dp"
        android:background="@android:color/holo_green_light"
        android:text="Scan Again" />
</LinearLayout>

Also as mentioned above, do not forget to add Wifi permissions in the AndroidManifest.xml

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

How do I float a div to the center?

You can do it inline like this

<div style="margin:0px auto"></div>

or you can do it via class

<div class="x"><div>

in your css file or between <style></style> add this .x{margin:0px auto}

or you can simply use the center tag

  <center>
    <div></div>
  </center>

or if you using absolute position, you can do

.x{
   width: 140px;
   position: absolute;
   top: 0px;
   left: 50%;
   margin-left: -70px; /*half the size of width*/
}

Pass object to javascript function

when you pass an object within curly braces as an argument to a function with one parameter , you're assigning this object to a variable which is the parameter in this case

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...

UPDATE:

Apparently this syntax is only available starting on SQL Server 2008.

How to view user privileges using windows cmd?

Use whoami /priv command to list all the user privileges.

"Could not find a version that satisfies the requirement opencv-python"

I faced the same issue but the mistake which I was making was pip install python-opencv where I should have used pip install opencv-python. Hope this helps to anyone. It took me few hours to find.

Why Is `Export Default Const` invalid?

If the component name is explained in the file name MyComponent.js, just don't name the component, keeps code slim.

import React from 'react'

export default (props) =>
    <div id='static-page-template'>
        {props.children}
    </div>

Update: Since this labels it as unknown in stack tracing, it isn't recommended

How can I change cols of textarea in twitter-bootstrap?

Another option is to split off the textarea in the Site.css as follows:

/* Set width on the form input elements since they're 100% wide by default */

input,
select {

  max-width: 280px;
}

textarea {

  /*max-width: 280px;*/
  max-width: 500px;
  width: 280px;
  height: 200px;
}

also (in my MVC 5) add ref to textarea:

@Html.TextAreaFor(model => ................... @class = "form-control", @id="textarea"............

It worked for me

Prevent any form of page refresh using jQuery/Javascript

Issue #2 now can be solved using BroadcastAPI.

At the moment it's only available in Chrome, Firefox, and Opera.

var bc = new BroadcastChannel('test_channel');

bc.onmessage = function (ev) { 
    if(ev.data && ev.data.url===window.location.href){
       alert('You cannot open the same page in 2 tabs');
    }
}

bc.postMessage(window.location.href);

Uncaught SyntaxError: Unexpected token < On Chrome

change it to

$.post({ 
         url = 'getData.php',  
         data : { 'id' id } , 
         dataType : 'text'
       });

This way ajax will not try to parse the data into json or similar

Regular expression for matching latitude/longitude coordinates?

A complete and simple method in objective C for checking correct pattern for latitude and longitude is:

 -( BOOL )textIsValidValue:(NSString*) searchedString
{
    NSRange   searchedRange = NSMakeRange(0, [searchedString length]);
    NSError  *error = nil;
    NSString *pattern = @"^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?),\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$";
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern options:0 error:&error];
    NSTextCheckingResult *match = [regex firstMatchInString:searchedString options:0 range: searchedRange];
    return match ? YES : NO;
}

where searchedString is the input that user would enter in the respective textfield.

Unclosed Character Literal error

Java uses double quotes for "String" and single quotes for 'C'haracters.

Check if a string is palindrome

Note that reversing the whole string (either with the rbegin()/rend() range constructor or with std::reverse) and comparing it with the input would perform unnecessary work.

It's sufficient to compare the first half of the string with the latter half, in reverse:

#include <string>
#include <algorithm>
#include <iostream>
int main()
{
    std::string s;
    std::cin >> s;
    if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
        std::cout << "is a palindrome.\n";
    else
        std::cout << "is NOT a palindrome.\n";
}

demo: http://ideone.com/mq8qK

Creating an Instance of a Class with a variable in Python

Given your edit i assume you have the class name as a string and want to instantiate the class? Just use a dictionary as a dispatcher.

class Foo(object):
    pass

class Bar(object):
    pass

dispatch_dict = {"Foo": Foo, "Bar": Bar}
dispatch_dict["Foo"]() # returns an instance of Foo

Cross-Origin Request Headers(CORS) with PHP headers

Many description internet-wide don't mention that specifying Access-Control-Allow-Origin is not enough. Here is a complete example that works for me:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
        header('Access-Control-Allow-Headers: token, Content-Type');
        header('Access-Control-Max-Age: 1728000');
        header('Content-Length: 0');
        header('Content-Type: text/plain');
        die();
    }

    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');

    $ret = [
        'result' => 'OK',
    ];
    print json_encode($ret);

Best way to extract a subvector from a vector?

You can use STL copy with O(M) performance when M is the size of the subvector.

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

If you need to actually replace the td you are selecting from the DOM, then you need to first go to the parentNode, then replace the contents replace the innerHTML with a new html string representing what you want. The trick is converting the first-table-cell to a string so you can then use it in a string replace method.

I added a fiddle example: http://jsfiddle.net/vzUF4/

<table><tr><td id="first-table-cell">0</td><td>END</td></tr></table>

<script>
  var firstTableCell = document.getElementById('first-table-cell');
  var tableRow = firstTableCell.parentNode;
  // Create a separate node used to convert node into string.
  var renderingNode = document.createElement('tr');
  renderingNode.appendChild(firstTableCell.cloneNode(true));
  // Do a simple string replace on the html
  var stringVersionOfFirstTableCell = renderingNode.innerHTML;
  tableRow.innerHTML = tableRow.innerHTML.replace(stringVersionOfFirstTableCell,
    '<td>0</td><td>1</td>');
</script>

A lot of the complexity here is that you are mixing DOM methods with string methods. If DOM methods work for your application, it would be much bette to use those. You can also do this with pure DOM methods (document.createElement, removeChild, appendChild), but it takes more lines of code and your question explicitly said you wanted to use a string.

How to save DataFrame directly to Hive?

Saving to Hive is just a matter of using write() method of your SQLContext:

df.write.saveAsTable(tableName)

See https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/DataFrameWriter.html#saveAsTable(java.lang.String)

From Spark 2.2: use DataSet instead DataFrame.

Add a properties file to IntelliJ's classpath

If you ever end up with the same problem with Scala and SBT:

  • Go to Project Structure. The shortcut is (CTRL + ALT + SHIFT + S)

  • On the far left list, choose Project Settings > Modules

  • On the module list right of that, select the module of your project name (without the build) and choose the sources tab

  • In middle, expand the folder that the root of your project for me that's /home/<username>/IdeaProjects/<projectName>

  • Look at the Content Root section on the right side, the red paths are directories that you haven't made. You'll want to put the properties file in a Resources directory. So I created src/main/resources and put log4j.properties in it. I believe you can also modify the Content Root to put it wherever you want (I didn't do this).

  • I ran my code with a SBT configuration and it found my log4j.properties file.

enter image description here

Git undo changes in some files

Yes;

git commit FILE

will commit just FILE. Then you can use

git reset --hard

to undo local changes in other files.

There may be other ways too that I don't know about...

edit: or, as NicDumZ said, git-checkout just the files you want to undo the changes on (the best solution depends on wether there are more files to commit or more files to undo :-)

How can I pause setInterval() functions?

i wrote a simple ES6 class that may come handy. inspired by https://stackoverflow.com/a/58580918/4907364 answer

export class IntervalTimer {
    private callbackStartTime;
    private remaining= 0;
    private paused= false;
    public timerId = null;
    private readonly _callback;
    private readonly _delay;

    constructor(callback, delay) {
        this._callback = callback;
        this._delay = delay;
    }

    pause() {
        if (!this.paused) {
            this.clear();
            this.remaining = new Date().getTime() - this.callbackStartTime;
            this.paused = true;
        }
    }

    resume() {
        if (this.paused) {
            if (this.remaining) {
                setTimeout(() => {
                    this.run();
                    this.paused = false;
                    this.start();
                }, this.remaining);
            } else {
                this.paused = false;
                this.start();
            }
        }
    }

    clear() {
        clearInterval(this.timerId);
    }

    start() {
        this.clear();
        this.timerId = setInterval(() => {
            this.run();
        }, this._delay);
    }

    private run() {
        this.callbackStartTime = new Date().getTime();
        this._callback();
    }
}

usage is pretty straightforward,

const interval = new IntervalTimer(console.log(aaa), 3000);
interval.start();
interval.pause();
interval.resume();
interval.clear();

Problems with local variable scope. How to solve it?

not Error:

JSONObject json1 = getJsonX();

Error:

JSONObject json2 = null;
if(x == y)
   json2 = getJSONX();

Error: Local variable statement defined in an enclosing scope must be final or effectively final.

But you can write:

JSONObject json2 = (x == y) ? json2 = getJSONX() : null;

Reading in from System.in - Java

Use System.in, it is an InputStream which just serves this purpose

Where does forever store console.log output?

Help is your best saviour, there is a logs action that you can call to check logs for all running processes.

forever --help

Shows the commands

logs                Lists log files for all forever processes
logs <script|index> Tails the logs for <script|index>

Sample output of the above command, for three processes running. console.log output's are stored in these logs.

info:    Logs for running Forever processes
data:        script    logfile
data:    [0] server.js /root/.forever/79ao.log
data:    [1] server.js /root/.forever/ZcOk.log
data:    [2] server.js /root/.forever/L30K.log

Converting Pandas dataframe into Spark dataframe error

You need to make sure your pandas dataframe columns are appropriate for the type spark is inferring. If your pandas dataframe lists something like:

pd.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5062 entries, 0 to 5061
Data columns (total 51 columns):
SomeCol                    5062 non-null object
Col2                       5062 non-null object

And you're getting that error try:

df[['SomeCol', 'Col2']] = df[['SomeCol', 'Col2']].astype(str)

Now, make sure .astype(str) is actually the type you want those columns to be. Basically, when the underlying Java code tries to infer the type from an object in python it uses some observations and makes a guess, if that guess doesn't apply to all the data in the column(s) it's trying to convert from pandas to spark it will fail.

Javascript callback when IFRAME is finished loading?

I think the load event is right. What is not right is the way you use to retreive the content from iframe content dom.

What you need is the html of the page loaded in the iframe not the html of the iframe object.

What you have to do is to access the content document with iFrameObj.contentDocument. This returns the dom of the page loaded inside the iframe, if it is on the same domain of the current page.

I would retreive the content before removing the iframe.

I've tested in firefox and opera.

Then i think you can retreive your data with $(childDom).html() or $(childDom).find('some selector') ...

Where does this come from: -*- coding: utf-8 -*-

This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

Waiting until the task finishes

Use DispatchGroups to achieve this. You can either get notified when the group's enter() and leave() calls are balanced:

func myFunction() {
    var a: Int?

    let group = DispatchGroup()
    group.enter()

    DispatchQueue.main.async {
        a = 1
        group.leave()
    }

    // does not wait. But the code in notify() gets run 
    // after enter() and leave() calls are balanced

    group.notify(queue: .main) {
        print(a)
    }
}

or you can wait:

func myFunction() {
    var a: Int?

    let group = DispatchGroup()
    group.enter()

    // avoid deadlocks by not using .main queue here
    DispatchQueue.global(attributes: .qosDefault).async {
        a = 1
        group.leave()
    }

    // wait ...
    group.wait()

    print(a) // you could also `return a` here
}

Note: group.wait() blocks the current queue (probably the main queue in your case), so you have to dispatch.async on another queue (like in the above sample code) to avoid a deadlock.

How to set username and password for SmtpClient object in .NET?

The SmtpClient can be used by code:

SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");

Does a finally block always get executed in Java?

Here are some conditions which can bypass a finally block:

  1. If the JVM exits while the try or catch code is being executed, then the finally block may not execute. More on sun tutorial
  2. Normal Shutdown - this occurs either when the last non-daemon thread exits OR when Runtime.exit() (some good blog). When a thread exits, the JVM performs an inventory of running threads, and if the only threads that are left are daemon threads, it initiates an orderly shutdown. When the JVM halts, any remaining daemon threads are abandoned finally blocks are not executed, stacks are not unwound the JVM just exits. Daemon threads should be used sparingly few processing activities can be safely abandoned at any time with no cleanup. In particular, it is dangerous to use daemon threads for tasks that might perform any sort of I/O. Daemon threads are best saved for "housekeeping" tasks, such as a background thread that periodically removes expired entries from an in-memory cache (source)

Last non-daemon thread exits example:

public class TestDaemon {
    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    System.out.println("Is alive");
                    Thread.sleep(10);
                    // throw new RuntimeException();
                }
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                System.out.println("This will never be executed.");
            }
        }
    };

    public static void main(String[] args) throws InterruptedException {
        Thread daemon = new Thread(runnable);
        daemon.setDaemon(true);
        daemon.start();
        Thread.sleep(100);
        // daemon.stop();
        System.out.println("Last non-daemon thread exits.");
    }
}

Output:

Is alive
Is alive
Is alive
Is alive
Is alive
Is alive
Is alive
Is alive
Is alive
Is alive
Last non-daemon thread exits.
Is alive
Is alive
Is alive
Is alive
Is alive

Dynamically add child components in React

Firstly a warning: you should never tinker with DOM that is managed by React, which you are doing by calling ReactDOM.render(<SampleComponent ... />);

With React, you should use SampleComponent directly in the main App.

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);

The content of your Component is irrelevant, but it should be used like this:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <SampleComponent name="SomeName"/>
            </div>
        );
    }
});

You can then extend your app component to use a list.

var App = React.createClass({
    render: function() {
        var componentList = [
            <SampleComponent name="SomeName1"/>,
            <SampleComponent name="SomeName2"/>
        ]; // Change this to get the list from props or state
        return (
            <div>
                <h1>App main component! </h1>
                {componentList}
            </div>
        );
    }
});

I would really recommend that you look at the React documentation then follow the "Get Started" instructions. The time you spend on that will pay off later.

https://facebook.github.io/react/index.html

How does the data-toggle attribute work? (What's its API?)

I think you are a bit confused on the purpose of custom data attributes. From the w3 spec

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value".

In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.

Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".

  • Button Toggle

    Button.prototype.toggle = function () {
      var changed = true
      var $parent = this.$element.closest('[data-toggle="buttons"]')
    
      if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
          if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
          else $parent.find('.active').removeClass('active')
        }
        if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
      } else {
        this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
      }
    
      if (changed) this.$element.toggleClass('active')
    }
    

The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element.

From what I see these are the data-toggle options:

  • collapse
  • dropdown
  • modal
  • tab
  • pill
  • button(s)

You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.

gradlew: Permission Denied

Try below command:

chmod +x gradlew && ./gradlew compileDebug --stacktrace

What is the use of the %n format specifier in C?

%n is C99, works not with VC++.

Style input element to fill remaining width of its container

Here is a simple and clean solution without using JavaScript or table layout hacks. It is similar to this answer: Input text auto width filling 100% with other elements floating

It is important to wrap the input field with a span which is display:block. Next thing is that the button has to come first and the the input field second.

Then you can float the button to the right and the input field fills the remaining space.

_x000D_
_x000D_
form {_x000D_
    width: 500px;_x000D_
    overflow: hidden;_x000D_
    background-color: yellow;_x000D_
}_x000D_
input {_x000D_
    width: 100%;_x000D_
}_x000D_
span {_x000D_
    display: block;_x000D_
    overflow: hidden;_x000D_
    padding-right:10px;_x000D_
}_x000D_
button {_x000D_
    float: right;_x000D_
}
_x000D_
<form method="post">_x000D_
     <button>Search</button>_x000D_
     <span><input type="text" title="Search" /></span>_x000D_
</form>
_x000D_
_x000D_
_x000D_

A simple fiddle: http://jsfiddle.net/v7YTT/90/

Update 1: If your website is targeted towards modern browsers only, I suggest using flexible boxes. Here you can see the current support.

Update 2: This even works with multiple buttons or other elements that share the full with with the input field. Here is an example.

How to compare timestamp dates with date-only parameter in MySQL?

When I read your question, I thought your were on Oracle DB until I saw the tag 'MySQL'. Anyway, for people working with Oracle here is the way:

SELECT *
FROM table
where timestamp = to_timestamp('21.08.2017 09:31:57', 'dd-mm-yyyy hh24:mi:ss');

removing table border

From your case, you need to set the border to none on <table> and <td> tags.

    <table width=1000 style="border:none; border-collapse:collapse; cellspacing:0; cellpadding:0" >
        <tr>
            <td style="border:none" rowspan=2>
                <img src="/Content/Images/elk_banner.jpg" />
            </td>
            <td style="border:none">
                <div id="logindisplay">
                    @Html.Partial("_LogOnPartial")
                </div>
            </td>
        </tr>
    </table>

htaccess <Directory> deny from all

You can also use RedirectMatch directive to deny access to a folder.

To deny access to a folder, you can use the following RedirectMatch in htaccess :

 RedirectMatch 403 ^/folder/?$

This will forbid an external access to /folder/ eg : http://example.com/folder/ will return a 403 forbidden error.

To deny access to everything inside the folder, You can use this :

RedirectMatch 403 ^/folder/.*$

This will block access to the entire folder eg : http://example.com/folder/anyURI will return a 403 error response to client.

How to check whether a pandas DataFrame is empty?

I prefer going the long route. These are the checks I follow to avoid using a try-except clause -

  1. check if variable is not None
  2. then check if its a dataframe and
  3. make sure its not empty

Here, DATA is the suspect variable -

DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty

How can I set the 'backend' in matplotlib in Python?

FYI, I found I needed to put matplotlib.use('Agg') first in Python import order. For what I was doing (unit testing needed to be headless) that meant putting

import matplotlib
matplotlib.use('Agg')

at the top of my master test script. I didn't have to touch any other files.

How to use cURL to send Cookies?

You are using a wrong format in your cookie file. As curl documentation states, it uses an old Netscape cookie file format, which is different from the format used by web browsers. If you need to create a curl cookie file manually, this post should help you. In your example the file should contain following line

127.0.0.1   FALSE   /   FALSE   0   USER_TOKEN  in

having 7 TAB-separated fields meaning domain, tailmatch, path, secure, expires, name, value.

printf a variable in C

Your printf needs a format string:

printf("%d\n", x);

This reference page gives details on how to use printf and related functions.

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

Android SDK Build Tools are exactly what the name says they are; tools for building Android Applications.It is very important to use the latest build tools version (selected automatically by your IDE via the Android SDK) but the reason the old versions are left there is to support backward compatibility, that is If your projects depend on older versions of the Build Tools.

Inserting one list into another list in java?

An object is only once in memory. Your first addition to list just adds the object references.

anotherList.addAll will also just add the references. So still only 100 objects in memory.

If you change list by adding/removing elements, anotherList won't be changed. But if you change any object in list, then it's content will be also changed, when accessing it from anotherList, because the same reference is being pointed to from both lists.

Javascript parse float is ignoring the decimals after my comma

It is better to use this syntax to replace all the commas in a case of a million 1,234,567

var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, ""); 
var number = parseFloat(string);
console.log(number)

The g means to remove all commas.

Check the Jsfiddle demo here.

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

Error in MySQL when setting default value for DATE or DATETIME

To solve the problem with MySQL Workbench (After applying the solution on the server side) :

Remove SQL_MODE to TRADITIONAL in the preferences panel.

enter image description here

Arrays.fill with multidimensional array in Java

This is because a double[][] is an array of double[] which you can't assign 0.0 to (it would be like doing double[] vector = 0.0). In fact, Java has no true multidimensional arrays.

As it happens, 0.0 is the default value for doubles in Java, thus the matrix will actually already be filled with zeros when you get it from new. However, if you wanted to fill it with, say, 1.0 you could do the following:

I don't believe the API provides a method to solve this without using a loop. It's simple enough however to do it with a for-each loop.

double[][] matrix = new double[20][4];

// Fill each row with 1.0
for (double[] row: matrix)
    Arrays.fill(row, 1.0);

MySQL pivot table query with dynamic columns

The only way in MySQL to do this dynamically is with Prepared statements. Here is a good article about them:

Dynamic pivot tables (transform rows to columns)

Your code would look like this:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(pa.fieldname = ''',
      fieldname,
      ''', pa.fieldvalue, NULL)) AS ',
      fieldname
    )
  ) INTO @sql
FROM product_additional;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See Demo

NOTE: GROUP_CONCAT function has a limit of 1024 characters. See parameter group_concat_max_len