Programs & Examples On #Computational finance

Why is there no String.Empty in Java?

Late answer, but I think it adds something new to this topic.

None of the previous answers has answered the original question. Some have attempted to justify the lack of a constant, while others have showed ways in which we can deal with the lack of the constant. But no one has provided a compelling justification for the benefit of the constant, so its lack is still not properly explained.

A constant would be useful because it would prevent certain code errors from going unnoticed.

Say that you have a large code base with hundreds of references to "". Someone modifies one of these while scrolling through the code and changes it to " ". Such a change would have a high chance of going unnoticed into production, at which point it might cause some issue whose source will be tricky to detect.

OTOH, a library constant named EMPTY, if subject to the same error, would generate a compiler error for something like EM PTY.

Defining your own constant is still better. Someone could still alter its initialization by mistake, but because of its wide use, the impact of such an error would be much harder to go unnoticed than an error in a single use case.

This is one of the general benefits that you get from using constants instead of literal values. People usually recognize that using a constant for a value used in dozens of places allows you to easily update that value in just one place. What is less often acknowledged is that this also prevents that value from being accidentally modified, because such a change would show everywhere. So, yes, "" is shorter than EMPTY, but EMPTY is safer to use than "".

So, coming back to the original question, we can only speculate that the language designers were probably not aware of this benefit of providing constants for literal values that are frequently used. Hopefully, we'll one day see string constants added in Java.

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException

Related

How to "flatten" a multi-dimensional array to simple one in PHP?

Another method from PHP's user comments (simplified) and here:

function array_flatten_recursive($array) { 
   if (!$array) return false;
   $flat = array();
   $RII = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
   foreach ($RII as $value) $flat[] = $value;
   return $flat;
}

The big benefit of this method is that it tracks the depth of the recursion, should you need that while flattening.
This will output:

$array = array( 
    'A' => array('B' => array( 1, 2, 3)), 
    'C' => array(4, 5) 
); 
print_r(array_flatten_recursive($array)); 

#Returns: 
Array ( 
    [0] => 1 
    [1] => 2 
    [2] => 3 
    [3] => 4 
    [4] => 5 
)

PHP compare time

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

How to use \n new line in VB msgbox() ...?

msgbox "This is the first line" & vbcrlf & "and this is the second line"

or in .NET msgbox "This is the first line" & Environment.NewLine & "and this is the second line"

Configuring Git over SSH to login once

Try ssh-add, you need ssh-agent to be running and holding your private key

(Ok, responding to the updated question, you first run ssh-keygen to generate a public and private key as Jefromi explained. You put the public key on the server. You should use a passphrase, if you don't you have the equivalent of a plain-text password in your private key. But when you do, then you need as a practical matter ssh-agent as explained below.)

You want to be running ssh-agent in the background as you log in. Once you log in, the idea is to run ssh-add once and only once, in order to give the agent your passphrase, to decode your key. The agent then just sits in memory with your key unlocked and loaded, ready to use every time you ssh somewhere.

All ssh-family commands1 will then consult the agent and automatically be able to use your private key.

On OSX (err, macOS), GNOME and KDE systems, ssh-agent is usually launched automatically for you. I will go through the details in case, like me, you also have a Cygwin or other windows environment where this most certainly is not done for you.

Start here: man ssh-agent.

There are various ways to automatically run the agent. As the man page explains, you can run it so that it is a parent of all your login session's other processes. That way, the environment variables it provides will automatically be in all your shells. When you (later) invoke ssh-add or ssh both will have access to the agent because they all have the environment variables with magic socket pathnames or whatever.

Alternatively, you can run the agent as an ordinary child, save the environment settings in a file, and source that file in every shell when it starts.

My OSX and Ubuntu systems automatically do the agent launch setup, so all I have to do is run ssh-add once. Try running ssh-add and see if it works, if so, then you just need to do that once per reboot.

My Cygwin system needed it done manually, so I did this in my .profile and I have .bashrc source .profile:

. .agent > /dev/null
ps -p $SSH_AGENT_PID | grep ssh-agent > /dev/null || {
        ssh-agent > .agent
        . .agent > /dev/null
}

The .agent file is created automatically by the script; it contains the environment variables definitions and exports. The above tries to source the .agent file, and then tries to ps(1) the agent. If it doesn't work it starts an agent and creates a new agent file. You can also just run ssh-add and if it fails start an agent.


1. And even local and remote sudo with the right pam extension.

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

You can use Jquery's Equal Heights Plugin to accomplish, this plugins makes all the div of exact same height as other. If one of them grows and other will also grow.

Here a sample of implementation

Usage: $(object).equalHeights([minHeight], [maxHeight]);

Example 1: $(".cols").equalHeights(); 
           Sets all columns to the same height.

Example 2: $(".cols").equalHeights(400); 
           Sets all cols to at least 400px tall.

Example 3: $(".cols").equalHeights(100,300); 
           Cols are at least 100 but no more than 300 pixels tall. Elements with too much content will gain a scrollbar.

Here is the link

http://www.cssnewbie.com/equalheights-jquery-plugin/

Spring data JPA query with parameter properties

You can try something like this:

public interface PersonRepository extends CrudRepository<Person, Long> {
       @Query("select p from Person AS p"
       + " ,Name AS n"  
       + " where p.forename = n.forename "
       + " and p.surname = n.surname"
       + " and n = :name")
       Set<Person>findByName(@Param("name") Name name);
    }

C compile error: "Variable-sized object may not be initialized"

I am assuming that you are using a C99 compiler (with support for dynamically sized arrays). The problem in your code is that at the time when the compilers sees your variable declaration it cannot know how many elements there are in the array (I am also assuming here, from the compiler error that length is not a compile time constant).

You must manually initialize that array:

int boardAux[length][length];
memset( boardAux, 0, length*length*sizeof(int) );

How to decorate a class?

There's actually a pretty good implementation of a class decorator here:

https://github.com/agiliq/Django-parsley/blob/master/parsley/decorators.py

I actually think this is a pretty interesting implementation. Because it subclasses the class it decorates, it will behave exactly like this class in things like isinstance checks.

It has an added benefit: it's not uncommon for the __init__ statement in a custom django Form to make modifications or additions to self.fields so it's better for changes to self.fields to happen after all of __init__ has run for the class in question.

Very clever.

However, in your class you actually want the decoration to alter the constructor, which I don't think is a good use case for a class decorator.

Valid values for android:fontFamily and what they map to?

Available fonts (as of Oreo)

Preview of all fonts

The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.

For code sleuths: fonts.xml is the definitive and ever-expanding list of Android fonts.


Using these fonts

Set the android:fontFamily and android:textStyle attributes, e.g.

<!-- Roboto Bold -->
<TextView
    android:fontFamily="sans-serif"
    android:textStyle="bold" />

to the desired values from this table:

Font                     | android:fontFamily          | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin              | sans-serif-thin             |
Roboto Light             | sans-serif-light            |
Roboto Regular           | sans-serif                  |
Roboto Bold              | sans-serif                  | bold
Roboto Medium            | sans-serif-medium           |
Roboto Black             | sans-serif-black            |
Roboto Condensed Light   | sans-serif-condensed-light  |
Roboto Condensed Regular | sans-serif-condensed        |
Roboto Condensed Medium  | sans-serif-condensed-medium |
Roboto Condensed Bold    | sans-serif-condensed        | bold
Noto Serif               | serif                       |
Noto Serif Bold          | serif                       | bold
Droid Sans Mono          | monospace                   |
Cutive Mono              | serif-monospace             |
Coming Soon              | casual                      |
Dancing Script           | cursive                     |
Dancing Script Bold      | cursive                     | bold
Carrois Gothic SC        | sans-serif-smallcaps        |

(Noto Sans is a fallback font; you can't specify it directly)

Note: this table is derived from fonts.xml. Each font's family name and style is listed in fonts.xml, e.g.

<family name="serif-monospace">
    <font weight="400" style="normal">CutiveMono.ttf</font>
</family>

serif-monospace is thus the font family, and normal is the style.


Compatibility

Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:

  • Ice Cream Sandwich: Roboto regular, bold, italic, and bold italic
  • Jelly Bean: Roboto light, light italic, condensed, condensed bold, condensed italic, and condensed bold italic
  • Jelly Bean MR1: Roboto thin and thin italic
  • Lollipop:
    • Roboto medium, medium italic, black, and black italic
    • Noto Serif regular, bold, italic, bold italic
    • Cutive Mono
    • Coming Soon
    • Dancing Script
    • Carrois Gothic SC
    • Noto Sans
  • Oreo MR1: Roboto condensed medium

SQL Switch/Case in 'where' clause

declare @locationType varchar(50);
declare @locationID int;

SELECT column1, column2
FROM viewWhatever
WHERE
@locationID = 
  CASE @locationType
      WHEN 'location' THEN account_location
      WHEN 'area' THEN xxx_location_area 
      WHEN 'division' THEN xxx_location_division 
  END

Get MIME type from filename extension

I know the question is for C# I just want to left in Javascript format because i just converted the Samuel's answer:

export const contentTypes = {

".323": "text/h323",
".3g2": "video/3gpp2",
".3gp": "video/3gpp",
".3gp2": "video/3gpp2",
".3gpp": "video/3gpp",
".7z": "application/x-7z-compressed",
".aa": "audio/audible",
".AAC": "audio/aac",
".aaf": "application/octet-stream",
".aax": "audio/vnd.audible.aax",
".ac3": "audio/ac3",
".aca": "application/octet-stream",
".accda": "application/msaccess.addin",
".accdb": "application/msaccess",
".accdc": "application/msaccess.cab",
".accde": "application/msaccess",
".accdr": "application/msaccess.runtime",
".accdt": "application/msaccess",
".accdw": "application/msaccess.webapplication",
".accft": "application/msaccess.ftemplate",
".acx": "application/internet-property-stream",
".AddIn": "text/xml",
".ade": "application/msaccess",
".adobebridge": "application/x-bridge-url",
".adp": "application/msaccess",
".ADT": "audio/vnd.dlna.adts",
".ADTS": "audio/aac",
".afm": "application/octet-stream",
".ai": "application/postscript",
".aif": "audio/x-aiff",
".aifc": "audio/aiff",
".aiff": "audio/aiff",
".air": "application/vnd.adobe.air-application-installer-package+zip",
".amc": "application/x-mpeg",
".application": "application/x-ms-application",
".art": "image/x-jg",
".asa": "application/xml",
".asax": "application/xml",
".ascx": "application/xml",
".asd": "application/octet-stream",
".asf": "video/x-ms-asf",
".ashx": "application/xml",
".asi": "application/octet-stream",
".asm": "text/plain",
".asmx": "application/xml",
".aspx": "application/xml",
".asr": "video/x-ms-asf",
".asx": "video/x-ms-asf",
".atom": "application/atom+xml",
".au": "audio/basic",
".avi": "video/x-msvideo",
".axs": "application/olescript",
".bas": "text/plain",
".bcpio": "application/x-bcpio",
".bin": "application/octet-stream",
".bmp": "image/bmp",
".c": "text/plain",
".cab": "application/octet-stream",
".caf": "audio/x-caf",
".calx": "application/vnd.ms-office.calx",
".cat": "application/vnd.ms-pki.seccat",
".cc": "text/plain",
".cd": "text/plain",
".cdda": "audio/aiff",
".cdf": "application/x-cdf",
".cer": "application/x-x509-ca-cert",
".chm": "application/octet-stream",
".class": "application/x-java-applet",
".clp": "application/x-msclip",
".cmx": "image/x-cmx",
".cnf": "text/plain",
".cod": "image/cis-cod",
".config": "application/xml",
".contact": "text/x-ms-contact",
".coverage": "application/xml",
".cpio": "application/x-cpio",
".cpp": "text/plain",
".crd": "application/x-mscardfile",
".crl": "application/pkix-crl",
".crt": "application/x-x509-ca-cert",
".cs": "text/plain",
".csdproj": "text/plain",
".csh": "application/x-csh",
".csproj": "text/plain",
".css": "text/css",
".csv": "text/csv",
".cur": "application/octet-stream",
".cxx": "text/plain",
".dat": "application/octet-stream",
".datasource": "application/xml",
".dbproj": "text/plain",
".dcr": "application/x-director",
".def": "text/plain",
".deploy": "application/octet-stream",
".der": "application/x-x509-ca-cert",
".dgml": "application/xml",
".dib": "image/bmp",
".dif": "video/x-dv",
".dir": "application/x-director",
".disco": "text/xml",
".dll": "application/x-msdownload",
".dll.config": "text/xml",
".dlm": "text/dlm",
".doc": "application/msword",
".docm": "application/vnd.ms-word.document.macroEnabled.12",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".dot": "application/msword",
".dotm": "application/vnd.ms-word.template.macroEnabled.12",
".dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
".dsp": "application/octet-stream",
".dsw": "text/plain",
".dtd": "text/xml",
".dtsConfig": "text/xml",
".dv": "video/x-dv",
".dvi": "application/x-dvi",
".dwf": "drawing/x-dwf",
".dwp": "application/octet-stream",
".dxr": "application/x-director",
".eml": "message/rfc822",
".emz": "application/octet-stream",
".eot": "application/octet-stream",
".eps": "application/postscript",
".etl": "application/etl",
".etx": "text/x-setext",
".evy": "application/envoy",
".exe": "application/octet-stream",
".exe.config": "text/xml",
".fdf": "application/vnd.fdf",
".fif": "application/fractals",
".filters": "Application/xml",
".fla": "application/octet-stream",
".flr": "x-world/x-vrml",
".flv": "video/x-flv",
".fsscript": "application/fsharp-script",
".fsx": "application/fsharp-script",
".generictest": "application/xml",
".gif": "image/gif",
".group": "text/x-ms-group",
".gsm": "audio/x-gsm",
".gtar": "application/x-gtar",
".gz": "application/x-gzip",
".h": "text/plain",
".hdf": "application/x-hdf",
".hdml": "text/x-hdml",
".hhc": "application/x-oleobject",
".hhk": "application/octet-stream",
".hhp": "application/octet-stream",
".hlp": "application/winhlp",
".hpp": "text/plain",
".hqx": "application/mac-binhex40",
".hta": "application/hta",
".htc": "text/x-component",
".htm": "text/html",
".html": "text/html",
".htt": "text/webviewhtml",
".hxa": "application/xml",
".hxc": "application/xml",
".hxd": "application/octet-stream",
".hxe": "application/xml",
".hxf": "application/xml",
".hxh": "application/octet-stream",
".hxi": "application/octet-stream",
".hxk": "application/xml",
".hxq": "application/octet-stream",
".hxr": "application/octet-stream",
".hxs": "application/octet-stream",
".hxt": "text/html",
".hxv": "application/xml",
".hxw": "application/octet-stream",
".hxx": "text/plain",
".i": "text/plain",
".ico": "image/x-icon",
".ics": "application/octet-stream",
".idl": "text/plain",
".ief": "image/ief",
".iii": "application/x-iphone",
".inc": "text/plain",
".inf": "application/octet-stream",
".inl": "text/plain",
".ins": "application/x-internet-signup",
".ipa": "application/x-itunes-ipa",
".ipg": "application/x-itunes-ipg",
".ipproj": "text/plain",
".ipsw": "application/x-itunes-ipsw",
".iqy": "text/x-ms-iqy",
".isp": "application/x-internet-signup",
".ite": "application/x-itunes-ite",
".itlp": "application/x-itunes-itlp",
".itms": "application/x-itunes-itms",
".itpc": "application/x-itunes-itpc",
".IVF": "video/x-ivf",
".jar": "application/java-archive",
".java": "application/octet-stream",
".jck": "application/liquidmotion",
".jcz": "application/liquidmotion",
".jfif": "image/pjpeg",
".jnlp": "application/x-java-jnlp-file",
".jpb": "application/octet-stream",
".jpe": "image/jpeg",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".js": "application/x-javascript",
".json": "application/json",
".jsx": "text/jscript",
".jsxbin": "text/plain",
".latex": "application/x-latex",
".library-ms": "application/windows-library+xml",
".lit": "application/x-ms-reader",
".loadtest": "application/xml",
".lpk": "application/octet-stream",
".lsf": "video/x-la-asf",
".lst": "text/plain",
".lsx": "video/x-la-asf",
".lzh": "application/octet-stream",
".m13": "application/x-msmediaview",
".m14": "application/x-msmediaview",
".m1v": "video/mpeg",
".m2t": "video/vnd.dlna.mpeg-tts",
".m2ts": "video/vnd.dlna.mpeg-tts",
".m2v": "video/mpeg",
".m3u": "audio/x-mpegurl",
".m3u8": "audio/x-mpegurl",
".m4a": "audio/m4a",
".m4b": "audio/m4b",
".m4p": "audio/m4p",
".m4r": "audio/x-m4r",
".m4v": "video/x-m4v",
".mac": "image/x-macpaint",
".mak": "text/plain",
".man": "application/x-troff-man",
".manifest": "application/x-ms-manifest",
".map": "text/plain",
".master": "application/xml",
".mda": "application/msaccess",
".mdb": "application/x-msaccess",
".mde": "application/msaccess",
".mdp": "application/octet-stream",
".me": "application/x-troff-me",
".mfp": "application/x-shockwave-flash",
".mht": "message/rfc822",
".mhtml": "message/rfc822",
".mid": "audio/mid",
".midi": "audio/mid",
".mix": "application/octet-stream",
".mk": "text/plain",
".mmf": "application/x-smaf",
".mno": "text/xml",
".mny": "application/x-msmoney",
".mod": "video/mpeg",
".mov": "video/quicktime",
".movie": "video/x-sgi-movie",
".mp2": "video/mpeg",
".mp2v": "video/mpeg",
".mp3": "audio/mpeg",
".mp4": "video/mp4",
".mp4v": "video/mp4",
".mpa": "video/mpeg",
".mpe": "video/mpeg",
".mpeg": "video/mpeg",
".mpf": "application/vnd.ms-mediapackage",
".mpg": "video/mpeg",
".mpp": "application/vnd.ms-project",
".mpv2": "video/mpeg",
".mqv": "video/quicktime",
".ms": "application/x-troff-ms",
".msi": "application/octet-stream",
".mso": "application/octet-stream",
".mts": "video/vnd.dlna.mpeg-tts",
".mtx": "application/xml",
".mvb": "application/x-msmediaview",
".mvc": "application/x-miva-compiled",
".mxp": "application/x-mmxp",
".nc": "application/x-netcdf",
".nsc": "video/x-ms-asf",
".nws": "message/rfc822",
".ocx": "application/octet-stream",
".oda": "application/oda",
".odc": "text/x-ms-odc",
".odh": "text/plain",
".odl": "text/plain",
".odp": "application/vnd.oasis.opendocument.presentation",
".ods": "application/oleobject",
".odt": "application/vnd.oasis.opendocument.text",
".one": "application/onenote",
".onea": "application/onenote",
".onepkg": "application/onenote",
".onetmp": "application/onenote",
".onetoc": "application/onenote",
".onetoc2": "application/onenote",
".orderedtest": "application/xml",
".osdx": "application/opensearchdescription+xml",
".p10": "application/pkcs10",
".p12": "application/x-pkcs12",
".p7b": "application/x-pkcs7-certificates",
".p7c": "application/pkcs7-mime",
".p7m": "application/pkcs7-mime",
".p7r": "application/x-pkcs7-certreqresp",
".p7s": "application/pkcs7-signature",
".pbm": "image/x-portable-bitmap",
".pcast": "application/x-podcast",
".pct": "image/pict",
".pcx": "application/octet-stream",
".pcz": "application/octet-stream",
".pdf": "application/pdf",
".pfb": "application/octet-stream",
".pfm": "application/octet-stream",
".pfx": "application/x-pkcs12",
".pgm": "image/x-portable-graymap",
".pic": "image/pict",
".pict": "image/pict",
".pkgdef": "text/plain",
".pkgundef": "text/plain",
".pko": "application/vnd.ms-pki.pko",
".pls": "audio/scpls",
".pma": "application/x-perfmon",
".pmc": "application/x-perfmon",
".pml": "application/x-perfmon",
".pmr": "application/x-perfmon",
".pmw": "application/x-perfmon",
".png": "image/png",
".pnm": "image/x-portable-anymap",
".pnt": "image/x-macpaint",
".pntg": "image/x-macpaint",
".pnz": "image/png",
".pot": "application/vnd.ms-powerpoint",
".potm": "application/vnd.ms-powerpoint.template.macroEnabled.12",
".potx": "application/vnd.openxmlformats-officedocument.presentationml.template",
".ppa": "application/vnd.ms-powerpoint",
".ppam": "application/vnd.ms-powerpoint.addin.macroEnabled.12",
".ppm": "image/x-portable-pixmap",
".pps": "application/vnd.ms-powerpoint",
".ppsm": "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
".ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
".ppt": "application/vnd.ms-powerpoint",
".pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".prf": "application/pics-rules",
".prm": "application/octet-stream",
".prx": "application/octet-stream",
".ps": "application/postscript",
".psc1": "application/PowerShell",
".psd": "application/octet-stream",
".psess": "application/xml",
".psm": "application/octet-stream",
".psp": "application/octet-stream",
".pub": "application/x-mspublisher",
".pwz": "application/vnd.ms-powerpoint",
".qht": "text/x-html-insertion",
".qhtm": "text/x-html-insertion",
".qt": "video/quicktime",
".qti": "image/x-quicktime",
".qtif": "image/x-quicktime",
".qtl": "application/x-quicktimeplayer",
".qxd": "application/octet-stream",
".ra": "audio/x-pn-realaudio",
".ram": "audio/x-pn-realaudio",
".rar": "application/octet-stream",
".ras": "image/x-cmu-raster",
".rat": "application/rat-file",
".rc": "text/plain",
".rc2": "text/plain",
".rct": "text/plain",
".rdlc": "application/xml",
".resx": "application/xml",
".rf": "image/vnd.rn-realflash",
".rgb": "image/x-rgb",
".rgs": "text/plain",
".rm": "application/vnd.rn-realmedia",
".rmi": "audio/mid",
".rmp": "application/vnd.rn-rn_music_package",
".roff": "application/x-troff",
".rpm": "audio/x-pn-realaudio-plugin",
".rqy": "text/x-ms-rqy",
".rtf": "application/rtf",
".rtx": "text/richtext",
".ruleset": "application/xml",
".s": "text/plain",
".safariextz": "application/x-safari-safariextz",
".scd": "application/x-msschedule",
".sct": "text/scriptlet",
".sd2": "audio/x-sd2",
".sdp": "application/sdp",
".sea": "application/octet-stream",
".searchConnector-ms": "application/windows-search-connector+xml",
".setpay": "application/set-payment-initiation",
".setreg": "application/set-registration-initiation",
".settings": "application/xml",
".sgimb": "application/x-sgimb",
".sgml": "text/sgml",
".sh": "application/x-sh",
".shar": "application/x-shar",
".shtml": "text/html",
".sit": "application/x-stuffit",
".sitemap": "application/xml",
".skin": "application/xml",
".sldm": "application/vnd.ms-powerpoint.slide.macroEnabled.12",
".sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide",
".slk": "application/vnd.ms-excel",
".sln": "text/plain",
".slupkg-ms": "application/x-ms-license",
".smd": "audio/x-smd",
".smi": "application/octet-stream",
".smx": "audio/x-smd",
".smz": "audio/x-smd",
".snd": "audio/basic",
".snippet": "application/xml",
".snp": "application/octet-stream",
".sol": "text/plain",
".sor": "text/plain",
".spc": "application/x-pkcs7-certificates",
".spl": "application/futuresplash",
".src": "application/x-wais-source",
".srf": "text/plain",
".SSISDeploymentManifest": "text/xml",
".ssm": "application/streamingmedia",
".sst": "application/vnd.ms-pki.certstore",
".stl": "application/vnd.ms-pki.stl",
".sv4cpio": "application/x-sv4cpio",
".sv4crc": "application/x-sv4crc",
".svc": "application/xml",
".swf": "application/x-shockwave-flash",
".t": "application/x-troff",
".tar": "application/x-tar",
".tcl": "application/x-tcl",
".testrunconfig": "application/xml",
".testsettings": "application/xml",
".tex": "application/x-tex",
".texi": "application/x-texinfo",
".texinfo": "application/x-texinfo",
".tgz": "application/x-compressed",
".thmx": "application/vnd.ms-officetheme",
".thn": "application/octet-stream",
".tif": "image/tiff",
".tiff": "image/tiff",
".tlh": "text/plain",
".tli": "text/plain",
".toc": "application/octet-stream",
".tr": "application/x-troff",
".trm": "application/x-msterminal",
".trx": "application/xml",
".ts": "video/vnd.dlna.mpeg-tts",
".tsv": "text/tab-separated-values",
".ttf": "application/octet-stream",
".tts": "video/vnd.dlna.mpeg-tts",
".txt": "text/plain",
".u32": "application/octet-stream",
".uls": "text/iuls",
".user": "text/plain",
".ustar": "application/x-ustar",
".vb": "text/plain",
".vbdproj": "text/plain",
".vbk": "video/mpeg",
".vbproj": "text/plain",
".vbs": "text/vbscript",
".vcf": "text/x-vcard",
".vcproj": "Application/xml",
".vcs": "text/plain",
".vcxproj": "Application/xml",
".vddproj": "text/plain",
".vdp": "text/plain",
".vdproj": "text/plain",
".vdx": "application/vnd.ms-visio.viewer",
".vml": "text/xml",
".vscontent": "application/xml",
".vsct": "text/xml",
".vsd": "application/vnd.visio",
".vsi": "application/ms-vsi",
".vsix": "application/vsix",
".vsixlangpack": "text/xml",
".vsixmanifest": "text/xml",
".vsmdi": "application/xml",
".vspscc": "text/plain",
".vss": "application/vnd.visio",
".vsscc": "text/plain",
".vssettings": "text/xml",
".vssscc": "text/plain",
".vst": "application/vnd.visio",
".vstemplate": "text/xml",
".vsto": "application/x-ms-vsto",
".vsw": "application/vnd.visio",
".vsx": "application/vnd.visio",
".vtx": "application/vnd.visio",
".wav": "audio/wav",
".wave": "audio/wav",
".wax": "audio/x-ms-wax",
".wbk": "application/msword",
".wbmp": "image/vnd.wap.wbmp",
".wcm": "application/vnd.ms-works",
".wdb": "application/vnd.ms-works",
".wdp": "image/vnd.ms-photo",
".webarchive": "application/x-safari-webarchive",
".webtest": "application/xml",
".wiq": "application/xml",
".wiz": "application/msword",
".wks": "application/vnd.ms-works",
".WLMP": "application/wlmoviemaker",
".wlpginstall": "application/x-wlpg-detect",
".wlpginstall3": "application/x-wlpg3-detect",
".wm": "video/x-ms-wm",
".wma": "audio/x-ms-wma",
".wmd": "application/x-ms-wmd",
".wmf": "application/x-msmetafile",
".wml": "text/vnd.wap.wml",
".wmlc": "application/vnd.wap.wmlc",
".wmls": "text/vnd.wap.wmlscript",
".wmlsc": "application/vnd.wap.wmlscriptc",
".wmp": "video/x-ms-wmp",
".wmv": "video/x-ms-wmv",
".wmx": "video/x-ms-wmx",
".wmz": "application/x-ms-wmz",
".wpl": "application/vnd.ms-wpl",
".wps": "application/vnd.ms-works",
".wri": "application/x-mswrite",
".wrl": "x-world/x-vrml",
".wrz": "x-world/x-vrml",
".wsc": "text/scriptlet",
".wsdl": "text/xml",
".wvx": "video/x-ms-wvx",
".x": "application/directx",
".xaf": "x-world/x-vrml",
".xaml": "application/xaml+xml",
".xap": "application/x-silverlight-app",
".xbap": "application/x-ms-xbap",
".xbm": "image/x-xbitmap",
".xdr": "text/plain",
".xht": "application/xhtml+xml",
".xhtml": "application/xhtml+xml",
".xla": "application/vnd.ms-excel",
".xlam": "application/vnd.ms-excel.addin.macroEnabled.12",
".xlc": "application/vnd.ms-excel",
".xld": "application/vnd.ms-excel",
".xlk": "application/vnd.ms-excel",
".xll": "application/vnd.ms-excel",
".xlm": "application/vnd.ms-excel",
".xls": "application/vnd.ms-excel",
".xlsb": "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
".xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".xlt": "application/vnd.ms-excel",
".xltm": "application/vnd.ms-excel.template.macroEnabled.12",
".xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
".xlw": "application/vnd.ms-excel",
".xml": "text/xml",
".xmta": "application/xml",
".xof": "x-world/x-vrml",
".XOML": "text/plain",
".xpm": "image/x-xpixmap",
".xps": "application/vnd.ms-xpsdocument",
".xrm-ms": "text/xml",
".xsc": "application/xml",
".xsd": "text/xml",
".xsf": "text/xml",
".xsl": "text/xml",
".xslt": "text/xml",
".xsn": "application/octet-stream",
".xss": "application/xml",
".xtp": "application/octet-stream",
".xwd": "image/x-xwindowdump",
".z": "application/x-compress",
".zip": "application/x-zip-compressed"
}

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

you have to add fulltext index on specific fields you want to search.

ALTER TABLE news ADD FULLTEXT(headline, story);

where "news" is your table and "headline, story" fields you wont to enable for fulltext search

How can I see normal print output created during pytest run?

If you are using PyCharm IDE, then you can run that individual test or all tests using Run toolbar. The Run tool window displays output generated by your application and you can see all the print statements in there as part of test output.

What is managed or unmanaged code in programming?

Managed Code:
Code that runs under a "contract of cooperation" with the common language runtime. Managed code must supply the metadata necessary for the runtime to provide services such as memory management, cross-language integration, code access security, and automatic lifetime control of objects. All code based on Microsoft intermediate language (MSIL) executes as managed code.

Un-Managed Code:
Code that is created without regard for the conventions and requirements of the common language runtime. Unmanaged code executes in the common language runtime environment with minimal services (for example, no garbage collection, limited debugging, and so on).

Reference: http://www.dotnetspider.com/forum/11612-difference-between-managed-and-unmanaged-code.aspx

How do I change the default application icon in Java?

You can try this one, it works just fine :

`   ImageIcon icon = new ImageIcon(".//Ressources//User_50.png");
    this.setIconImage(icon.getImage());`

Batch script to delete files

in batch code your path should not contain any Space so pls change your folder name from "TEST 100%" to "TEST_100%" and your new code will be del "D:\TEST\TEST_100%\Archive*.TXT"

hope this will resolve your problem

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

You can not. You will / do break a lot of things. Like relationships. WHich rely on the number being pulled back which EF can not do in the way you set it up. THe price for breaking every pattern there is.

Generate the GUID in the C# layer, so that relationships can continue working.

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

I tried it on XP and it doesn't work if the PC is set to International time yyyy-M-d. Place a breakpoint on the line and before it is processed change the date string to use '-' in place of the '/' and you'll find it works. It makes no difference whether you have the CultureInfo or not. Seems strange to be able specify an expercted format only to have the separator ignored.

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

MySQL Error: : 'Access denied for user 'root'@'localhost'

After trying all others answers, this it what finally worked for me

sudo mysql -- It does not ask me for any password

-- Then in MariaDB/MySQL console:
update mysql.user set plugin = 'mysql_native_password' where User='root';
FLUSH PRIVILEGES;
exit;

I found the answer in this post : https://medium.com/@chiragpatel_52497/solved-error-access-denied-for-user-root-localhost-of-mysql-programming-school-6e3611838d06

How do I deal with corrupted Git object files?

You can use "find" for remove all files in the /objects directory with 0 in size with the command:

find .git/objects/ -size 0 -delete

Backup is recommended.

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

CSS text-align not working

I try to avoid floating elements unless the design really needs it. Because you have floated the <li> they are out of normal flow.

If you add .navigation { text-align:center; } and change .navigation li { float: left; } to .navigation li { display: inline-block; } then entire navigation will be centred.

One caveat to this approach is that display: inline-block; is not supported in IE6 and needs a workaround to make it work in IE7.

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

You must write onActivityResult() in your FirstActivity.Java as follows

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        fragment.onActivityResult(requestCode, resultCode, data);
    }
}

This will trigger onActivityResult method of fragments on FirstActivity.java

Ajax Upload image

Image upload using ajax and check image format and upload max size   

<form class='form-horizontal' method="POST"  id='document_form' enctype="multipart/form-data">
                                    <div class='optionBox1'>
                                        <div class='row inviteInputWrap1 block1'>
                                            <div class='col-3'>
                                                <label class='col-form-label'>Name</label>
                                                <input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <label class='col-form-label'>File</label>
                                                <input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <span class='deleteInviteWrap1 remove1 d-none'>
                                                    <i class='fas fa-trash'></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class='row'>
                                             <div class='col-8 pl-3 pb-4 mt-4'>
                                                <span class='btn btn-info add1 pr-3'>+ Add More</span>
                                                 <button class='btn btn-primary'>Submit</button> 
                                            </div>
                                        </div>
                                    </div>
                                    </form>     
                                    
                                    </div>  
                      
    
      $.validator.setDefaults({
       submitHandler: function (form) 
         {
               $.ajax({
                    url : "action1.php",
                    type : "POST",
                    data : new FormData(form),
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    dataType:'json',
                    processData: false,
                    success: function(data)
                    {
                        if(data.status =='success')
                            {
                                 swal("Document has been successfully uploaded!", {
                                    icon: "success",
                                 });
                                 setTimeout(function(){
                                    window.location.reload(); 
                                },1200);
                            }
                            else
                            {
                                swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
                            }   
                    },
                    error:function(data)
                    {
                        swal ( "Ops!" ,  "error in document upload." ,  "error" );
                    }
                });
            }
      });
    
      $('#document_form').validate({
        rules: {
            "name[]": {
              required: true
          },
          "file[]": {
              required: true,
              extension: "jpg,jpeg,png,pdf,doc",
              filesize :2000000 
          }
        },
        messages: {
            "name[]": {
            required: "Please enter name"
          },
          "file[]": {
            required: "Please enter file",
            extension :'Please upload only jpg,jpeg,png,pdf,doc'
          }
        },
        errorElement: 'span',
        errorPlacement: function (error, element) {
          error.addClass('invalid-feedback');
          element.closest('.col-3').append(error);
        },
        highlight: function (element, errorClass, validClass) {
          $(element).addClass('is-invalid');
        },
        unhighlight: function (element, errorClass, validClass) {
          $(element).removeClass('is-invalid');
        }
      });
    
      $.validator.addMethod('filesize', function(value, element, param) {
         return this.optional(element) || (element.files[0].size <= param)
        }, 'File size must be less than 2 MB');

Reading large text files with streams in C#

All excellent answers! however, for someone looking for an answer, these appear to be somewhat incomplete.

As a standard String can only of Size X, 2Gb to 4Gb depending on your configuration, these answers do not really fulfil the OP's question. One method is to work with a List of Strings:

List<string> Words = new List<string>();

using (StreamReader sr = new StreamReader(@"C:\Temp\file.txt"))
{

string line = string.Empty;

while ((line = sr.ReadLine()) != null)
{
    Words.Add(line);
}
}

Some may want to Tokenise and split the line when processing. The String List now can contain very large volumes of Text.

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

Better way to generate array of all letters in the alphabet

Finally you are getting a char array with alphabet. Why did you do so hard way using a loop ?

It is just

char[] alphabet=new char[]{'a','b',.........,'z'}

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

You say "I am not using a forms to manipulate the data." But you are doing a POST. Therefore, you are, in fact, using a form, even if it's empty.

$.ajax's dataType tells jQuery what type the server will return, not what you are passing. POST can only pass a form. jQuery will convert data to key/value pairs and pass it as a query string. From the docs:

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

Therefore:

  1. You aren't passing JSON to the server. You're passing JSON to jQuery.
  2. Model binding happens in the same way it happens in any other case.

How to know Hive and Hadoop versions from command prompt?

You can not get hive version from command line.

You can checkout hadoop version as mentioned by Dave.

Also if you are using cloudera distribution, then look directly at the libs:

ls /usr/lib/hive/lib/ and check for hive library

hive-hwi-0.7.1-cdh3u3.jar

You can also check the compatible versions here:

http://www.cloudera.com/content/cloudera/en/documentation/cdh5/v5-1-x/CDH-Version-and-Packaging-Information/CDH-Version-and-Packaging-Information.html

IIS - 401.3 - Unauthorized

Since you're dealing with static content...

On the folder that acts as the root of your website- if you right click > properties > security, does "Users" show up in the list? if not click "Add..." and type it in, be sure to click "Apply" when you're done.

Get root view from current activity

anyview.getRootView(); will be the easiest way.

How to use onClick with divs in React.js

This works

var Box = React.createClass({
    getInitialState: function() {
        return {
            color: 'white'
        };
    },

    changeColor: function() {
        var newColor = this.state.color == 'white' ? 'black' : 'white';
        this.setState({ color: newColor });
    },

    render: function() {
        return (
            <div>
                <div
                    className='box'
                    style={{background:this.state.color}}
                    onClick={this.changeColor}
                >
                    In here already
                </div>
            </div>
        );
    }
});

ReactDOM.render(<Box />, document.getElementById('div1'));
ReactDOM.render(<Box />, document.getElementById('div2'));
ReactDOM.render(<Box />, document.getElementById('div3'));

and in your css, delete the styles you have and put this

.box {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  float: left;
}

You have to style the actual div you are calling onClick on. Give the div a className and then style it. Also remember to remove this block where you are rendering App into the dom, App is not defined

ReactDOM.render(<App />,document.getElementById('root'));

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

Ken's answer is basically right but I'd like to chime in on the "why would you want to use one over the other?" part of your question.

Basics

The base interface you choose for your repository has two main purposes. First, you allow the Spring Data repository infrastructure to find your interface and trigger the proxy creation so that you inject instances of the interface into clients. The second purpose is to pull in as much functionality as needed into the interface without having to declare extra methods.

The common interfaces

The Spring Data core library ships with two base interfaces that expose a dedicated set of functionalities:

  • CrudRepository - CRUD methods
  • PagingAndSortingRepository - methods for pagination and sorting (extends CrudRepository)

Store-specific interfaces

The individual store modules (e.g. for JPA or MongoDB) expose store-specific extensions of these base interfaces to allow access to store-specific functionality like flushing or dedicated batching that take some store specifics into account. An example for this is deleteInBatch(…) of JpaRepository which is different from delete(…) as it uses a query to delete the given entities which is more performant but comes with the side effect of not triggering the JPA-defined cascades (as the spec defines it).

We generally recommend not to use these base interfaces as they expose the underlying persistence technology to the clients and thus tighten the coupling between them and the repository. Plus, you get a bit away from the original definition of a repository which is basically "a collection of entities". So if you can, stay with PagingAndSortingRepository.

Custom repository base interfaces

The downside of directly depending on one of the provided base interfaces is two-fold. Both of them might be considered as theoretical but I think they're important to be aware of:

  1. Depending on a Spring Data repository interface couples your repository interface to the library. I don't think this is a particular issue as you'll probably use abstractions like Page or Pageable in your code anyway. Spring Data is not any different from any other general purpose library like commons-lang or Guava. As long as it provides reasonable benefit, it's just fine.
  2. By extending e.g. CrudRepository, you expose a complete set of persistence method at once. This is probably fine in most circumstances as well but you might run into situations where you'd like to gain more fine-grained control over the methods expose, e.g. to create a ReadOnlyRepository that doesn't include the save(…) and delete(…) methods of CrudRepository.

The solution to both of these downsides is to craft your own base repository interface or even a set of them. In a lot of applications I have seen something like this:

interface ApplicationRepository<T> extends PagingAndSortingRepository<T, Long> { }

interface ReadOnlyRepository<T> extends Repository<T, Long> {

  // Al finder methods go here
}

The first repository interface is some general purpose base interface that actually only fixes point 1 but also ties the ID type to be Long for consistency. The second interface usually has all the find…(…) methods copied from CrudRepository and PagingAndSortingRepository but does not expose the manipulating ones. Read more on that approach in the reference documentation.

Summary - tl;dr

The repository abstraction allows you to pick the base repository totally driven by you architectural and functional needs. Use the ones provided out of the box if they suit, craft your own repository base interfaces if necessary. Stay away from the store specific repository interfaces unless unavoidable.

How do I pass data to Angular routed components?

I this the other approach not good for this issue. I thing the best approach is Query-Parameter by Router angular that have 2 way:

Passing query parameter directly

With this code you can navigate to url by params in your html code:

<a [routerLink]="['customer-service']" [queryParams]="{ serviceId: 99 }"></a>

Passing query parameter by Router

You have to inject the router within your constructor like:

constructor(private router:Router){

}

Now use of that like:

goToPage(pageNum) {
    this.router.navigate(['/product-list'], { queryParams: { serviceId: serviceId} });
}

Now if you want to read from Router in another Component you have to use of ActivatedRoute like:

constructor(private activateRouter:ActivatedRouter){

}

and subscribe that:

  ngOnInit() {
    this.sub = this.route
      .queryParams
      .subscribe(params => {
        // Defaults to 0 if no query param provided.
        this.page = +params['serviceId'] || 0;
      });
  }

Get current scroll position of ScrollView in React Native

The above answers tell how to get the position using different API, onScroll, onMomentumScrollEnd etc; If you want to know the page index, you can calculate it using the offset value.

 <ScrollView 
    pagingEnabled={true}
    onMomentumScrollEnd={this._onMomentumScrollEnd}>
    {pages}
 </ScrollView> 

  _onMomentumScrollEnd = ({ nativeEvent }: any) => {
   // the current offset, {x: number, y: number} 
   const position = nativeEvent.contentOffset; 
   // page index 
   const index = Math.round(nativeEvent.contentOffset.x / PAGE_WIDTH);

   if (index !== this.state.currentIndex) {
     // onPageDidChanged
   }
 };

enter image description here

In iOS, the relationship between ScrollView and the visible region is as follow: The picture comes from https://www.objc.io/issues/3-views/scroll-view/

ref: https://www.objc.io/issues/3-views/scroll-view/

Error: fix the version conflict (google-services plugin)

With

com.android.tools.build:gradle:3.2.0

You have to use:

classpath 'com.google.gms:google-services:4.1.0'

This fixed my problem

Capitalize the first letter of string in AngularJs

_x000D_
_x000D_
.capitalize {_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.capitalize:first-letter {_x000D_
  font-size: 2em;_x000D_
  text-transform: capitalize;_x000D_
}
_x000D_
<span class="capitalize">_x000D_
  really, once upon a time there was a badly formatted output coming from my backend, <strong>all completely in lowercase</strong> and thus not quite as fancy-looking as could be - but then cascading style sheets (which we all know are <a href="http://9gag.com/gag/6709/css-is-awesome">awesome</a>) with modern pseudo selectors came around to the rescue..._x000D_
</span>
_x000D_
_x000D_
_x000D_

Vertical Tabs with JQuery?

I wouldn't expect vertical tabs to need different Javascript from horizontal tabs. The only thing that would be different is the CSS for presenting the tabs and content on the page. JS for tabs generally does no more than show/hide/maybe load content.

Autowiring fails: Not an managed Type

After encountering this issue and tried different method of adding the entity packaname name to EntityScan, ComponentScan etc, none of it worked.

Added the package to packageScan config in the EntityManagerFactory of the repository config. The below code gives the code based configuration as opposed to XML based ones answered above.

@Primary
@Bean(name = "entityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource);
    emf.setJpaVendorAdapter(jpaVendorAdapter);
    emf.setPackagesToScan("org.package.entity");
    emf.setPersistenceUnitName("default"); 
    emf.afterPropertiesSet();
    return emf.getObject();
}

Why use argparse rather than optparse?

At first I was as reluctant as @fmark to switch from optparse to argparse, because:

  1. I thought the difference was not that huge.
  2. Quite some VPS still provides Python 2.6 by default.

Then I saw this doc, argparse outperforms optparse, especially when talking about generating meaningful help message: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html

And then I saw "argparse vs. optparse" by @Nicholas, saying we can have argparse available in python <2.7 (Yep, I didn't know that before.)

Now my two concerns are well addressed. I wrote this hoping it will help others with a similar mindset.

Can I have onScrollListener for a ScrollView?

Here's a derived HorizontalScrollView I wrote to handle notifications about scrolling and scroll ending. It properly handles when a user has stopped actively scrolling and when it fully decelerates after a user lets go:

public class ObservableHorizontalScrollView extends HorizontalScrollView {
    public interface OnScrollListener {
        public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY);
        public void onEndScroll(ObservableHorizontalScrollView scrollView);
    }

    private boolean mIsScrolling;
    private boolean mIsTouching;
    private Runnable mScrollingRunnable;
    private OnScrollListener mOnScrollListener;

    public ObservableHorizontalScrollView(Context context) {
        this(context, null, 0);
    }

    public ObservableHorizontalScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ObservableHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        int action = ev.getAction();

        if (action == MotionEvent.ACTION_MOVE) {
            mIsTouching = true;
            mIsScrolling = true;
        } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            if (mIsTouching && !mIsScrolling) {
                if (mOnScrollListener != null) {
                    mOnScrollListener.onEndScroll(this);
                }
            }

            mIsTouching = false;
        }

        return super.onTouchEvent(ev);
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);

        if (Math.abs(oldX - x) > 0) {
            if (mScrollingRunnable != null) {
                removeCallbacks(mScrollingRunnable);
            }

            mScrollingRunnable = new Runnable() {
                public void run() {
                    if (mIsScrolling && !mIsTouching) {
                        if (mOnScrollListener != null) {
                            mOnScrollListener.onEndScroll(ObservableHorizontalScrollView.this);
                        }
                    }

                    mIsScrolling = false;
                    mScrollingRunnable = null;
                }
            };

            postDelayed(mScrollingRunnable, 200);
        }

        if (mOnScrollListener != null) {
            mOnScrollListener.onScrollChanged(this, x, y, oldX, oldY);
        }
    }

    public OnScrollListener getOnScrollListener() {
        return mOnScrollListener;
    }

    public void setOnScrollListener(OnScrollListener mOnEndScrollListener) {
        this.mOnScrollListener = mOnEndScrollListener;
    }

}

Most common C# bitwise operations on enums

This was inspired by using Sets as indexers in Delphi, way back when:

/// Example of using a Boolean indexed property
/// to manipulate a [Flags] enum:

public class BindingFlagsIndexer
{
  BindingFlags flags = BindingFlags.Default;

  public BindingFlagsIndexer()
  {
  }

  public BindingFlagsIndexer( BindingFlags value )
  {
     this.flags = value;
  }

  public bool this[BindingFlags index]
  {
    get
    {
      return (this.flags & index) == index;
    }
    set( bool value )
    {
      if( value )
        this.flags |= index;
      else
        this.flags &= ~index;
    }
  }

  public BindingFlags Value 
  {
    get
    { 
      return flags;
    } 
    set( BindingFlags value ) 
    {
      this.flags = value;
    }
  }

  public static implicit operator BindingFlags( BindingFlagsIndexer src )
  {
     return src != null ? src.Value : BindingFlags.Default;
  }

  public static implicit operator BindingFlagsIndexer( BindingFlags src )
  {
     return new BindingFlagsIndexer( src );
  }

}

public static class Class1
{
  public static void Example()
  {
    BindingFlagsIndexer myFlags = new BindingFlagsIndexer();

    // Sets the flag(s) passed as the indexer:

    myFlags[BindingFlags.ExactBinding] = true;

    // Indexer can specify multiple flags at once:

    myFlags[BindingFlags.Instance | BindingFlags.Static] = true;

    // Get boolean indicating if specified flag(s) are set:

    bool flatten = myFlags[BindingFlags.FlattenHierarchy];

    // use | to test if multiple flags are set:

    bool isProtected = ! myFlags[BindingFlags.Public | BindingFlags.NonPublic];

  }
}

How to change port number for apache in WAMP

You could try changing Apache server to listen to some other port other than port 80.

Click on yellow WAMP icon in your taskbar Choose Apache -> httpd.conf Inside find these two lines of code:

Listen 80 ServerName localhost:80 and change them to something like this (they are not one next to the other):

Listen 8080 ServerName localhost:8080

What is the equivalent of Java's System.out.println() in Javascript?

In java System.out.println() prints something to console. In javascript same can be achieved using console.log().

You need to view browser console by pressing F12 key which opens developer tool and then switch to console tab.

Create an enum with string values

I have tried in TypeScript 1.5 like below and it's worked for me

module App.Constants {
   export enum e{
        Hello= ("Hello") as any,
World= ("World") as any
    }
}

PIG how to count a number of rows in alias

COUNT is part of pig see the manual

LOGS= LOAD 'log';
LOGS_GROUP= GROUP LOGS ALL;
LOG_COUNT = FOREACH LOGS_GROUP GENERATE COUNT(LOGS);

Multiple distinct pages in one HTML file

Well, you could, but you probably just want to have two sets of content in the same page, and switch between them. Example:

_x000D_
_x000D_
    <html>
    <head>
    <script>
    function show(shown, hidden) {
      document.getElementById(shown).style.display='block';
      document.getElementById(hidden).style.display='none';
      return false;
    }
    </script>
    </head>
    <body>
    
      <div id="Page1">
        Content of page 1
        <a href="#" onclick="return show('Page2','Page1');">Show page 2</a>
      </div>
    
      <div id="Page2" style="display:none">
        Content of page 2
        <a href="#" onclick="return show('Page1','Page2');">Show page 1</a>
      </div>
    
    </body>
    </html>
_x000D_
_x000D_
_x000D_

(Simplififed HTML code, should of course have doctype, etc.)

Bash tool to get nth line from a file

With awk it is pretty fast:

awk 'NR == num_line' file

When this is true, the default behaviour of awk is performed: {print $0}.


Alternative versions

If your file happens to be huge, you'd better exit after reading the required line. This way you save CPU time See time comparison at the end of the answer.

awk 'NR == num_line {print; exit}' file

If you want to give the line number from a bash variable you can use:

awk 'NR == n' n=$num file
awk -v n=$num 'NR == n' file   # equivalent

See how much time is saved by using exit, specially if the line happens to be in the first part of the file:

# Let's create a 10M lines file
for ((i=0; i<100000; i++)); do echo "bla bla"; done > 100Klines
for ((i=0; i<100; i++)); do cat 100Klines; done > 10Mlines

$ time awk 'NR == 1234567 {print}' 10Mlines
bla bla

real    0m1.303s
user    0m1.246s
sys 0m0.042s
$ time awk 'NR == 1234567 {print; exit}' 10Mlines
bla bla

real    0m0.198s
user    0m0.178s
sys 0m0.013s

So the difference is 0.198s vs 1.303s, around 6x times faster.

how to create inline style with :before and :after

If you really need it inline, for example because you are loading some user-defined colors dynamically, you can always add a <style> element right before your content.

<style>#project-slide-1:before { color: #ff0000; }</style>
<div id="project-slide-1" class="project-slide"> ... </div>

Example use case with PHP and some (wordpress inspired) dummy functions:

<style>#project-slide-<?php the_ID() ?>:before { color: <?php the_field('color') ?>; }</style>
<div id="project-slide-<?php the_ID() ?>" class="project-slide"> ... </div>

Since HTML 5.2 it is valid to place style elements inside the body, although it is still recommend to place style elements in the head.

Reference: https://www.w3.org/TR/html52/document-metadata.html#the-style-element

CSS hide scroll bar, but have element scrollable

Hope this helps

/* Hide scrollbar for Chrome, Safari and Opera */
::-webkit-scrollbar {
  display: none;
}

/* Hide scrollbar for IE, Edge and Firefox */
html {
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

Dynamic SQL results into temp table in SQL Stored procedure

You can define a table dynamically just as you are inserting into it dynamically, but the problem is with the scope of temp tables. For example, this code:

DECLARE @sql varchar(max)
SET @sql = 'CREATE TABLE #T1 (Col1 varchar(20))'
EXEC(@sql)
INSERT INTO #T1 (Col1) VALUES ('This will not work.')
SELECT * FROM #T1

will return with the error "Invalid object name '#T1'." This is because the temp table #T1 is created at a "lower level" than the block of executing code. In order to fix, use a global temp table:

DECLARE @sql varchar(max)
SET @sql = 'CREATE TABLE ##T1 (Col1 varchar(20))'
EXEC(@sql)
INSERT INTO ##T1 (Col1) VALUES ('This will work.')
SELECT * FROM ##T1

Hope this helps, Jesse

Facebook Open Graph not clearing cache

  1. Go to http://developers.facebook.com/tools/debug

  2. Paste in the url of the page and click debug. If your site is using url aliases make sure you are using the same url as Facebook is using for the page you are sharing (example: in Drupal use the node/* path instead of the alias if the page is shared via that url).

  3. Click in the "Share preview" part on "See this in the share dialog" link

What is the default lifetime of a session?

You can use something like ini_set('session.gc_maxlifetime', 28800); // 8 * 60 * 60 too.

Save matplotlib file to a directory

You just need to put the file path (directory) before the name of the image. Example:

fig.savefig('/home/user/Documents/graph.png')

Other example:

fig.savefig('/home/user/Downloads/MyImage.png')

RVM is not a function, selecting rubies with 'rvm use ...' will not work

The error is due to rvm is not running as in login shell. Hence try the below command:

/bin/bash --login

You will able run rvm commands instantly as login shell in terminal.

Thanks!

Change Volley timeout duration

See Request.setRetryPolicy() and the constructor for DefaultRetryPolicy, e.g.

JsonObjectRequest myRequest = new JsonObjectRequest(Method.GET,
        url, null,
        new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error: " + error.getMessage());
            }
});

myRequest.setRetryPolicy(new DefaultRetryPolicy(
        MY_SOCKET_TIMEOUT_MS, 
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Passing an array by reference in C?

also be aware that if you are creating a array within a method, you cannot return it. If you return a pointer to it, it would have been removed from the stack when the function returns. you must allocate memory onto the heap and return a pointer to that. eg.

//this is bad
char* getname()
{
  char name[100];
  return name;
}

//this is better
char* getname()
{
  char *name = malloc(100);
  return name;
  //remember to free(name)
}

ImportError: DLL load failed: %1 is not a valid Win32 application

The ImportError message is a bit misleading because of the reference to Win32, whereas the problem was simply the opencv DLLs were not found.

This problem was solved by adding the path the opencv binaries to the Windows PATH environment variable (as an example, on my computer this path is : C:\opencv\build\bin\Release).

Bootstrap collapse animation not smooth

For others like me who had a different but similar issue where the animation was not occurring at all:

From what I could find it may be something in my browser setting which preferred less motion for accessibility purposes. I could not find any setting in my browser, but I was able to get the animation working by downloading a local copy of bootstrap and commenting out this section of the CSS file:

@media (prefers-reduced-motion: reduce) {
  .collapsing {
    -webkit-transition: none;
    transition: none;
  }
}

Most concise way to convert a Set<T> to a List<T>

List<String> list = new ArrayList<String>(listOfTopicAuthors);

Escaping backslash in string - javascript

For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" /> element.

This question already mentions, and links to other Stack Overflow questions regarding this topic.


Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.
The backslash has to be escaped.

string = string.split("\\");

In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.

So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\") will show a dialog containing two backslashes.

How do you remove the title text from the Android ActionBar?

In your manifest.xml page you can give address to your activity label. the address is somewhere in your values/strings.xml . then you can change the value of the tag in xml file to null.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="title_main_activity"></string>
</resources>

How can I trim beginning and ending double quotes from a string?

This is the best way I found, to strip double quotes from the beginning and end of a string.

someString.replace (/(^")|("$)/g, '')

Maven: How to run a .java file from command line passing arguments

Adding a shell script e.g. run.sh makes it much more easier:

#!/usr/bin/env bash
export JAVA_PROGRAM_ARGS=`echo "$@"`
mvn exec:java -Dexec.mainClass="test.Main" -Dexec.args="$JAVA_PROGRAM_ARGS"

Then you are able to execute:

./run.sh arg1 arg2 arg3

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

What character represents a new line in a text area

By HTML specifications, browsers are required to canonicalize line breaks in user input to CR LF (\r\n), and I don’t think any browser gets this wrong. Reference: clause 17.13.4 Form content types in the HTML 4.01 spec.

In HTML5 drafts, the situation is more complicated, since they also deal with the processes inside a browser, not just the data that gets sent to a server-side form handler when the form is submitted. According to them (and browser practice), the textarea element value exists in three variants:

  1. the raw value as entered by the user, unnormalized; it may contain CR, LF, or CR LF pair;
  2. the internal value, called “API value”, where line breaks are normalized to LF (only);
  3. the submission value, where line breaks are normalized to CR LF pairs, as per Internet conventions.

Combining two expressions (Expression<Func<T, bool>>)

Well, you can use Expression.AndAlso / OrElse etc to combine logical expressions, but the problem is the parameters; are you working with the same ParameterExpression in expr1 and expr2? If so, it is easier:

var body = Expression.AndAlso(expr1.Body, expr2.Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]);

This also works well to negate a single operation:

static Expression<Func<T, bool>> Not<T>(
    this Expression<Func<T, bool>> expr)
{
    return Expression.Lambda<Func<T, bool>>(
        Expression.Not(expr.Body), expr.Parameters[0]);
}

Otherwise, depending on the LINQ provider, you might be able to combine them with Invoke:

// OrElse is very similar...
static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> left,
    Expression<Func<T, bool>> right)
{
    var param = Expression.Parameter(typeof(T), "x");
    var body = Expression.AndAlso(
            Expression.Invoke(left, param),
            Expression.Invoke(right, param)
        );
    var lambda = Expression.Lambda<Func<T, bool>>(body, param);
    return lambda;
}

Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for Invoke, but it is quite lengthy (and I can't remember where I left it...)


Generalized version that picks the simplest route:

static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> expr1,
    Expression<Func<T, bool>> expr2)
{
    // need to detect whether they use the same
    // parameter instance; if not, they need fixing
    ParameterExpression param = expr1.Parameters[0];
    if (ReferenceEquals(param, expr2.Parameters[0]))
    {
        // simple version
        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(expr1.Body, expr2.Body), param);
    }
    // otherwise, keep expr1 "as is" and invoke expr2
    return Expression.Lambda<Func<T, bool>>(
        Expression.AndAlso(
            expr1.Body,
            Expression.Invoke(expr2, param)), param);
}

Starting from .NET 4.0, there is the ExpressionVisitor class which allows you to build expressions that are EF safe.

    public static Expression<Func<T, bool>> AndAlso<T>(
        this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var parameter = Expression.Parameter(typeof (T));

        var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
        var left = leftVisitor.Visit(expr1.Body);

        var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
        var right = rightVisitor.Visit(expr2.Body);

        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(left, right), parameter);
    }



    private class ReplaceExpressionVisitor
        : ExpressionVisitor
    {
        private readonly Expression _oldValue;
        private readonly Expression _newValue;

        public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
        {
            _oldValue = oldValue;
            _newValue = newValue;
        }

        public override Expression Visit(Expression node)
        {
            if (node == _oldValue)
                return _newValue;
            return base.Visit(node);
        }
    }

How do I convert a long to a string in C++?

Well if you are fan of copy-paste, here it is:

#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
    std::stringstream ss;
    ss << t;
    return ss.str();
}

Can linux cat command be used for writing text to file?

I use the following code to write raw text to files, to update my CPU-settings. Hope this helps out! Script:

#!/bin/sh

cat > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor <<EOF
performance
EOF

cat > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF
performance
EOF

This writes the text "performance" to the two files mentioned in the script above. This example overwrite old data in files.

This code is saved as a file (cpu_update.sh) and to make it executable run:

chmod +x cpu_update.sh

After that, you can run the script with:

./cpu_update.sh

IF you do not want to overwrite the old data in the file, switch out

cat > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF

with

cat >> /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF

This will append your text to the end of the file without removing what other data already is in the file.

check if jquery has been loaded, then load it if false

Even though you may have a head appending it may not work in all browsers. This was the only method I found to work consistently.

<script type="text/javascript">
if (typeof jQuery == 'undefined') {
  document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"><\/script>');        
  } 
</script>

The remote certificate is invalid according to the validation procedure

Even shorter version of the solution from Dominic Zukiewicz:

ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

But this means that you will trust all certificates. For a service that isn't just run locally, something a bit smarter will be needed. In the first instance you could use this code to just test whether it solves your problem.

Positioning background image, adding padding

first off, to be a bit of a henpeck, its best NOT to use just the <background> tag. rather, use the proper, more specific, <background-image> tag.

the only way that i'm aware of to do such a thing is to build the padding into the image by extending the matte. since the empty pixels aren't stripped, you have your padding right there. so if you need a 10px border, create 10px of empty pixels all around your image. this is mui simple in Photoshop, Fireworks, GIMP, &c.

i'd also recommend trying out the PNG8 format instead of the dying GIF... much better.

there may be an alternate solution to your problem if we knew a bit more of how you're using it. :) it LOOKS like you're trying to add an accordion button. this would be best placed in the HTML because then you can target it with JavaScript/PHP; something you cannot do if it's in the background (at least not simply). in such a case, you can style the heck out of the image you currently have in CSS by using the following:

#hello img { padding: 10px; }

WR!

How do I limit the number of returned items?

Find parameters

The parameters find function takes are as follows:

  1. conditions «Object».
  2. [projection] «Object|String» optional fields to return, see Query.prototype.select()
  3. [options] «Object» optional see Query.prototype.setOptions()
  4. [callback] «Function»

How to limit

const Post = require('./models/Post');

Post.find(
  { published: true }, 
  null, 
  { sort: { 'date': 'asc' }, limit: 20 },
  function(error, posts) {
   if (error) return `${error} while finding from post collection`;

   return posts; // posts with sorted length of 20
  }
);

Extra Info

Mongoose allows you to query your collections in different ways like: Official Documentation

// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});

// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })

// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })

// passing options and executes
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});

// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});

// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});

unique object identifier in javascript

Latest browsers provide a cleaner method for extending Object.prototype. This code will make the property hidden from property enumeration (for p in o)

For the browsers that implement defineProperty, you can implement uniqueId property like this:

(function() {
    var id_counter = 1;
    Object.defineProperty(Object.prototype, "__uniqueId", {
        writable: true
    });
    Object.defineProperty(Object.prototype, "uniqueId", {
        get: function() {
            if (this.__uniqueId == undefined)
                this.__uniqueId = id_counter++;
            return this.__uniqueId;
        }
    });
}());

For details, see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

How can I make directory writable?

chmod 777 <directory>

this not change all ,just one file

chmod -R a+w <directory>

this ok

Angular2 change detection: ngOnChanges not firing for nested object

I stumbled upon the same need. And I read a lot on this so, here is my copper on the subject.

If you want your change detection on push, then you would have it when you change a value of an object inside right ? And you also would have it if somehow, you remove objects.

As already said, use of changeDetectionStrategy.onPush

Say you have this component you made, with changeDetectionStrategy.onPush:

<component [collection]="myCollection"></component>

Then you'd push an item and trigger the change detection :

myCollection.push(anItem);
refresh();

or you'd remove an item and trigger the change detection :

myCollection.splice(0,1);
refresh();

or you'd change an attrbibute value for an item and trigger the change detection :

myCollection[5].attribute = 'new value';
refresh();

Content of refresh :

refresh() : void {
    this.myCollection = this.myCollection.slice();
}

The slice method returns the exact same Array, and the [ = ] sign make a new reference to it, triggering the change detection every time you need it. Easy and readable :)

Regards,

denied: requested access to the resource is denied : docker

In my case sudo -E failed with this message. The resolution was to provide access do docker without sudo (create a group docker, add the (Jenkins) user to the group, set the group on /var/run/docker.sock). Now docker push does not need sudo, and it works.

jsonify a SQLAlchemy result set in Flask

I just want to add my method to do this.

just define a custome json encoder to serilize your db models.

class ParentEncoder(json.JSONEncoder):
    def default(self, obj):
        # convert object to a dict
        d = {}
        if isinstance(obj, Parent):
            return {"id": obj.id, "name": obj.name, 'children': list(obj.child)}
        if isinstance(obj, Child):
            return {"id": obj.id, "name": obj.name}

        d.update(obj.__dict__)
        return d

then in your view function

parents = Parent.query.all()
dat = json.dumps({"data": parents}, cls=ParentEncoder)
resp = Response(response=dat, status=200, mimetype="application/json")
return (resp)

it works well though the parent have relationships

Send Post Request with params using Retrofit

Post data to backend using retrofit

 implementation 'com.squareup.retrofit2:retrofit:2.8.1'
 implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
 implementation 'com.google.code.gson:gson:2.8.6'
 implementation 'com.squareup.okhttp3:logging-interceptor:4.5.0'

public interface UserService {
  @POST("users/")
  Call<UserResponse> userRegistration(@Body UserRegistration 
    userRegistration);
}



public class ApiClient {

    private static Retrofit getRetrofit(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.larntech.net/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();



        return retrofit;

    }


    public static UserService getService(){
        UserService userService = getRetrofit().create(UserService.class);
        return userService;
    }

}

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Add zero-padding to a string

"1".PadLeft(4, '0');

How to install Java SDK on CentOS?

On centos 7, I just do

sudo yum install java-sdk

I assume you have most common repo already. Centos just finds the correct SDK with the -devel sufix.

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

in my case I have used - (Hyphen) in my script name in case of Jenkinsfile Library. Got resolved after replacing Hyphen(-) with Underscore(_)

List comprehension vs map

map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.

An example of the tiny speed advantage of map when using exactly the same function:

$ python -mtimeit -s'xs=range(10)' 'map(hex, xs)'
100000 loops, best of 3: 4.86 usec per loop
$ python -mtimeit -s'xs=range(10)' '[hex(x) for x in xs]'
100000 loops, best of 3: 5.58 usec per loop

An example of how performance comparison gets completely reversed when map needs a lambda:

$ python -mtimeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
100000 loops, best of 3: 4.24 usec per loop
$ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]'
100000 loops, best of 3: 2.32 usec per loop

How to import data from text file to mysql database

1. if it's tab delimited txt file:

LOAD DATA LOCAL INFILE 'D:/MySQL/event.txt' INTO TABLE event

LINES TERMINATED BY '\r\n';

2. otherwise:

LOAD DATA LOCAL INFILE 'D:/MySQL/event.txt' INTO TABLE event

FIELDS TERMINATED BY 'x' (here x could be comma ',', tab '\t', semicolon ';', space ' ')

LINES TERMINATED BY '\r\n';

Disable a Button

You can enable/disable a button using isEnabled or isUserInteractionEnabled property.

The difference between two is :

  • isEnabled is a property of UIControl (super class of UIButton) and it has visual effects (i.e. grayed out) of enable/disable

  • isUserInteractionEnabled is a property of UIView (super class of UIControl) and has no visual effect although but achieves the purpose

Usage :

myButton.isEnabled = false // Recommended approach

myButton.isUserInteractionEnabled = false // Alternative approach

c++ parse int from string

Some handy quick functions (if you're not using Boost):

template<typename T>
std::string ToString(const T& v)
{
    std::ostringstream ss;
    ss << v;
    return ss.str();
}

template<typename T>
T FromString(const std::string& str)
{
    std::istringstream ss(str);
    T ret;
    ss >> ret;
    return ret;
}

Example:

int i = FromString<int>(s);
std::string str = ToString(i);

Works for any streamable types (floats etc). You'll need to #include <sstream> and possibly also #include <string>.

Django template how to look up a dictionary value with a variable

For me creating a python file named template_filters.py in my App with below content did the job

# coding=utf-8
from django.template.base import Library

register = Library()


@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

usage is like what culebrón said :

{{ mydict|get_item:item.NAME }}

Git clone particular version of remote repository

You could "reset" your repository to any commit you want (e.g. 1 month ago).

Use git-reset for that:

git clone [remote_address_here] my_repo
cd my_repo
git reset --hard [ENTER HERE THE COMMIT HASH YOU WANT]

jQuery load first 3 elements, click "load more" to display next 5 elements

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/

How to open spss data files in excel?

I tried the below and it worked well,

Install Dimensions Data Model and OLE DB Access

and follow the below steps in excel

Data->Get External Data ->From Other sources -> From Data Connection Wizard -> Other/Advanced-> SPSS MR DM-2 OLE DB Provider-> Metadata type as SPSS File(SAV)-> SPSS data file in Metadata Location->Finish

Read all files in a folder and apply a function to each data frame

On the contrary, I do think working with list makes it easy to automate such things.

Here is one solution (I stored your four dataframes in folder temp/).

filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)

It is important to store the full path for your files (as I did with full.names), otherwise you have to paste the working directory, e.g.

filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")

will work too. Note that I used substr to extract file names while discarding full path.

You can access your summary tables as follows:

> res$`df4.csv`
       A              B        
 Min.   :0.00   Min.   : 1.00  
 1st Qu.:1.25   1st Qu.: 2.25  
 Median :3.00   Median : 6.00  
 Mean   :3.50   Mean   : 7.00  
 3rd Qu.:5.50   3rd Qu.:10.50  
 Max.   :8.00   Max.   :16.00  

If you really want to get individual summary tables, you can extract them afterwards. E.g.,

for (i in 1:length(res))
  assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])

Make xargs execute the command once for each line of input

If you want to run the command for every line (i.e. result) coming from find, then what do you need the xargs for?

Try:

find path -type f -exec your-command {} \;

where the literal {} gets substituted by the filename and the literal \; is needed for find to know that the custom command ends there.

EDIT:

(after the edit of your question clarifying that you know about -exec)

From man xargs:

-L max-lines
Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x.

Note that filenames ending in blanks would cause you trouble if you use xargs:

$ mkdir /tmp/bax; cd /tmp/bax
$ touch a\  b c\  c
$ find . -type f -print | xargs -L1 wc -l
0 ./c
0 ./c
0 total
0 ./b
wc: ./a: No such file or directory

So if you don't care about the -exec option, you better use -print0 and -0:

$ find . -type f -print0 | xargs -0L1 wc -l
0 ./c
0 ./c
0 ./b
0 ./a

How do I add python3 kernel to jupyter (IPython)

sudo apt-get install python3-pip python3-dev
pip3 install -U jupyter

How do I create a shortcut via command-line in Windows?

I created a VB script and run it either from command line or from a Java process. I also tried to catch errors when creating the shortcut so I can have a better error handling.

Set oWS = WScript.CreateObject("WScript.Shell")
shortcutLocation = Wscript.Arguments(0)

'error handle shortcut creation
On Error Resume Next
Set oLink = oWS.CreateShortcut(shortcutLocation)
If Err Then WScript.Quit Err.Number

'error handle setting shortcut target
On Error Resume Next
oLink.TargetPath = Wscript.Arguments(1)
If Err Then WScript.Quit Err.Number

'error handle setting start in property
On Error Resume Next
oLink.WorkingDirectory = Wscript.Arguments(2)
If Err Then WScript.Quit Err.Number

'error handle saving shortcut
On Error Resume Next
oLink.Save
If Err Then WScript.Quit Err.Number

I run the script with the following commmand:

cscript /b script.vbs shortcutFuturePath targetPath startInProperty

It is possible to have it working even without setting the 'Start in' property in some cases.

How do I start PowerShell from Windows Explorer?

Try the PowerShell PowerToy... It adds a context menu item for Open PowerShell Here.

Or you could create a shortcut that opens PowerShell with the Start In folder being your Projects folder.

How to build a 'release' APK in Android Studio?

AndroidStudio is alpha version for now. So you have to edit gradle build script files by yourself. Add next lines to your build.gradle

android {

    signingConfigs {

        release {

            storeFile file('android.keystore')
            storePassword "pwd"
            keyAlias "alias"
            keyPassword "pwd"
        }
    }

    buildTypes {

       release {

           signingConfig signingConfigs.release
       }
    }
}

To actually run your application at emulator or device run gradle installDebug or gradle installRelease.

You can create helloworld project from AndroidStudio wizard to see what structure of gradle files is needed. Or export gradle files from working eclipse project. Also this series of articles are helpfull http://blog.stylingandroid.com/archives/1872#more-1872

Resolve host name to an ip address

Try tracert to resolve the hostname. IE you have Ip address 8.8.8.8 so you would use; tracert 8.8.8.8

What are all the different ways to create an object in Java?

there is also ClassLoader.loadClass(string) but this is not often used.

and if you want to be a total lawyer about it, arrays are technically objects because of an array's .length property. so initializing an array creates an object.

How can I change the font size of ticks of axes object in matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()

the x/yticks has the same properties as matplotlib.text

How to run Spyder in virtual environment?

To do without reinstalling spyder in all environments follow official reference here.

In summary (tested with conda):

  • Spyder should be installed in the base environment

From the system prompt:

  • Create an new environment. Note that depending on how you create it (conda, virtualenv) the environment folder will be located at different place on your system)

  • Activate the environment (e.g., conda activate [yourEnvName])

  • Install spyder-kernels inside the environment (e.g., conda install spyder-kernels)

  • Find and copy the path for the python executable inside the environment. Finding this path can be done using from the prompt this command python -c "import sys; print(sys.executable)"

  • Deactivate the environment (i.e., return to base conda deactivate)

  • run spyder (spyder3)

  • Finally in spyder Tool menu go to Preferences > Python Interpreter > Use the following interpreter and paste the environment python executable path

  • Restart the ipython console

PS: in spyder you should see at the bottom something like thisenter image description here

Voila

How to detect a textbox's content has changed

I would recommend taking a look at jQuery UI autocomplete widget. They handled most of the cases there since their code base is more mature than most ones out there.

Below is a link to a demo page so you can verify it works. http://jqueryui.com/demos/autocomplete/#default

You will get the most benefit from reading the source and seeing how they solved it. You can find it here: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.autocomplete.js.

Basically they do it all, they bind to input, keydown, keyup, keypress, focus and blur. Then they have special handling for all sorts of keys like page up, page down, up arrow key and down arrow key. A timer is used before getting the contents of the textbox. When a user types a key that does not correspond to a command (up key, down key and so on) there is a timer that explorers the content after about 300 milliseconds. It looks like this in the code:

// switch statement in the 
switch( event.keyCode ) {
            //...
            case keyCode.ENTER:
            case keyCode.NUMPAD_ENTER:
                // when menu is open and has focus
                if ( this.menu.active ) {
                    // #6055 - Opera still allows the keypress to occur
                    // which causes forms to submit
                    suppressKeyPress = true;
                    event.preventDefault();
                    this.menu.select( event );
                }
                break;
            default:
                suppressKeyPressRepeat = true;
                // search timeout should be triggered before the input value is changed
                this._searchTimeout( event );
                break;
            }
// ...
// ...
_searchTimeout: function( event ) {
    clearTimeout( this.searching );
    this.searching = this._delay(function() { // * essentially a warpper for a setTimeout call *
        // only search if the value has changed
        if ( this.term !== this._value() ) { // * _value is a wrapper to get the value *
            this.selectedItem = null;
            this.search( null, event );
        }
    }, this.options.delay );
},

The reason to use a timer is so that the UI gets a chance to be updated. When Javascript is running the UI cannot be updated, therefore the call to the delay function. This works well for other situations such as keeping focus on the textbox (used by that code).

So you can either use the widget or copy the code into your own widget if you are not using jQuery UI (or in my case developing a custom widget).

What is the difference between aggregation, composition and dependency?

An object associated with a composition relationship will not exist outside the containing object. Examples are an Appointment and the owner (a Person) or a Calendar; a TestResult and a Patient.

On the other hand, an object that is aggregated by a containing object can exist outside that containing object. Examples are a Door and a House; an Employee and a Department.

A dependency relates to collaboration or delegation, where an object requests services from another object and is therefor dependent on that object. As the client of the service, you want the service interface to remain constant, even if future services are offered.

Decoding a Base64 string in Java

Modify the package you're using:

import org.apache.commons.codec.binary.Base64;

And then use it like this:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

href="file://" doesn't work

%20 is the space between AmberCRO SOP.

Try -

href="http://file:///K:/AmberCRO SOP/2011-07-05/SOP-SOP-3.0.pdf"

Or rename the folder as AmberCRO-SOP and write it as -

href="http://file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf"

How to make a edittext box in a dialog

I know its too late to answer this question but for others who are searching for some thing similar to this here is a simple code of an alertbox with an edittext

AlertDialog.Builder alert = new AlertDialog.Builder(this); 

or

new AlertDialog.Builder(mContext, R.style.MyCustomDialogTheme);

if you want to change the theme of the dialog.

final EditText edittext = new EditText(ActivityContext);
alert.setMessage("Enter Your Message");
alert.setTitle("Enter Your Title");

alert.setView(edittext);

alert.setPositiveButton("Yes Option", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        //What ever you want to do with the value
        Editable YouEditTextValue = edittext.getText();
        //OR
        String YouEditTextValue = edittext.getText().toString();
    }
});

alert.setNegativeButton("No Option", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // what ever you want to do with No option.
    }
});

alert.show();

Why can I ping a server but not connect via SSH?

ping (ICMP protocol) and ssh are two different protocols.

  1. It could be that ssh service is not running or not installed

  2. firewall restriction (local to server like iptables or even sshd config lock down ) or (external firewall that protects incomming traffic to network hosting 111.111.111.111)

First check is to see if ssh port is up

nc -v -w 1 111.111.111.111 -z 22

if it succeeds then ssh should communicate if not then it will never work until restriction is lifted or ssh is started

brew install mysql on macOS

If mysql is already installed

Stop mysql completely.

  1. mysql.server stop <-- may need editing based on your version
  2. ps -ef | grep mysql <-- lists processes with mysql in their name
  3. kill [PID] <-- kill the processes by PID

Remove files. Instructions above are good. I'll add:

  1. sudo find /. -name "*mysql*"
  2. Using your judgement, rm -rf these files. Note that many programs have drivers for mysql which you do not want to remove. For example, don't delete stuff in a PHP install's directory. Do remove stuff in its own mysql directory.

Install

Hopefully you have homebrew. If not, download it.

I like to run brew as root, but I don't think you have to. Edit 2018: you can't run brew as root anymore

  1. sudo brew update
  2. sudo brew install cmake <-- dependency for mysql, useful
  3. sudo brew install openssl <-- dependency for mysql, useful
  4. sudo brew info mysql <-- skim through this... it gives you some idea of what's coming next
  5. sudo brew install mysql --with-embedded; say done <-- Installs mysql with the embedded server. Tells you when it finishes (my install took 10 minutes)

Afterwards

  1. sudo chown -R mysql /usr/local/var/mysql/ <-- mysql wouldn't work for me until I ran this command
  2. sudo mysql.server start <-- once again, the exact syntax may vary
  3. Create users in mysql (http://dev.mysql.com/doc/refman/5.7/en/create-user.html). Remember to add a password for the root user.

Fitting empirical distribution to theoretical ones with Scipy (Python)?

The following code is the version of the general answer but with corrections and clarity.

import numpy as np
import pandas as pd
import scipy.stats as st
import statsmodels.api as sm
import matplotlib as mpl
import matplotlib.pyplot as plt
import math
import random

mpl.style.use("ggplot")

def danoes_formula(data):
    """
    DANOE'S FORMULA
    https://en.wikipedia.org/wiki/Histogram#Doane's_formula
    """
    N = len(data)
    skewness = st.skew(data)
    sigma_g1 = math.sqrt((6*(N-2))/((N+1)*(N+3)))
    num_bins = 1 + math.log(N,2) + math.log(1+abs(skewness)/sigma_g1,2)
    num_bins = round(num_bins)
    return num_bins

def plot_histogram(data, results, n):
    ## n first distribution of the ranking
    N_DISTRIBUTIONS = {k: results[k] for k in list(results)[:n]}

    ## Histogram of data
    plt.figure(figsize=(10, 5))
    plt.hist(data, density=True, ec='white', color=(63/235, 149/235, 170/235))
    plt.title('HISTOGRAM')
    plt.xlabel('Values')
    plt.ylabel('Frequencies')

    ## Plot n distributions
    for distribution, result in N_DISTRIBUTIONS.items():
        # print(i, distribution)
        sse = result[0]
        arg = result[1]
        loc = result[2]
        scale = result[3]
        x_plot = np.linspace(min(data), max(data), 1000)
        y_plot = distribution.pdf(x_plot, loc=loc, scale=scale, *arg)
        plt.plot(x_plot, y_plot, label=str(distribution)[32:-34] + ": " + str(sse)[0:6], color=(random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)))
    
    plt.legend(title='DISTRIBUTIONS', bbox_to_anchor=(1.05, 1), loc='upper left')
    plt.show()

def fit_data(data):
    ## st.frechet_r,st.frechet_l: are disbled in current SciPy version
    ## st.levy_stable: a lot of time of estimation parameters
    ALL_DISTRIBUTIONS = [        
        st.alpha,st.anglit,st.arcsine,st.beta,st.betaprime,st.bradford,st.burr,st.cauchy,st.chi,st.chi2,st.cosine,
        st.dgamma,st.dweibull,st.erlang,st.expon,st.exponnorm,st.exponweib,st.exponpow,st.f,st.fatiguelife,st.fisk,
        st.foldcauchy,st.foldnorm, st.genlogistic,st.genpareto,st.gennorm,st.genexpon,
        st.genextreme,st.gausshyper,st.gamma,st.gengamma,st.genhalflogistic,st.gilbrat,st.gompertz,st.gumbel_r,
        st.gumbel_l,st.halfcauchy,st.halflogistic,st.halfnorm,st.halfgennorm,st.hypsecant,st.invgamma,st.invgauss,
        st.invweibull,st.johnsonsb,st.johnsonsu,st.ksone,st.kstwobign,st.laplace,st.levy,st.levy_l,
        st.logistic,st.loggamma,st.loglaplace,st.lognorm,st.lomax,st.maxwell,st.mielke,st.nakagami,st.ncx2,st.ncf,
        st.nct,st.norm,st.pareto,st.pearson3,st.powerlaw,st.powerlognorm,st.powernorm,st.rdist,st.reciprocal,
        st.rayleigh,st.rice,st.recipinvgauss,st.semicircular,st.t,st.triang,st.truncexpon,st.truncnorm,st.tukeylambda,
        st.uniform,st.vonmises,st.vonmises_line,st.wald,st.weibull_min,st.weibull_max,st.wrapcauchy
    ]
    
    MY_DISTRIBUTIONS = [st.beta, st.expon, st.norm, st.uniform, st.johnsonsb, st.gennorm, st.gausshyper]

    ## Calculae Histogram
    num_bins = danoes_formula(data)
    frequencies, bin_edges = np.histogram(data, num_bins, density=True)
    central_values = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges)-1)]

    results = {}
    for distribution in MY_DISTRIBUTIONS:
        ## Get parameters of distribution
        params = distribution.fit(data)
        
        ## Separate parts of parameters
        arg = params[:-2]
        loc = params[-2]
        scale = params[-1]
    
        ## Calculate fitted PDF and error with fit in distribution
        pdf_values = [distribution.pdf(c, loc=loc, scale=scale, *arg) for c in central_values]
        
        ## Calculate SSE (sum of squared estimate of errors)
        sse = np.sum(np.power(frequencies - pdf_values, 2.0))
        
        ## Build results and sort by sse
        results[distribution] = [sse, arg, loc, scale]
        
    results = {k: results[k] for k in sorted(results, key=results.get)}
    return results
        
def main():
    ## Import data
    data = pd.Series(sm.datasets.elnino.load_pandas().data.set_index('YEAR').values.ravel())
    results = fit_data(data)
    plot_histogram(data, results, 5)

if __name__ == "__main__":
    main()
    
    

enter image description here

How to right-align and justify-align in Markdown?

If you want to use justify align in Jupyter Notebook use the following syntax:

<p style='text-align: justify;'> Your Text </p>

For right alignment:

<p style='text-align: right;'> Your Text </p>

Insert line after first match using sed

A POSIX compliant one using the s command:

sed '/CLIENTSCRIPT="foo"/s/.*/&\
CLIENTSCRIPT2="hello"/' file

Converting char[] to byte[]

private static byte[] charArrayToByteArray(char[] c_array) {
        byte[] b_array = new byte[c_array.length];
        for(int i= 0; i < c_array.length; i++) {
            b_array[i] = (byte)(0xFF & (int)c_array[i]);
        }
        return b_array;
}

Set Windows process (or user) memory limit

No way to do this that I know of, although I'm very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.

The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it's the closest way I know of.

The working set stuff is good (Job Objects also control working sets), but that's not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn't limit total allocated memory.

Remove Elements from a HashSet while Iterating

Java 8 Collection has a nice method called removeIf that makes things easier and safer. From the API docs:

default boolean removeIf(Predicate<? super E> filter)
Removes all of the elements of this collection that satisfy the given predicate. 
Errors or runtime exceptions thrown during iteration or by the predicate 
are relayed to the caller.

Interesting note:

The default implementation traverses all elements of the collection using its iterator(). 
Each matching element is removed using Iterator.remove().

From: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-

Java Best Practices to Prevent Cross Site Scripting

Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.

Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.

Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.

Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.

Where Sticky Notes are saved in Windows 10 1607

Use this document to transfer Sticky Notes data file StickyNotes.snt to the new format

http://www.winhelponline.com/blog/recover-backup-sticky-notes-data-file-windows-10/

Restore:

%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState

  • Close Sticky Notes
  • Create a new folder named Legacy
  • Under the Legacy folder, copy your existing StickyNotes.snt, and rename it to ThresholdNotes.snt
  • Start the Sticky Notes app. It reads the legacy .snt file and transfers the content to the database file automatically.

Backup

just backup following file.

%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite

How to know that a string starts/ends with a specific string in jQuery?

You can always extend String prototype like this:

//  Checks that string starts with the specific string
if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

//  Checks that string ends with the specific string...
if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function (str) {
        return this.slice(-str.length) == str;
    };
}

And use it like this:

var str = 'Hello World';

if( str.startsWith('Hello') ) {
   // your string starts with 'Hello'
}

if( str.endsWith('World') ) {
   // your string ends with 'World'
}

Permission to write to the SD card

You're right that the SD Card directory is /sdcard but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory() to get the directory:

File sdDir = Environment.getExternalStorageDirectory();

If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:

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

How to make a checkbox checked with jQuery?

from jQuery v1.6 use prop

to check that is checkd or not

$('input:radio').prop('checked') // will return true or false

and to make it checkd use

$("input").prop("checked", true);

Example: Communication between Activity and Service using Messaging

Seems to me you could've saved some memory by declaring your activity with "implements Handler.Callback"

XmlSerializer giving FileNotFoundException at constructor

Troubleshooting compilation errors on the other hand is very complicated. These problems manifest themselves in a FileNotFoundException with the message:

File or assembly name abcdef.dll, or one of its dependencies, was not found. File name: "abcdef.dll"
   at System.Reflection.Assembly.nLoad( ... )
   at System.Reflection.Assembly.InternalLoad( ... )
   at System.Reflection.Assembly.Load(...)
   at System.CodeDom.Compiler.CompilerResults.get_CompiledAssembly() 

You may wonder what a file not found exception has to do with instantiating a serializer object, but remember: the constructor writes C# files and tries to compile them. The call stack of this exception provides some good information to support that suspicion. The exception occurred while the XmlSerializer attempted to load an assembly generated by CodeDOM calling the System.Reflection.Assembly.Load method. The exception does not provide an explanation as to why the assembly that the XmlSerializer was supposed to create was not present. In general, the assembly is not present because the compilation failed, which may happen because, under rare circumstances, the serialization attributes produce code that the C# compiler fails to compile.

Note This error also occurs when the XmlSerializer runs under an account or a security environment that is not able to access the temp directory.

Source: http://msdn.microsoft.com/en-us/library/aa302290.aspx

using setTimeout on promise chain

The shorter ES6 version of the answer:

const delay = t => new Promise(resolve => setTimeout(resolve, t));

And then you can do:

delay(3000).then(() => console.log('Hello'));

What is 'PermSize' in Java?

The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.

Use Font Awesome Icon in Placeholder

@Elli's answer can work in FontAwesome 5, but it requires using the correct font name and using the specific CSS for the version you want. For example when using FA5 Free, I could not get it to work if I included the all.css, but it worked fine if I included the solid.css:

_x000D_
_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/solid.css">_x000D_
_x000D_
<input type="text" placeholder="&#xF002; Search" style="font-family: Arial, 'Font Awesome 5 Free'" />
_x000D_
_x000D_
_x000D_

For FA5 Pro the font name is 'Font Awesome 5 Pro'

The difference between "require(x)" and "import x"

This simple diagram that helps me to understand the difference between require and import.

enter image description here

Apart from that,

You can't selectively load only the pieces you need with require but with imports, you can selectively load only the pieces you need. That can save memory.

Loading is synchronous(step by step) for require on the other hand import can be asynchronous(without waiting for previous import) so it can perform a little better than require.

No Exception while type casting with a null in java

You can cast null to any reference type. You can also call methods which handle a null as an argument, e.g. System.out.println(Object) does, but you cannot reference a null value and call a method on it.

BTW There is a tricky situation where it appears you can call static methods on null values.

Thread t = null;
t.yield(); // Calls static method Thread.yield() so this runs fine.

Is there a "theirs" version of "git merge -s ours"?

See Junio Hamano's widely cited answer: if you're going to discard committed content, just discard the commits, or at any rate keep it out of the main history. Why bother everyone in the future reading commit messages from commits that have nothing to offer?

But sometimes there are administrative requirements, or perhaps some other reason. For those situations where you really have to record commits that contribute nothing, you want:

(edit: wow, did I manage to get this wrong before. This one works.)

git update-ref HEAD $(
        git commit-tree -m 'completely superseding with branchB content' \
                        -p HEAD -p branchB    branchB:
)
git reset --hard

Plot smooth line with PyPlot

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.

Object spread vs. Object.assign

I think one big difference between the spread operator and Object.assign that doesn't seem to be mentioned in the current answers is that the spread operator will not copy the the source object’s prototype to the target object. If you want to add properties to an object and you don't want to change what instance it is of, then you will have to use Object.assign.

Edit: I've actually realised that my example is misleading. The spread operator desugars to Object.assign with the first parameter set to an empty object. In my code example below, I put error as the first parameter of the Object.assign call so the two are not equivalent. The first parameter of Object.assign is actually modified and then returned which is why it retains its prototype. I have added another example below:

_x000D_
_x000D_
const error = new Error();
error instanceof Error // true

const errorExtendedUsingSpread = {
  ...error,
  ...{
    someValue: true
  }
};
errorExtendedUsingSpread instanceof Error; // false

// What the spread operator desugars into
const errorExtendedUsingImmutableObjectAssign = Object.assign({}, error, {
    someValue: true
});
errorExtendedUsingImmutableObjectAssign instanceof Error; // false

// The error object is modified and returned here so it keeps its prototypes
const errorExtendedUsingAssign = Object.assign(error, {
  someValue: true
});
errorExtendedUsingAssign instanceof Error; // true
_x000D_
_x000D_
_x000D_

See also: https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md

Laravel Unknown Column 'updated_at'

Nice answer by Alex and Sameer, but maybe just additional info on why is necessary to put

public $timestamps = false;

Timestamps are nicely explained on official Laravel page:

By default, Eloquent expects created_at and updated_at columns to exist on your >tables. If you do not wish to have these columns automatically managed by >Eloquent, set the $timestamps property on your model to false.

Getting only Month and Year from SQL DATE

select month(dateField), year(dateField)

SQL SERVER: Get total days between two dates

SQL Server DateDiff

DECLARE @startdate datetime2 = '2007-05-05 12:10:09.3312722';
DECLARE @enddate datetime2 = '2009-05-04 12:10:09.3312722'; 
SELECT DATEDIFF(day, @startdate, @enddate);

How to clear a textbox once a button is clicked in WPF?

You can use Any of the statement given below to clear the text of the text box on button click:

  1. textBoxName.Text = string.Empty;
  2. textBoxName.Clear();
  3. textBoxName.Text = "";

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

Using Java 8 to convert a list of objects into a string obtained from the toString() method

There is a collector joining in the API. It's a static method in Collectors.

list.stream().map(Object::toString).collect(Collectors.joining(","))

Not perfect because of the necessary call of toString, but works. Different delimiters are possible.

Joining Multiple Tables - Oracle

You are doing a cartesian join. This means that if you wouldn't have even have the single where clause, the number of results you get would be book_customer size times books size times book_order size times publisher size.

In order words, the result set gets blown up because you didn't add meaningful join clauses. Your correct query should look something like this:

SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date", p.publishername
FROM book_customer bc, books b, book_order bo, publisher p
WHERE bc.book_id = b.book_id
AND bo.book_id = b.book_id
(etc.)
AND publishername = 'PRINTING IS US';

Note: usually it is adviced to not use the implicit joins like in this query, but use the INNER JOIN syntax. I am assuming however, that this syntax is used in your study material so I've left it in.

How to Find Item in Dictionary Collection?

Of course, if you want to make sure it's in there otherwise fail then this works:

thisTag = _tags[key];

NOTE: This will fail if the key,value pair does not exists but sometimes that is exactly what you want. This way you can catch it and do something about the error. I would only do this if I am certain that the key,value pair is or should be in the dictionary and if not I want it to know about it via the throw.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

I ran into the same issue and the above answers didn't help. I need to debug and find it.

 <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.6.0-cdh5.13.1</version>
        <exclusions>
            <exclusion>
                <artifactId>jsp-api</artifactId>
                <groupId>javax.servlet.jsp</groupId>
            </exclusion>
        </exclusions>
    </dependency>

After excluding the jsp-api, it worked for me.

How to set margin of ImageView using code, not xml

android.view.ViewGroup.MarginLayoutParams has a method setMargins(left, top, right, bottom). Direct subclasses are: FrameLayout.LayoutParams, LinearLayout.LayoutParams and RelativeLayout.LayoutParams.

Using e.g. LinearLayout:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
imageView.setLayoutParams(lp);

MarginLayoutParams

This sets the margins in pixels. To scale it use

context.getResources().getDisplayMetrics().density

DisplayMetrics

Current date without time

it should be as simple as

DateTime.Today

Cast Int to enum in Java

MyEnum.values()[x] is an expensive operation. If the performance is a concern, you may want to do something like this:

public enum MyEnum {
    EnumValue1,
    EnumValue2;

    public static MyEnum fromInteger(int x) {
        switch(x) {
        case 0:
            return EnumValue1;
        case 1:
            return EnumValue2;
        }
        return null;
    }
}

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

The specific characters that can be stored in a varchar or char column depend upon the column collation. See my answer here for a script that will show you these for the various different collations.

If you want to find all characters outside a particular ASCII range see my answer here.

Java Timer vs ExecutorService?

According to Java Concurrency in Practice:

  • Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn't.
  • Timer has only one execution thread, so long-running task can delay other tasks. ScheduledThreadPoolExecutor can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing ThreadFactory).
  • Runtime exceptions thrown in TimerTask kill that one thread, thus making Timer dead :-( ... i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want (by overriding afterExecute method from ThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run.

If you can use ScheduledThreadExecutor instead of Timer, do so.

One more thing... while ScheduledThreadExecutor isn't available in Java 1.4 library, there is a Backport of JSR 166 (java.util.concurrent) to Java 1.2, 1.3, 1.4, which has the ScheduledThreadExecutor class.

How do I prevent and/or handle a StackOverflowException?

With .NET 4.0 You can add the HandleProcessCorruptedStateExceptions attribute from System.Runtime.ExceptionServices to the method containing the try/catch block. This really worked! Maybe not recommended but works.

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;

namespace ExceptionCatching
{
    public class Test
    {
        public void StackOverflow()
        {
            StackOverflow();
        }

        public void CustomException()
        {
            throw new Exception();
        }

        public unsafe void AccessViolation()
        {
            byte b = *(byte*)(8762765876);
        }
    }

    class Program
    {
        [HandleProcessCorruptedStateExceptions]
        static void Main(string[] args)
        {
            Test test = new Test();
            try {
                //test.StackOverflow();
                test.AccessViolation();
                //test.CustomException();
            }
            catch
            {
                Console.WriteLine("Caught.");
            }

            Console.WriteLine("End of program");

        }

    }      
}

Android: Internet connectivity change listener

I have noticed that no one mentioned WorkManger solution which is better and support most of android devices.

You should have a Worker with network constraint AND it will fired only if network available, i.e:

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val worker = OneTimeWorkRequestBuilder<MyWorker>().setConstraints(constraints).build()

And in worker you do whatever you want once connection back, you may fire the worker periodically .

i.e:

inside dowork() callback:

notifierLiveData.postValue(info)

Running code after Spring Boot starts

ApplicationReadyEvent is really only useful if the task you want to perform is not a requirement for correct server operation. Starting an async task to monitor something for changes is a good example.

If, however your server is in a 'not ready' state until the task is completed then it's better to implement SmartInitializingSingleton because you'll get the callback before your REST port has been opened and your server is open for business.

Don't be tempted to use @PostConstruct for tasks that should only happen once ever. You'll get a rude surprise when you notice it being called multiple times...

ERROR in Cannot find module 'node-sass'

If you run

npm install node-sass

and it still doesn't work remember to change permission to folder

Centering text in a table in Twitter Bootstrap

just give the surrounding <tr> a custom class like:

<tr class="custom_centered">
  <td>1</td>
  <td>2</td>
  <td>3</td>
</tr>

and have the css only select <td>s that are inside an <tr> with your custom class.

tr.custom_centered td {
  text-align: center;
}

like this you don't risk to override other tables or even override a bootstrap base class (like some of my predecessors suggested).

Has anyone gotten HTML emails working with Twitter Bootstrap?

What about Bootstrap Email? This seems to really nice and compatible with bootstrap 4.

How to find char in string and get all the indexes?

def find_idx(str, ch):
    yield [i for i, c in enumerate(str) if c == ch]

for idx in find_idx('babak karchini is a beginner in python ', 'i'):
    print(idx)

output:

[11, 13, 15, 23, 29]

Telling Python to save a .txt file to a certain directory on Windows and Mac

Using an absolute or relative string as the filename.

name_of_file = input("What is the name of the file: ")
completeName = '/home/user/Documents'+ name_of_file + ".txt"
file1 = open(completeName , "w")
toFile = input("Write what you want into the field")
file1.write(toFile)
file1.close()

How to force JS to do math instead of putting two strings together

I'm adding this answer because I don't see it here.

One way is to put a '+' character in front of the value

example:

var x = +'11.5' + +'3.5'

x === 15

I have found this to be the simplest way

In this case, the line:

dots = document.getElementById("txt").value;

could be changed to

dots = +(document.getElementById("txt").value);

to force it to a number

NOTE:

+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5

How to print jquery object/array

var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];

$.each(arrofobject, function(index, val) {
    console.log(val.category);
});

Conversion failed when converting the varchar value 'simple, ' to data type int

In order to avoid such error you could use CASE + ISNUMERIC to handle scenarios when you cannot convert to int.
Change

CONVERT(INT, CONVERT(VARCHAR(12), a.value))

To

CONVERT(INT,
        CASE
        WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
        ELSE 0 END) 

Basically this is saying if you cannot convert me to int assign value of 0 (in my example)

Alternatively you can look at this article about creating a custom function that will check if a.value is number: http://www.tek-tips.com/faqs.cfm?fid=6423

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

As Usman said, i had a lot of trouble first time, I was following a tutorial. I had not set my directory to the project directory hence got this error.

I solved the issue by

  1. Setting the correct root directory to where my project was cd myproject
  2. Compile the app - ng serve

That was it.

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

SSL peer shut down incorrectly in Java

I had a similar issue that was resolved by unchecking the option in java advanced security for "Use SSL 2.0 compatible ClientHello format.

Firefox 'Cross-Origin Request Blocked' despite headers

I found that my problem was that the server I've sent the cross request to had a certificate that was not trusted.

If you want to connect to a cross domain with https, you have to add an exception for this certificate first.

You can do this by visiting the blocked link once and addibng the exception.

How to make canvas responsive

extending accepted answer with jquery

what if you want to add more canvas?, this jquery.each answer it

responsiveCanvas(); //first init
$(window).resize(function(){
  responsiveCanvas(); //every resizing
  stage.update(); //update the canvas, stage is object of easeljs

});
function responsiveCanvas(target){
  $(canvas).each(function(e){

    var parentWidth = $(this).parent().outerWidth();
    var parentHeight =  $(this).parent().outerHeight();
    $(this).attr('width', parentWidth);
    $(this).attr('height', parentHeight);
    console.log(parentWidth);
  })

}

it will do all the job for you

why we dont set the width or the height via css or style? because it will stretch your canvas instead of make it into expecting size

Markdown: continue numbered list

Notice how in Macmade's solution, you can see an extra line of code above the "Code block".

Here are two better solutions:

  1. Indent the code block by an extra 4 spaces (so usually 8, in this nested list example, 12). This will put the code in a <pre> element. On SO, you can even specify syntax highlight with a
    <!-- language: lang-js --> indented by 4 spaces (+1 here due to the nested list).

    1. item 1
    2. item 2

      Code.block('JavaScript', maybe)?
      
    3. item 3

  2. Or, just put the Code block within backticks and indent by 4 spaces (here, 1 extra because of the nested list). You'll get a regular indented text paragraph, with a <code> element inside it. This one you can't syntax-highlight:

    1. item 1
    2. item 2

      Code block

    3. item 3

Note: you can click "edit" on this answer to see the underlying Markdown code. No need to save ;)

How can I pass arguments to a batch file?

Simple solution(even though question is old)

Test1.bat

echo off
echo "Batch started"
set arg1=%1
echo "arg1 is %arg1%"
echo on
pause

CallTest1.bat

call "C:\Temp\Test1.bat" pass123

output

YourLocalPath>call "C:\Temp\test.bat" pass123

YourLocalPath>echo off
"Batch started"
"arg1 is pass123"

YourLocalPath>pause
Press any key to continue . . .

Where YourLocalPath is current directory path.

To keep things simple store the command param in variable and use variable for comparison.

Its not just simple to write but its simple to maintain as well so if later some other person or you read your script after long period of time, it will be easy to understand and maintain.

To write code inline : see other answers.

How to echo or print an array in PHP?

I know this is an old question but if you want a parseable PHP representation you could use:

$parseablePhpCode = var_export($yourVariable,true);

If you echo the exported code to a file.php (with a return statement) you may require it as

$yourVariable = require('file.php');

Passing variables in remote ssh command

(This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)

You can feed data right through the standard input of the ssh command and read that from the remote location.

In the following example,

  1. an indexed array is filled (for convenience) with the names of the variables whose values you want to retrieve on the remote side.
  2. For each of those variables, we give to ssh a null-terminated line giving the name and value of the variable.
  3. In the shh command itself, we loop through these lines to initialise the required variables.
# Initialize examples of variables.
# The first one even contains whitespace and a newline.
readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
readonly BAR=ygnàgyààynygbjrbjrb

# Make a list of what you want to pass through SSH.
# (The “unset” is just in case someone exported
# an associative array with this name.)
unset -v VAR_NAMES
readonly VAR_NAMES=(
    FOO
    BAR
)

for name in "${VAR_NAMES[@]}"
do
    printf '%s %s\0' "$name" "${!name}"
done | ssh [email protected] '
    while read -rd '"''"' name value
    do
        export "$name"="$value"
    done

    # Check
    printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
'

Output:

FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]

If you don’t need to export those, you should be able to use declare instead of export.

A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:

$ ssh [email protected] 'read foo' <<< "$foo"

What's the meaning of exception code "EXC_I386_GPFLT"?

I wondered why this appeared during my unit tests.

I have added a method declaration to a protocol which included throws; but the potentially throwing method wasn't even used in that particular test. Enabling Zombies in test sounded like too much trouble.

Turns out a ?K clean did the trick. I'm always flabberghasted when that solves actual problems.

Carriage return in C?

Program prints ab, goes back one character and prints si overwriting the b resulting asi. Carriage return returns the caret to the first column of the current line. That means the ha will be printed over as and the result is hai

Print a variable in hexadecimal in Python

A way that will fail if your input string isn't valid pairs of hex characters...:

>>> import binascii
>>> ' '.join(hex(ord(i)) for i in binascii.unhexlify('deadbeef'))
'0xde 0xad 0xbe 0xef'

Android Device Chooser -- device not showing up

Another alternative: on modern Apple iMac's, the USB port closest to the outside edge of the machine never works with ADB, whereas all others work fine. I've seen this on two different iMacs, possibly those are USB 1.0 ports (or something equally stupid) - or it's a general manufacturing defect.

Plugging USB cables (new, old, high quality or cheap) into all other USB ports works fine, but plugging into that one fails ADB

NB: plugging into that port works for file-transfer, etc - it's only ADB that breaks.

How to directly move camera to current location in Google Maps Android API v2?

I am explaining, How to get current location and Directly move to the camera to current location with assuming that you have implemented map-v2. For more details, You can refer official doc.

Add location service in gradle

implementation "com.google.android.gms:play-services-location:11.0.1"

Add location permission in manifest file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Make sure you ask for RunTimePermission. I am using Ask-Permission for that. Its easy to use.

Now refer below code to get the current location and display it on a map.

private FusedLocationProviderClient mFusedLocationProviderClient;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFusedLocationProviderClient = LocationServices
                .getFusedLocationProviderClient(getActivity());

}

private void getDeviceLocation() {
        try {
            if (mLocationPermissionGranted) {
                Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
                locationResult.addOnCompleteListener(new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            // Set the map's camera position to the current location of the device.
                            Location location = task.getResult();
                            LatLng currentLatLng = new LatLng(location.getLatitude(),
                                    location.getLongitude());
                            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(currentLatLng,
                                    DEFAULT_ZOOM);
                            googleMap.moveCamera(update);
                        }
                    }
                });
            }
        } catch (SecurityException e) {
            Log.e("Exception: %s", e.getMessage());
        }
}

When user granted location permission call above getDeviceLocation() method

private void updateLocationUI() {
        if (googleMap == null) {
            return;
        }
        try {
            if (mLocationPermissionGranted) {
                googleMap.setMyLocationEnabled(true);
                googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                getDeviceLocation();
            } else {
                googleMap.setMyLocationEnabled(false);
                googleMap.getUiSettings().setMyLocationButtonEnabled(false);
            }
        } catch (SecurityException e) {
            Log.e("Exception: %s", e.getMessage());
        }
    }

File.Move Does Not Work - File Already Exists

If file really exists and you want to replace it use below code:

string file = "c:\test\SomeFile.txt"
string moveTo = "c:\test\test\SomeFile.txt"

if (File.Exists(moveTo))
{
    File.Delete(moveTo);
}

File.Move(file, moveTo);

How to get Real IP from Visitor?

This is the most common technique I've seen:

function getUserIP() {
    if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
            $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
            return trim($addr[0]);
        } else {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

Note that it does not guarantee it you will get always the correct user IP because there are many ways to hide it.

How to terminate process from Python using pid?

Using the awesome psutil library it's pretty simple:

p = psutil.Process(pid)
p.terminate()  #or p.kill()

If you don't want to install a new library, you can use the os module:

import os
import signal

os.kill(pid, signal.SIGTERM) #or signal.SIGKILL 

See also the os.kill documentation.


If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.

Something like:

import psutil
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'StripCore.py']:
        print('Process found. Terminating it.')
        process.terminate()
        break
else:
    print('Process not found: starting it.')
    Popen(['python', 'StripCore.py'])

Sample run:

$python test_strip.py   #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.
$killall python
$python test_strip.py 
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.

Note: In previous psutil versions cmdline was an attribute instead of a method.

Camera access through browser

The Picup app is a way to take pictures from an HTML5 page and upload them to your server. It requires some extra programming on the server, but apart from PhoneGap, I have not found another way.

Set value of hidden input with jquery

Suppose you have a hidden input, named XXX, if you want to assign a value to the following

<script type="text/javascript">

    $(document).ready(function(){
    $('#XXX').val('any value');
    })
</script>

Remove all special characters with RegExp

I use RegexBuddy for debbuging my regexes it has almost all languages very usefull. Than copy/paste for the targeted language. Terrific tool and not very expensive.

So I copy/pasted your regex and your issue is that [,] are special characters in regex, so you need to escape them. So the regex should be : /!@#$^&%*()+=-[\x5B\x5D]\/{}|:<>?,./im

Update style of a component onScroll in React.js

constructor() {
    super()
      this.state = {
        change: false
      }
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll);
    console.log('add event');
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
    console.log('remove event');
  }

  handleScroll = e => {
    if (window.scrollY === 0) {
      this.setState({ change: false });
    } else if (window.scrollY > 0 ) {
      this.setState({ change: true });
    }
  }

render() { return ( <div className="main" style={{ boxShadow: this.state.change ? 0px 6px 12px rgba(3,109,136,0.14):none}} ></div>

This is how I did it and works perfect.

How to truncate text in Angular2?

Like this:

{{ data.title | slice:0:20 }}

And if you want the ellipsis, here's a workaround

{{ data.title | slice:0:20 }}...

How to read numbers from file in Python?

To me this kind of seemingly simple problem is what Python is all about. Especially if you're coming from a language like C++, where simple text parsing can be a pain in the butt, you'll really appreciate the functionally unit-wise solution that python can give you. I'd keep it really simple with a couple of built-in functions and some generator expressions.

You'll need open(name, mode), myfile.readlines(), mystring.split(), int(myval), and then you'll probably want to use a couple of generators to put them all together in a pythonic way.

# This opens a handle to your file, in 'r' read mode
file_handle = open('mynumbers.txt', 'r')
# Read in all the lines of your file into a list of lines
lines_list = file_handle.readlines()
# Extract dimensions from first line. Cast values to integers from strings.
cols, rows = (int(val) for val in lines_list[0].split())
# Do a double-nested list comprehension to get the rest of the data into your matrix
my_data = [[int(val) for val in line.split()] for line in lines_list[1:]]

Look up generator expressions here. They can really simplify your code into discrete functional units! Imagine doing the same thing in 4 lines in C++... It would be a monster. Especially the list generators, when I was I C++ guy I always wished I had something like that, and I'd often end up building custom functions to construct each kind of array I wanted.

Configure active profile in SpringBoot via Maven

You should use the Spring Boot Maven Plugin:

<project>  
  ...
  <build>
    ...
    <plugins>
      ...
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.1.RELEASE</version>
        <configuration>
          <profiles>
            <profile>foo</profile>
            <profile>bar</profile>
          </profiles>
        </configuration>
        ...
      </plugin>
      ...
    </plugins>
    ...
  </build>
  ...
</project>

How to print Two-Dimensional Array like table

A part from @djechlin answer, you should change the rows and columns. Since you are taken as 7 rows and 5 columns, but actually you want is 7 columns and 5 rows.

Do this way:-

int twoDm[][]= new int[5][7];

for(i=0;i<5;i++){
    for(j=0;j<7;j++) {
        System.out.print(twoDm[i][j]+" ");
    }
    System.out.println("");
}

How to display and hide a div with CSS?

You need

.abc,.ab {
    display: none;
}

#f:hover ~ .ab {
    display: block;
}

#s:hover ~ .abc {
    display: block;
}

#s:hover ~ .a,
#f:hover ~ .a{
    display: none;
}

Updated demo at http://jsfiddle.net/gaby/n5fzB/2/


The problem in your original CSS was that the , in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a means #f:hover ~ .abc and .a. You set that to display:none so it was always set to be hidden for all .a elements.

How to echo xml file in php

The best solution is to add to your apache .htaccess file the following line after RewriteEngine On

RewriteRule ^sitemap\.xml$ sitemap.php [L]

and then simply having a file sitemap.php in your root folder that would be normally accessible via http://www.yoursite.com/sitemap.xml, the default URL where all search engines will firstly search.

The file sitemap.php shall start with

<?php
//Saturday, 11 January 2020 @kevin

header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

<url>
  <loc>https://www.yoursite.com/</loc>
  <lastmod>2020-01-08T13:06:14+00:00</lastmod>
  <priority>1.00</priority>
</url>


</urlset>

it works :)

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

Here's where it gets confusing, the text states "If the balance factor of R is 1, it means the insertion occurred on the (external) right side of that node and a left rotation is needed". But from m understanding the text said (as I quoted) that if the balance factor was within [-1, 1] then there was no need for balancing?

R is the right-hand child of the current node N.

If balance(N) = +2, then you need a rotation of some sort. But which rotation to use? Well, it depends on balance(R): if balance(R) = +1 then you need a left-rotation on N; but if balance(R) = -1 then you will need a double-rotation of some sort.

Run-time error '1004' - Method 'Range' of object'_Global' failed

Change

Range(DataImportColumn & DataImportRow).Offset(0, 2).Value

to

Cells(DataImportRow,DataImportColumn).Value

When you just have the row and the column then you can use the cells() object. The syntax is Cells(Row,Column)

Also one more tip. You might want to fully qualify your Cells object. for example

ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value

WebService Client Generation Error with JDK8

Not an actual answer but more as a reference.

If you are using the jaxws Maven plugin and you get the same error message, add the mentioned property to the plugin configuration:

...
<plugin>
  <groupId>org.jvnet.jax-ws-commons</groupId>
  <artifactId>jaxws-maven-plugin</artifactId>
  <version>2.3</version>
  <configuration>
    <!-- Needed with JAXP 1.5 -->
    <vmArgs>
        <vmArg>-Djavax.xml.accessExternalSchema=all</vmArg>
    </vmArgs>
  </configuration>
</plugin>

Javascript date.getYear() returns 111 in 2011?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getYear

getYear is no longer used and has been replaced by the getFullYear method.

The getYear method returns the year minus 1900; thus:

  • For years greater than or equal to 2000, the value returned by getYear is 100 or greater. For example, if the year is 2026, getYear returns 126.
  • For years between and including 1900 and 1999, the value returned by getYear is between 0 and 99. For example, if the year is 1976, getYear returns 76.
  • For years less than 1900, the value returned by getYear is less than 0. For example, if the year is 1800, getYear returns -100.
  • To take into account years before and after 2000, you should use getFullYear instead of getYear so that the year is specified in full.

orderBy multiple fields in Angular

<select ng-model="divs" ng-options="(d.group+' - '+d.sub) for d in divisions | orderBy:['group','sub']" />

User array instead of multiple orderBY

get user timezone

On server-side it will be not as accurate as with JavaScript. Meanwhile, sometimes it is required to solve such task. Just to share the possible solution in this case I write this answer.

If you need to determine user's time zone it could be done via Geo-IP services. Some of them providing timezone. For example, this one (http://smart-ip.net/geoip-api) could help:

<?php
$ip     = $_SERVER['REMOTE_ADDR']; // means we got user's IP address 
$json   = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);

if ($ipData['timezone']) {
    $tz = new DateTimeZone( $ipData['timezone']);
    $now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
   // we can't determine a timezone - do something else...
}

How to ignore deprecation warnings in Python

None of these answers worked for me so I will post my way to solve this. I use the following at the beginning of my main.py script and it works fine.


Use the following as it is (copy-paste it):

def warn(*args, **kwargs):
    pass
import warnings
warnings.warn = warn

Example:

import "blabla"
import "blabla"

def warn(*args, **kwargs):
    pass
import warnings
warnings.warn = warn

# more code here...
# more code here...

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

Really quick and really dirty? This one-liner on the top of your script will work:

[[ $(pgrep -c "`basename \"$0\"`") -gt 1 ]] && exit

Of course, just make sure that your script name is unique. :)

UITapGestureRecognizer - single tap and double tap

Swift 3 solution:

let singleTap = UITapGestureRecognizer(target: self, action:#selector(self.singleTapAction(_:)))
singleTap.numberOfTapsRequired = 1
view.addGestureRecognizer(singleTap)

let doubleTap = UITapGestureRecognizer(target: self, action:#selector(self.doubleTapAction(_:)))
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)

singleTap.require(toFail: doubleTap)

In the code line singleTap.require(toFail: doubleTap) we are forcing the single tap to wait and ensure that the tap event is not a double tap.