Programs & Examples On #Open basedir

Setting in PHP.INI limiting whether PHP can access files outside of the specified directory tree.

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

I'm posting an answer from another thread because it's what worked well for me, the trick is to add support for both architectures :

Posting this because I could not find a direct answer and had to look at a couple of different posts to get what I wanted done...

I was able to use the x86 Accelerated (HAXM) emulator by simply adding this to my Module's build.gradle script Inside android{} block:

splits {
        abi {
            enable true
            reset()
            include 'x86', 'armeabi-v7a'
            universalApk true
        }
    }

Run (build)... Now there will be a (yourapp)-x86-debug.apk in your output folder. I'm sure there's a way to automate installing upon Run but I just start my preferred HAXM emulator and use command line:

adb install (yourapp)-x86-debug.apk

ReportViewer Client Print Control "Unable to load client print control"?

In my case when I get this message IE suggest me to install add-on from Microsoft. After install problem solved.

My software:
IE9 but work also on older
SQL SERVER 2008 R2

How to auto generate migrations with Sequelize CLI from Sequelize models?

I created a small working "migration file generator". It creates files which are working perfectly fine using sequelize db:migrate - even with foreign keys!

You can find it here: https://gist.github.com/manuelbieh/ae3b028286db10770c81

I tested it in an application with 12 different models covering:

  • STRING, TEXT, ENUM, INTEGER, BOOLEAN, FLOAT as DataTypes

  • Foreign key constraints (even reciprocal (user belongsTo team, team belongsTo user as owner))

  • Indexes with name, method and unique properties

jQuery or JavaScript auto click

You haven't provided your javascript code, but the usual cause of this type of issue is not waiting till the page is loaded. Remember that most javascript is executed before the DOM is loaded, so code trying to manipulate it won't work.

To run code after the page has finished loading, use the $(document).ready callback:

$(document).ready(function(){
  $('#some-id').trigger('click');
});

How to install libusb in Ubuntu

"I need to install it to the folder of my C program." Why?

Include usb.h:

#include <usb.h>

and remember to add -lusb to gcc:

gcc -o example example.c -lusb

This work fine for me.

Casting variables in Java

Suppose you wanted to cast a String to a File (yes it does not make any sense), you cannot cast it directly because the File class is not a child and not a parent of the String class (and the compiler complains).

But you could cast your String to Object, because a String is an Object (Object is parent). Then you could cast this object to a File, because a File is an Object.

So all you operations are 'legal' from a typing point of view at compile time, but it does not mean that it will work at runtime !

File f = (File)(Object) "Stupid cast";

The compiler will allow this even if it does not make sense, but it will crash at runtime with this exception:

Exception in thread "main" java.lang.ClassCastException:
    java.lang.String cannot be cast to java.io.File

Message 'src refspec master does not match any' when pushing commits in Git

This worked for me, resetting to remote master the repository:

git checkout master
git commit -a -m "your comment"
git push origin master

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Event binding on dynamically created elements?

Take note of "MAIN" class the element is placed, for example,

<div class="container">
     <ul class="select">
         <li> First</li>
         <li>Second</li>
    </ul>
</div>

In the above scenario, the MAIN object the jQuery will watch is "container".

Then you will basically have elements names under container such as ul, li, and select:

$(document).ready(function(e) {
    $('.container').on( 'click',".select", function(e) {
        alert("CLICKED");
    });
 });

Defining constant string in Java?

It would look like this:

public static final String WELCOME_MESSAGE = "Hello, welcome to the server";

If the constants are for use just in a single class, you'd want to make them private instead of public.

Difference between xcopy and robocopy

The differences I could see is that Robocopy has a lot more options, but I didn't find any of them particularly helpful unless I'm doing something special.

I did some benchmarking of several copy routines and found XCOPY and ROBOCOPY to be the fastest, but to my surprise, XCOPY consistently edged out Robocopy.

It's ironic that robocopy retries a copy that fails, but it also failed a lot in my benchmark tests, where xcopy never did.

I did full file (byte by byte) file compares after my benchmark tests.

Here are the switches I used with robocopy in my tests:

 **"/E /R:1 /W:1 /NP /NFL /NDL"**.  

If anyone knows a faster combination (other than removing /E, which I need), I'd love to hear.

Another interesting/disappointing thing with robocopy is that if a copy does fail, by default it retries 1,000,000 times with a 30 second delay between each try. If you are running a long batch file unattended, you may be very disappointed when you come back after a few hours to find it's still trying to copy a particular file.

The /R and /W switches let you change this behavior.

  • With /R you can tell it how many times to retry,
  • /W let's you specify the wait time before retries.

If there's a way to attach files here, I can share my results.

  • My tests were all done on the same computer and
  • copied files from one external drive to another external,
  • both on USB 3.0 ports.

I also included FastCopy and Windows Copy in my tests and each test was run 10 times. Note, the differences were pretty significant. The 95% confidence intervals had no overlap.

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

Try,

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

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

C# Handle System.UnauthorizedAccessException in LINQ

Run PowerShell command from command prompt (no ps1 script)

Here is the only answer that managed to work for my problem, got it figured out with the help of this webpage (nice reference).

powershell -command "& {&'some-command' someParam}"

Also, here is a neat way to do multiple commands:

powershell -command "& {&'some-command' someParam}"; "& {&'some-command' -SpecificArg someParam}"

For example, this is how I ran my 2 commands:

powershell -command "& {&'Import-Module' AppLocker}"; "& {&'Set-AppLockerPolicy' -XmlPolicy myXmlFilePath.xml}"

How can I properly handle 404 in ASP.NET MVC?

Requirements for 404

The following are my requirements for a 404 solution and below i show how i implement it:

  • I want to handle matched routes with bad actions
  • I want to handle matched routes with bad controllers
  • I want to handle un-matched routes (arbitrary urls that my app can't understand) - i don't want these bubbling up to the Global.asax or IIS because then i can't redirect back into my MVC app properly
  • I want a way to handle in the same manner as above, custom 404s - like when an ID is submitted for an object that does not exist (maybe deleted)
  • I want all my 404s to return an MVC view (not a static page) to which i can pump more data later if necessary (good 404 designs) and they must return the HTTP 404 status code

Solution

I think you should save Application_Error in the Global.asax for higher things, like unhandled exceptions and logging (like Shay Jacoby's answer shows) but not 404 handling. This is why my suggestion keeps the 404 stuff out of the Global.asax file.

Step 1: Have a common place for 404-error logic

This is a good idea for maintainability. Use an ErrorController so that future improvements to your well designed 404 page can adapt easily. Also, make sure your response has the 404 code!

public class ErrorController : MyController
{
    #region Http404

    public ActionResult Http404(string url)
    {
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        var model = new NotFoundViewModel();
        // If the url is relative ('NotFound' route) then replace with Requested path
        model.RequestedUrl = Request.Url.OriginalString.Contains(url) & Request.Url.OriginalString != url ?
            Request.Url.OriginalString : url;
        // Dont get the user stuck in a 'retry loop' by
        // allowing the Referrer to be the same as the Request
        model.ReferrerUrl = Request.UrlReferrer != null &&
            Request.UrlReferrer.OriginalString != model.RequestedUrl ?
            Request.UrlReferrer.OriginalString : null;

        // TODO: insert ILogger here

        return View("NotFound", model);
    }
    public class NotFoundViewModel
    {
        public string RequestedUrl { get; set; }
        public string ReferrerUrl { get; set; }
    }

    #endregion
}

Step 2: Use a base Controller class so you can easily invoke your custom 404 action and wire up HandleUnknownAction

404s in ASP.NET MVC need to be caught at a number of places. The first is HandleUnknownAction.

The InvokeHttp404 method creates a common place for re-routing to the ErrorController and our new Http404 action. Think DRY!

public abstract class MyController : Controller
{
    #region Http404 handling

    protected override void HandleUnknownAction(string actionName)
    {
        // If controller is ErrorController dont 'nest' exceptions
        if (this.GetType() != typeof(ErrorController))
            this.InvokeHttp404(HttpContext);
    }

    public ActionResult InvokeHttp404(HttpContextBase httpContext)
    {
        IController errorController = ObjectFactory.GetInstance<ErrorController>();
        var errorRoute = new RouteData();
        errorRoute.Values.Add("controller", "Error");
        errorRoute.Values.Add("action", "Http404");
        errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString);
        errorController.Execute(new RequestContext(
             httpContext, errorRoute));

        return new EmptyResult();
    }

    #endregion
}

Step 3: Use Dependency Injection in your Controller Factory and wire up 404 HttpExceptions

Like so (it doesn't have to be StructureMap):

MVC1.0 example:

public class StructureMapControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(Type controllerType)
    {
        try
        {
            if (controllerType == null)
                return base.GetControllerInstance(controllerType);
        }
        catch (HttpException ex)
        {
            if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound)
            {
                IController errorController = ObjectFactory.GetInstance<ErrorController>();
                ((ErrorController)errorController).InvokeHttp404(RequestContext.HttpContext);

                return errorController;
            }
            else
                throw ex;
        }

        return ObjectFactory.GetInstance(controllerType) as Controller;
    }
}

MVC2.0 example:

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        try
        {
            if (controllerType == null)
                return base.GetControllerInstance(requestContext, controllerType);
        }
        catch (HttpException ex)
        {
            if (ex.GetHttpCode() == 404)
            {
                IController errorController = ObjectFactory.GetInstance<ErrorController>();
                ((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext);

                return errorController;
            }
            else
                throw ex;
        }

        return ObjectFactory.GetInstance(controllerType) as Controller;
    }

I think its better to catch errors closer to where they originate. This is why i prefer the above to the Application_Error handler.

This is the second place to catch 404s.

Step 4: Add a NotFound route to Global.asax for urls that fail to be parsed into your app

This route should point to our Http404 action. Notice the url param will be a relative url because the routing engine is stripping the domain part here? That is why we have all that conditional url logic in Step 1.

        routes.MapRoute("NotFound", "{*url}", 
            new { controller = "Error", action = "Http404" });

This is the third and final place to catch 404s in an MVC app that you don't invoke yourself. If you don't catch unmatched routes here then MVC will pass the problem up to ASP.NET (Global.asax) and you don't really want that in this situation.

Step 5: Finally, invoke 404s when your app can't find something

Like when a bad ID is submitted to my Loans controller (derives from MyController):

    //
    // GET: /Detail/ID

    public ActionResult Detail(int ID)
    {
        Loan loan = this._svc.GetLoans().WithID(ID);
        if (loan == null)
            return this.InvokeHttp404(HttpContext);
        else
            return View(loan);
    }

It would be nice if all this could be hooked up in fewer places with less code but i think this solution is more maintainable, more testable and fairly pragmatic.

Thanks for the feedback so far. I'd love to get more.

NOTE: This has been edited significantly from my original answer but the purpose/requirements are the same - this is why i have not added a new answer

Button Width Match Parent

Using a ListTile also works as well, since a list fills the entire width:

ListTile(
  title: new RaisedButton(...),
),

How do I add a linker or compile flag in a CMake file?

The preferred way to specify toolchain-specific options is using CMake's toolchain facility. This ensures that there is a clean division between:

  • instructions on how to organise source files into targets -- expressed in CMakeLists.txt files, entirely toolchain-agnostic; and
  • details of how certain toolchains should be configured -- separated into CMake script files, extensible by future users of your project, scalable.

Ideally, there should be no compiler/linker flags in your CMakeLists.txt files -- even within if/endif blocks. And your program should build for the native platform with the default toolchain (e.g. GCC on GNU/Linux or MSVC on Windows) without any additional flags.

Steps to add a toolchain:

  1. Create a file, e.g. arm-linux-androideadi-gcc.cmake with global toolchain settings:

    set(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)
    set(CMAKE_CXX_FLAGS_INIT "-fexceptions")
    

    (You can find an example Linux cross-compiling toolchain file here.)

  2. When you want to generate a build system with this toolchain, specify the CMAKE_TOOLCHAIN_FILE parameter on the command line:

    mkdir android-arm-build && cd android-arm-build
    cmake -DCMAKE_TOOLCHAIN_FILE=$(pwd)/../arm-linux-androideadi-gcc.cmake ..
    

    (Note: you cannot use a relative path.)

  3. Build as normal:

    cmake --build .
    

Toolchain files make cross-compilation easier, but they have other uses:

  • Hardened diagnostics for your unit tests.

    set(CMAKE_CXX_FLAGS_INIT "-Werror -Wall -Wextra -Wpedantic")
    
  • Tricky-to-configure development tools.

    # toolchain file for use with gcov
    set(CMAKE_CXX_FLAGS_INIT "--coverage -fno-exceptions -g")
    
  • Enhanced safety checks.

    # toolchain file for use with gdb
    set(CMAKE_CXX_FLAGS_DEBUG_INIT "-fsanitize=address,undefined -fsanitize-undefined-trap-on-error")
    set(CMAKE_EXE_LINKER_FLAGS_INIT "-fsanitize=address,undefined -static-libasan")
    

Difference between Width:100% and width:100vw?

vw and vh stand for viewport width and viewport height respectively.

The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

Additional notes

Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.

You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.

When increasing the size of VARCHAR column on a large table could there be any problems?

Changing to Varchar(1200) from Varchar(200) should cause you no issue as it is only a metadata change and as SQL server 2008 truncates excesive blank spaces you should see no performance differences either so in short there should be no issues with making the change.

Changing nav-bar color after scrolling?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
      $(window).scroll(function() {_x000D_
        if ($(document).scrollTop() >1290 ) { _x000D_
          $(".navbar-fixed-top").css("background-color", "rgb(255, 160, 160)"); _x000D_
        }else if ($(document).scrollTop() >850) { _x000D_
            $(".navbar-fixed-top").css("background-color", "black"); _x000D_
          }else if ($(document).scrollTop() >350) { _x000D_
            $(".navbar-fixed-top").css("background-color", "rgba(47, 73, 158, 0.514)"); _x000D_
          }_x000D_
         else {_x000D_
          $(".navbar-fixed-top").css("background-color", "red"); _x000D_
        }_x000D_
      });_x000D_
    });
_x000D_
@import url(https://fonts.googleapis.com/css?family=Roboto+Slab:400,700|Open+Sans);_x000D_
body {_x000D_
  font-family: "Roboto Slab", sans-serif;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
h1,_x000D_
h2,_x000D_
h3,_x000D_
h4 {_x000D_
  font-family: "Open Sans", sans-serif;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  padding-top: 50px;_x000D_
}_x000D_
_x000D_
#home {_x000D_
  padding-top: 20%;_x000D_
  background-image: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://s31.postimg.org/l5q32ptln/coffee_cup_mug_apple.jpg');_x000D_
  background-attachment: fixed;_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center center;_x000D_
  position: relative;_x000D_
  height: 100vh;_x000D_
}_x000D_
_x000D_
#home h2 {_x000D_
  color: white;_x000D_
  font-size: 4em;_x000D_
}_x000D_
_x000D_
#home h4 {_x000D_
  color: white;_x000D_
  font-size: 2em;_x000D_
}_x000D_
_x000D_
#home ul {_x000D_
  list-style-type: none;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
#home li {_x000D_
  padding-bottom: 12px;_x000D_
  padding-right: 12px;_x000D_
  display: inline;_x000D_
}_x000D_
_x000D_
#home li:last-child {_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
@media (max-width: 710px) {_x000D_
  #home li {_x000D_
    display: block;_x000D_
  }_x000D_
}_x000D_
_x000D_
.img-style {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  margin-top: 50px;_x000D_
}_x000D_
_x000D_
#about {_x000D_
  height: 100vh;_x000D_
  padding-top: 10%;_x000D_
  background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://s32.postimg.org/sm6o6617p/photo_1432821596592_e2c18b78144f.jpg');_x000D_
  background-attachment: fixed;_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center center;_x000D_
  position: relative;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
#about p,_x000D_
li {_x000D_
  font-size: 17px;_x000D_
}_x000D_
_x000D_
.navbar.color-yellow {_x000D_
  background-color: yellow;_x000D_
  height: 50px;_x000D_
  color: yellow;_x000D_
}_x000D_
_x000D_
.navbar.color-change {_x000D_
  background-color: #f45b69;_x000D_
  height: 50px;_x000D_
  color: rgba(255, 254, 255, 0.8);_x000D_
}_x000D_
_x000D_
#portfolio {_x000D_
  padding-top: 30px;_x000D_
  rgba(226,_x000D_
  226,_x000D_
  226,_x000D_
  1);_x000D_
  background: linear-gradient(to bottom, rgba(226, 226, 226, 1) 0%, rgba(209, 209, 209, 1) 25%, rgba(219, 219, 219, 1) 57%, rgba(254, 254, 254, 1) 100%);_x000D_
  height: 100vh;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li {_x000D_
  float: left;_x000D_
  width: 32.22%;_x000D_
  overflow: hidden;_x000D_
  margin: 6px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li:hover .overly {_x000D_
  opacity: 1;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li:hover .position-center {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  -webkit-transform: translate(0%, -50%);_x000D_
  -moz-transform: translate(0%, -50%);_x000D_
  -ms-transform: translate(0%, -50%);_x000D_
  transform: translate(0%, -50%);_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li a {_x000D_
  display: block;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li a h2 {_x000D_
  font-size: 22px;_x000D_
  text-transform: uppercase;_x000D_
  letter-spacing: 1px;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li a p {_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li a span {_x000D_
  font-style: italic;_x000D_
  font-size: 13px;_x000D_
  color: #655E7A;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant .overly {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  background: rgba(0, 0, 0, 0.9);_x000D_
  opacity: 0;_x000D_
  -webkit-transition: .3s all;_x000D_
  -o-transition: .3s all;_x000D_
  transition: .3s all;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant .position-center {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 10%;_x000D_
  -webkit-transform: translate(0%, 50%);_x000D_
  -moz-transform: translate(0%, 50%);_x000D_
  -ms-transform: translate(0%, 50%);_x000D_
  transform: translate(0%, 50%);_x000D_
  -webkit-transition: .5s all;_x000D_
  -o-transition: .5s all;_x000D_
  transition: .5s all;_x000D_
}_x000D_
_x000D_
#contact {_x000D_
  height: 100vh;_x000D_
  padding-top: 10%;_x000D_
  background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://s32.postimg.org/ex6q1qxkl/pexels_photo.jpg");_x000D_
  background-attachment: fixed;_x000D_
  background-size: cover;_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center center;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
#contact h3 {_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
footer ul {_x000D_
  list-style-type: none;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
footer li {_x000D_
  display: inline;_x000D_
  padding-right: 10px;_x000D_
}_x000D_
_x000D_
footer li:last-child {_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
footer p {_x000D_
  color: grey;_x000D_
  font-size: 11px;_x000D_
}
_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="UTF-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
  <meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
  <title>Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <header>_x000D_
    <nav class="navbar navbar-default navbar-fixed-top" role="navigation">_x000D_
      <div class="container">_x000D_
        <div class="navbar-header">_x000D_
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapse" aria-expanded="false">_x000D_
          <span class="sr-only">Toggle navigation</span>_x000D_
          <span class="icon-bar"></span>_x000D_
          <span class="icon-bar"></span>_x000D_
          <span class="icon-bar"></span>_x000D_
        </button>_x000D_
          <a class="navbar-brand" href="#featured">Portfolio</a>_x000D_
        </div>_x000D_
        <!-- navbar-header -->_x000D_
        <div class="collapse navbar-collapse" id="collapse">_x000D_
          <ul class="nav navbar-nav navbar-right">_x000D_
            <li class="active"><a href="#home">Home</a></li>_x000D_
            <li><a href="#about">About</a></li>_x000D_
            <li><a href="#portfolio">Portfolio</a></li>_x000D_
            <li><a href="#contact">Contact</a></li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- collapse navbar-collapse -->_x000D_
_x000D_
      </div>_x000D_
      <!-- container -->_x000D_
    </nav>_x000D_
  </header>_x000D_
_x000D_
  <div class="main">_x000D_
    <div class="row " id="home" data-speed="2" data-type="background">_x000D_
      <div class="container">_x000D_
        <h2 class="text-center">Welcome to my portfolio</h2>_x000D_
        <h4 class="text-center">Where awesomeness is crafted</h4>_x000D_
        <hr>_x000D_
        <ul>_x000D_
          <li><a href="https://github.com/vamshi121" class="btn btn-primary"><i class="fa fa-github"></i> GitHub</a></li>_x000D_
          <li><a href="https://tn.linkedin.com/in/mannemvamshi" class="btn btn-primary"><i class="fa fa-linkedin"></i> LinkedIn</a></li>_x000D_
          <li><a href="https://freecodecamp.com/" class="btn btn-primary"><i class="fa fa-fire"></i> FreeCodeCamp</a></li>_x000D_
_x000D_
        </ul>_x000D_
      </div>_x000D_
      <!--container-->_x000D_
_x000D_
    </div>_x000D_
    <!--home-->_x000D_
    <div class="row" id="about" data-speed="2" data-type="background">_x000D_
      <div class="container">_x000D_
        <div class="row">_x000D_
          <div class="col-md-5 col-md-offset-1">_x000D_
            <h2>About me</h2>_x000D_
            <p>Courteous and Enthusiastic,I'm interested in IT and around in its globe. I began to be fascinated by web programming i.e, building websites and developing cross-platform apps.I'm always looking for new ventures where i can learn evolve and_x000D_
              expertise._x000D_
              </marquee>_x000D_
          </div>_x000D_
          </p>_x000D_
          <p>My skills are:_x000D_
            <ul>_x000D_
              <li> Front-end : HTML5, CSS3 , jQuery, Bootstrap, AngularJS</li>_x000D_
              <li>Back-end: Ruby on Rails</li>_x000D_
              <li>Methodology: Agile, TDD</li>_x000D_
            </ul>_x000D_
          </p>_x000D_
        </div>_x000D_
        <!--col-md-5-->_x000D_
        <div class="col-md-4 col-md-offset-1">_x000D_
          <img class="img-circle img-style hidden-xs" src="https://www.triketech.site/images/log.png" />_x000D_
        </div>_x000D_
      </div>_x000D_
      <!--row-->_x000D_
    </div>_x000D_
    <!--container-->_x000D_
  </div>_x000D_
  <!--about-->_x000D_
  <div class="row" id="portfolio" data-speed="2" data-type="background">_x000D_
    <div class="container">_x000D_
      <h2 class="text-center">Portfolio projects</h2>_x000D_
      <div class="row">_x000D_
        <div class="col-md-12">_x000D_
          <div class="block">_x000D_
            <div class="portfolio-contant">_x000D_
              <ul id="portfolio-contant-active">_x000D_
                <li class="mix Branding">_x000D_
                  <a href="#">_x000D_
                    <img src="#" alt="">_x000D_
                    <div class="overly">_x000D_
                      <div class="position-center">_x000D_
                        <h2>Local Support</h2>_x000D_
_x000D_
_x000D_
                      </div>_x000D_
                    </div>_x000D_
                    <!--overly-->_x000D_
                  </a>_x000D_
                </li>_x000D_
              </ul>_x000D_
            </div>_x000D_
            <!--portfolio-contant-->_x000D_
          </div>_x000D_
          <!--block-->_x000D_
        </div>_x000D_
        <!--col-->_x000D_
      </div>_x000D_
      <!--row-->_x000D_
    </div>_x000D_
    <!--container-->_x000D_
  </div>_x000D_
  <!--portfolio-->_x000D_
  <div class="row" id="contact" data-speed="2" data-type="background">_x000D_
    <div class="container">_x000D_
      <div class="col-md-4 col-md-offset-1">_x000D_
        <h3>Contact me at:</h3>_x000D_
        <h3>[email protected]</h3>_x000D_
      </div>_x000D_
      <!--col-md-4-->_x000D_
    </div>_x000D_
    <!--container-->_x000D_
  </div>_x000D_
  <!--contact-->_x000D_
  </div>_x000D_
  <!--main-->_x000D_
  <footer>_x000D_
    <ul>_x000D_
      <li><a href="#home">Home</a> </li>_x000D_
      <li><a href="#about">About</a> </li>_x000D_
      <li><a href="#portfolio">Portfolio</a> </li>_x000D_
      <li><a href="#contact">Contact</a> </li>_x000D_
    </ul>_x000D_
    <p class="text-center">Copyright &copy; - All Rights Reserved. </p>_x000D_
  </footer>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

<script> 
    $(document).ready(function(){
      $(window).scroll(function() {
        if ($(document).scrollTop() >1920 ) { 
          $(".navbar-fixed-top").css("background-color", "rgb(255, 160, 160)"); 
        } else if ($(document).scrollTop() >1580) { 
            $(".navbar-fixed-top").css("background-color", "black"); 
        } else if ($(document).scrollTop() >620) { 
            $(".navbar-fixed-top").css("background-color", "rgba(47, 73, 158, 0.514)"); 
        } else {
          $(".navbar-fixed-top").css("background-color", "transparent"); 
        }
      });
    });
</script>

SHA512 vs. Blowfish and Bcrypt

Blowfish is not a hashing algorithm. It's an encryption algorithm. What that means is that you can encrypt something using blowfish, and then later on you can decrypt it back to plain text.

SHA512 is a hashing algorithm. That means that (in theory) once you hash the input you can't get the original input back again.

They're 2 different things, designed to be used for different tasks. There is no 'correct' answer to "is blowfish better than SHA512?" You might as well ask "are apples better than kangaroos?"

If you want to read some more on the topic here's some links:

Change background of LinearLayout in Android

 android:background="@drawable/ic_launcher"

should be included inside Layout tab. where ic_launcher is image name that u can put inside project folder/res/drawable . you can copy any number of images and make it as background

':app:lintVitalRelease' error when generating signed apk

Try below code

buildTypes {
    release {
        lintOptions {
            disable 'MissingTranslation'
            checkReleaseBuilds false
            abortOnError false
        }
        minifyEnabled false
        signingConfig signingConfigs.release
    }
}

Oracle PL/SQL : remove "space characters" from a string

Since you're comfortable with regular expressions, you probably want to use the REGEXP_REPLACE function. If you want to eliminate anything that matches the [:space:] POSIX class

REGEXP_REPLACE( my_value, '[[:space:]]', '' )


SQL> ed
Wrote file afiedt.buf

  1  select '|' ||
  2         regexp_replace( 'foo ' || chr(9), '[[:space:]]', '' ) ||
  3         '|'
  4*   from dual
SQL> /

'|'||
-----
|foo|

If you want to leave one space in place for every set of continuous space characters, just add the + to the regular expression and use a space as the replacement character.

with x as (
  select 'abc 123  234     5' str
    from dual
)
select regexp_replace( str, '[[:space:]]+', ' ' )
  from x

How do you rename a Git tag?

For the adventurous it can be done in one command:

mv .git/refs/tags/OLD .git/refs/tags/NEW

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

You can do

var color =  System.Drawing.ColorTranslator.FromHtml("#FFFFFF");

Or this (you will need the System.Windows.Media namespace)

var color = (Color)ColorConverter.ConvertFromString("#FFFFFF");

jQuery .live() vs .on() method for adding a click event after loading dynamic html

If you want the click handler to work for an element that gets loaded dynamically, then you set the event handler on a parent object (that does not get loaded dynamically) and give it a selector that matches your dynamic object like this:

$('#parent').on("click", "#child", function() {});

The event handler will be attached to the #parent object and anytime a click event bubbles up to it that originated on #child, it will fire your click handler. This is called delegated event handling (the event handling is delegated to a parent object).

It's done this way because you can attach the event to the #parent object even when the #child object does not exist yet, but when it later exists and gets clicked on, the click event will bubble up to the #parent object, it will see that it originated on #child and there is an event handler for a click on #child and fire your event.

Reloading .env variables without restarting server (Laravel 5, shared hosting)

In config/database.php I changed the default DB connection from mysql to sqlite. I deleted the .env file (actually renamed it) and created the sqlite file with touch storage/database.sqlite. The migration worked with sqlite.

Then I switched back the config/database.php default DB connection to mysql and recovered the .env file. The migration worked with mysql.

It doesn't make sense I guess. Maybe was something serverside.

Why is PHP session_destroy() not working?

Perhaps is way too late to respond but, make sure your session is initialized before destroying it.

session_start() ;
session_destroy() ;

i.e. you cannot destroy a session in logout.php if you initialized your session in index.php. You must start the session in logout.php before destroying it.

JTable How to refresh table model after insert delete or update the data.

The faster way for your case is:

    jTable.repaint(); // Repaint all the component (all Cells).

The optimized way when one or few cell change:

    ((AbstractTableModel) jTable.getModel()).fireTableCellUpdated(x, 0); // Repaint one cell.

Evaluate empty or null JSTL c tags

Here's an example of how to validate a int and a String that you pass from the Java Controller to the JSP file.

MainController.java:

@RequestMapping(value="/ImportJavaToJSP")
public ModelAndView getImportJavaToJSP() {
    ModelAndView model2= new ModelAndView("importJavaToJSPExamples");

    int someNumberValue=6;
    String someStringValue="abcdefg";
    //model2.addObject("someNumber", someNumberValue);
    model2.addObject("someString", someStringValue);

    return model2;
}

importJavaToJSPExamples.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<p>${someNumber}</p>
<c:if test="${not empty someNumber}">
    <p>someNumber is Not Empty</p>
</c:if>
<c:if test="${empty someNumber}">
    <p>someNumber is Empty</p>
</c:if>
<p>${someString}</p>
<c:if test="${not empty someString}">
    <p>someString is Not Empty</p>
</c:if>
<c:if test="${empty someString}">
    <p>someString is Empty</p>
</c:if>

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

After further reading, and confirmation from Linus G Thiel above, I found I simply had to,

  • Downgrade to Node.js 0.6.12
  • And either,
    • Install Mocha as global
    • Add ./node_modules/.bin to my PATH

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

Sometimes all it takes to get a EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) is a missing return statement.

It certainly was my case.

Automated way to convert XML files to SQL database?

For Mysql please see the LOAD XML SyntaxDocs.

It should work without any additional XML transformation for the XML you've provided, just specify the format and define the table inside the database firsthand with matching column names:

LOAD XML LOCAL INFILE 'table1.xml'
    INTO TABLE table1
    ROWS IDENTIFIED BY '<table1>';

There is also a related question:

For Postgresql I do not know.

Remove header and footer from window.print()

Firefox :

  • Add moznomarginboxes attribute in <html>

Example :

<html moznomarginboxes mozdisallowselectionprint>

Add and remove attribute with jquery

It's because you've removed the id which is how you're finding the element. This line of code is trying to add id="page_navigation1" to an element with the id named page_navigation1, but it doesn't exist (because you deleted the attribute):

$("#page_navigation1").attr("id","page_navigation1");

Demo: jsFiddle

If you want to add and remove a class that makes your <div> red use:

$( '#page_navigation1' ).addClass( 'red-class' );

And:

$( '#page_navigation1' ).removeClass( 'red-class' );

Where red-class is:

.red-class {
    background-color: red;
}

How can I String.Format a TimeSpan object with a custom format in .NET?

I would go with

myTimeSpan.ToString("hh\\:mm\\:ss");

Get just the filename from a path in a Bash script

Here is an easy way to get the file name from a path:

echo "$PATH" | rev | cut -d"/" -f1 | rev

To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):

cut -d"." -f1

remove table row with specific id

$('#3').remove();

Might not work with numeric id's though.

Domain Account keeping locking out with correct password every few minutes

Finally i found my problem. SQL Reporting Service was causing my account lockout. Stop and try, after confirm no more passwords bad attempts i should reconfigure reporting services service account ---Not at Service Properties, it is in Reporting Service own config--.

How many characters can a Java String have?

The heap part gets worse, my friends. UTF-16 isn't guaranteed to be limited to 16 bits and can expand to 32

What is the difference between include and require in Ruby?

What's the difference between "include" and "require" in Ruby?

Answer:

The include and require methods do very different things.

The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method.

The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.

Source

So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require.

Oddly enough, Ruby's require is analogous to C's include, while Ruby's include is almost nothing like C's include.

How to set Android camera orientation properly?

From other member and my problem:

Camera Rotation issue depend on different Devices and certain Version.

Version 1.6: to fix the Rotation Issue, and it is good for most of devices

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {   
            p.set("orientation", "portrait");
            p.set("rotation",90);
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {                               
            p.set("orientation", "landscape");          
            p.set("rotation", 90);
        }

Version 2.1: depend on kind of devices, for example, Cannt fix the issue with XPeria X10, but it is good for X8, and Mini

Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);

Version 2.2: not for all devices

camera.setDisplayOrientation(90);

http://code.google.com/p/android/issues/detail?id=1193#c42

How to use hex color values

public static func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)
    }

    if ((cString.characters.count) == 6) {

        var rgbValue:UInt32 = 0
        Scanner(string: cString).scanHexInt32(&rgbValue)

        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }else if ((cString.characters.count) == 8) {

        var rgbValue:UInt32 = 0
        Scanner(string: cString).scanHexInt32(&rgbValue)

        return UIColor(
            red: CGFloat((rgbValue & 0x00FF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x0000FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x000000FF) / 255.0,
            alpha: CGFloat((rgbValue & 0xFF000000) >> 24) / 255.0
        )
    }else{
        return UIColor.gray
    }
}

How to use

var color: UIColor = hexStringToUIColor(hex: "#00ff00"); // Without transparency
var colorWithTransparency: UIColor = hexStringToUIColor(hex: "#dd00ff00"); // With transparency

raw_input function in Python

The raw_input() function reads a line from input (i.e. the user) and returns a string

Python v3.x as raw_input() was renamed to input()

PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

Ref: Docs Python 3

Completely Remove MySQL Ubuntu 14.04 LTS

This is what saved me. Apparently the depackager tries to put things in the wrong tmp folder.

https://askubuntu.com/a/248860

Socket send and receive byte array

First, do not use DataOutputStream unless it’s really necessary. Second:

Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(message);

Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

I would always use sp_executesql these days, all it really is is a wrapper for EXEC which handles parameters & variables.

However do not forget about OPTION RECOMPILE when tuning queries on very large databases, especially where you have data spanned over more than one database and are using a CONSTRAINT to limit index scans.

Unless you use OPTION RECOMPILE, SQL server will attempt to create a "one size fits all" execution plan for your query, and will run a full index scan each time it is run.

This is much less efficient than a seek, and means it is potentially scanning entire indexes which are constrained to ranges which you are not even querying :@

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

WPF TemplateBinding vs RelativeSource TemplatedParent

TemplateBinding - More limiting than using regular Binding

  • More efficient than a Binding but it has less functionality
  • Only works inside a ControlTemplate's visual tree
  • Doesn't work with properties on Freezables
  • Doesn't work within a ControlTemplate's Trigger
  • Provides a shortcut in setting properties(not as verbose),e.g. {TemplateBinding targetProperty}

Regular Binding - Does not have above limitations of TemplateBinding

  • Respects Parent Properties
  • Resets Target Values to clear out any explicitly set values
  • Example: <Ellipse Fill="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Background}"/>

How to open in default browser in C#

For those finding this question in dotnet core. I found a solution here

Code:

private void OpenUrl(string url)
{
    try
    {
        Process.Start(url);
    }
    catch
    {
        // hack because of this: https://github.com/dotnet/corefx/issues/10361
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            url = url.Replace("&", "^&");
            Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            Process.Start("xdg-open", url);
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            Process.Start("open", url);
        }
        else
        {
            throw;
        }
    }
}

Using async/await with a forEach loop

You can use Array.prototype.forEach, but async/await is not so compatible. This is because the promise returned from an async callback expects to be resolved, but Array.prototype.forEach does not resolve any promises from the execution of its callback. So then, you can use forEach, but you'll have to handle the promise resolution yourself.

Here is a way to read and print each file in series using Array.prototype.forEach

async function printFilesInSeries () {
  const files = await getFilePaths()

  let promiseChain = Promise.resolve()
  files.forEach((file) => {
    promiseChain = promiseChain.then(() => {
      fs.readFile(file, 'utf8').then((contents) => {
        console.log(contents)
      })
    })
  })
  await promiseChain
}

Here is a way (still using Array.prototype.forEach) to print the contents of files in parallel

async function printFilesInParallel () {
  const files = await getFilePaths()

  const promises = []
  files.forEach((file) => {
    promises.push(
      fs.readFile(file, 'utf8').then((contents) => {
        console.log(contents)
      })
    )
  })
  await Promise.all(promises)
}

Select values from XML field in SQL Server 2008

Given that the XML field is named 'xmlField'...

SELECT 
[xmlField].value('(/person//firstName/node())[1]', 'nvarchar(max)') as FirstName,
[xmlField].value('(/person//lastName/node())[1]', 'nvarchar(max)') as LastName
FROM [myTable]

How to pass parameters to a partial view in ASP.NET MVC?

Just:

@Html.Partial("PartialName", Model);

How to tell which disk Windows Used to Boot

Unless C: is not the drive that windows booted from.
Parse the %SystemRoot% variable, it contains the location of the windows folder (i.e. c:\windows).

How to sort by dates excel?

For example 8/12/1976. Copy your date column. Highlight the copied column and click Data> Text to Columns> Delimited> Next. In the delimiters column check "Other" and input / and then click Next and Finish. You'll have 3 columns and the first column will be 1/8. Highlight it and click the comma in the Number section and it will give you the month as 8.00, so then reduce it by clicking the comma in Home/Numbers and you'll now have 8 in the first column, 18 in the second column and 1976 in the third column. In the first empty cell to the right use the concatenate function and leave out the year column. If your month is column A, day is column B and year is column C, it will look like this: =concatenate(A2,"/",B2) and hit enter. It will look like 8/18, however, when you click on the cell you'll see the concatenate formula. Highlight the cell(s), then copy and paste special values. Now you can sort by date. It's really quick when you get the hang of it.

How to determine day of week by passing specific date?

public class TryDateFormats {
    public static void main(String[] args) throws ParseException {
        String month = "08";
        String day = "05";
        String year = "2015";
        String inputDateStr = String.format("%s/%s/%s", day, month, year);
        Date inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inputDate);
        String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
        System.out.println(dayOfWeek);
    }
}

Convert time span value to format "hh:mm Am/Pm" using C#

At first, you need to convert time span to DateTime structure:

var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)

Then you need to convert the value to string with Short Time format

var result = dt.ToString("t"); // Convert to string using Short Time format

How to download a Nuget package without nuget.exe or Visual Studio extension?

Although building the URL or using tools is still possible, it is not needed anymore.

https://www.nuget.org/ currently has a download link named "Download package", that is available even if you don't have an account on the site.

(at the bottom of the right column).


Example of EntityFramework's detail page: https://www.nuget.org/packages/EntityFramework/: (Updated after comment of kwitee.)

Example of EntityFramework's detail page

How do I install a Python package with a .whl file?

I am in the same boat as the OP.

Using a Windows command prompt, from directory:

C:\Python34\Scripts>
pip install wheel

seemed to work.

Changing directory to where the whl was located, it just tells me 'pip is not recognized'. Going back to C:\Python34\Scripts>, then using the full command above to provide the 'where/its/downloaded' location, it says Requirement 'scikit_image-...-win32.whl' looks like a filename, but the filename does not exist.

So I dropped a copy of the .whl in Python34/Scripts, ran the exact same command over again (with the --find-links= still going to the other folder), and this time it worked.

Get selected element's outer HTML

you can also just do it this way

document.getElementById(id).outerHTML

where id is the id of the element that you are looking for

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

How can I disable inherited css styles?

Simplest is to class-ify all of the divs:

div.rounded {
    background: #CFFEB6 url('tr.gif') no-repeat top right;
}
div.rounded div.br {
    background: url('br.gif') no-repeat bottom right;
}
div.rounded div.br div.bl {
    background: url('bl.gif') no-repeat bottom left;
}
div.rounded div.br div.bl div.inner {
    padding: 10px;
}
.button {
    border: 1px solid #999;
     background:#eeeeee url('');
    text-align:center;
}
.button:hover {
    background-color:#c4e2f2;
}

And then use:

<div class='round'><div class='br'><div class='bl'><div class='inner'>
<div class='button'><a href='#'>Test</a></div>
</div></div></div></div>

How can I send and receive WebSocket messages on the server side?

PHP Implementation:

function encode($message)
{
    $length = strlen($message);

    $bytesHeader = [];
    $bytesHeader[0] = 129; // 0x1 text frame (FIN + opcode)

    if ($length <= 125) {
            $bytesHeader[1] = $length;
    } else if ($length >= 126 && $length <= 65535) {
            $bytesHeader[1] = 126;
            $bytesHeader[2] = ( $length >> 8 ) & 255;
            $bytesHeader[3] = ( $length      ) & 255;
    } else {
            $bytesHeader[1] = 127;
            $bytesHeader[2] = ( $length >> 56 ) & 255;
            $bytesHeader[3] = ( $length >> 48 ) & 255;
            $bytesHeader[4] = ( $length >> 40 ) & 255;
            $bytesHeader[5] = ( $length >> 32 ) & 255;
            $bytesHeader[6] = ( $length >> 24 ) & 255;
            $bytesHeader[7] = ( $length >> 16 ) & 255;
            $bytesHeader[8] = ( $length >>  8 ) & 255;
            $bytesHeader[9] = ( $length       ) & 255;
    }

    $str = implode(array_map("chr", $bytesHeader)) . $message;

    return $str;
}

Java rounding up to an int using Math.ceil

Also to convert a number from integer to real number you can add a dot:

int total = (int) Math.ceil(157/32.);

And the result of (157/32.) will be real too. ;)

Get loop count inside a Python FOR loop

Try using itertools.count([n])

Extracting the top 5 maximum values in excel

There 3 functions you want to look at here:

I ran a sample in Excel with your OPS values in Column B and Players in Column C, see below:

Excel sample

  • In Cells A13 to A17, the values 1 to 5 were inserted to specify the nth highest value.
  • In Cell B13, the following formula was added: =LARGE($B$2:$B$11, A13)
  • In Cell C13, the following formula was added: =INDEX($C$2:$C$11,MATCH(B13,$B$2:$B$11,0))
  • These formulae get the highest ranking OPS and Player based on the value in A13.
  • Simply select and drag to copy these formulae down to the next 4 cells which will reference the corresponding ranking in Column A.

How can I beautify JSON programmatically?

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

How to resolve a Java Rounding Double issue

As the previous answers stated, this is a consequence of doing floating point arithmetic.

As a previous poster suggested, When you are doing numeric calculations, use java.math.BigDecimal.

However, there is a gotcha to using BigDecimal. When you are converting from the double value to a BigDecimal, you have a choice of using a new BigDecimal(double) constructor or the BigDecimal.valueOf(double) static factory method. Use the static factory method.

The double constructor converts the entire precision of the double to a BigDecimal while the static factory effectively converts it to a String, then converts that to a BigDecimal.

This becomes relevant when you are running into those subtle rounding errors. A number might display as .585, but internally its value is '0.58499999999999996447286321199499070644378662109375'. If you used the BigDecimal constructor, you would get the number that is NOT equal to 0.585, while the static method would give you a value equal to 0.585.

double value = 0.585;
System.out.println(new BigDecimal(value));
System.out.println(BigDecimal.valueOf(value));

on my system gives

0.58499999999999996447286321199499070644378662109375
0.585

Forward host port to docker container

You could also create an ssh tunnel.

docker-compose.yml:

---

version: '2'

services:
  kibana:
    image: "kibana:4.5.1"
    links:
      - elasticsearch
    volumes:
      - ./config/kibana:/opt/kibana/config:ro

  elasticsearch:
    build:
      context: .
      dockerfile: ./docker/Dockerfile.tunnel
    entrypoint: ssh
    command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"

docker/Dockerfile.tunnel:

FROM buildpack-deps:jessie

RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive \
    apt-get -y install ssh && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
    chmod 600 /root/.ssh/config && \
    chown $USER:$USER -R /root/.ssh

config/ssh/config:

# Elasticsearch Server
Host elasticsearch
    HostName jump.host.czerasz.com
    User czerasz
    ForwardAgent yes
    IdentityFile ~/.ssh/id_rsa

This way the elasticsearch has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.

Get all rows from SQLite

Cursor cursor = myDb.viewData();

        if (cursor.moveToFirst()){
              do {
                 String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
                 String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
                 String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
                 String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));

                 }while (cursor.moveToNext());

                }

                cursor.requery();

Check if a string matches a regex in Bash script

You can use the test construct, [[ ]], along with the regular expression match operator, =~, to check if a string matches a regex pattern.

For your specific case, you can write:

[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"

Or more a accurate test:

[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
#           |^^^^^^^^ ^^^^^^ ^^^^^^  ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
#           |   |     ^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^ |
#           |   |          |                   |              |
#           |   |           \                  |              |
#           | --year--   --month--           --day--          |
#           |          either 01...09      either 01..09     end of line
# start of line            or 10,11,12         or 10..29
#                                              or 30, 31

That is, you can define a regex in Bash matching the format you want. This way you can do:

[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"

where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.


In other shells you can use grep. If your shell is POSIX compliant, do

(echo "$date" | grep -Eq  ^regex$) && echo "matched" || echo "did not match"

In fish, which is not POSIX-compliant, you can do

echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"

How to set 777 permission on a particular folder?

go to FileZilla and select which folder you will be give 777 permission, then right click set permission 777 and select check box, then ok.

Select unique values with 'select' function in 'dplyr' library

Just to add to the other answers, if you would prefer to return a vector rather than a dataframe, you have the following options:

dplyr < 0.7.0

Enclose the dplyr functions in a parentheses and combine it with $ syntax:

(mtcars %>% distinct(cyl))$cyl

dplyr >= 0.7.0

Use the pull verb:

mtcars %>% distinct(cyl) %>% pull()

Common MySQL fields and their appropriate data types

In my experience, first name/last name fields should be at least 48 characters -- there are names from some countries such as Malaysia or India that are very long in their full form.

Phone numbers and postcodes you should always treat as text, not numbers. The normal reason given is that there are postcodes that begin with 0, and in some countries, phone numbers can also begin with 0. But the real reason is that they aren't numbers -- they're identifiers that happen to be made up of numerical digits (and that's ignoring countries like Canada that have letters in their postcodes). So store them in a text field.

In MySQL you can use VARCHAR fields for this type of information. Whilst it sounds lazy, it means you don't have to be too concerned about the right minimum size.

CSS: How can I set image size relative to parent height?

If all your trying to do is fill the div this might help someone else, if aspect ratio is not important, is responsive.

.img-fill > img {
  min-height: 100%;
  min-width: 100%;  
}

List of All Folders and Sub-folders

find . -type d > list.txt

Will list all directories and subdirectories under the current path. If you want to list all of the directories under a path other than the current one, change the . to that other path.

If you want to exclude certain directories, you can filter them out with a negative condition:

find . -type d ! -name "~snapshot" > list.txt

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

when your URL pattern is wrong, this error may be occurred.

eg. If you wrote @WebServlet("login"), this error will be shown. The correct one is @WebServlet("/login").

Make header and footer files to be included in multiple html pages

Must you use html file structure with JavaScript? Have you considered using PHP instead so that you can use simple PHP include object?

If you convert the file names of your .html pages to .php - then at the top of each of your .php pages you can use one line of code to include the content from your header.php

<?php include('header.php'); ?>

Do the same in the footer of each page to include the content from your footer.php file

<?php include('footer.php'); ?>

No JavaScript / Jquery or additional included files required.

NB You could also convert your .html files to .php files using the following in your .htaccess file

# re-write html to php
RewriteRule ^(.*)\.html$ $1.php [L]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]


# re-write no extension to .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

How to check whether a variable is a class or not?

This check is compatible with both Python 2.x and Python 3.x.

import six
isinstance(obj, six.class_types)

This is basically a wrapper function that performs the same check as in andrea_crotti answer.

Example:

>>> import datetime
>>> isinstance(datetime.date, six.class_types)
>>> True
>>> isinstance(datetime.date.min, six.class_types)
>>> False

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

DropDownList1.Items.FindByValue(stringValue).Selected = true; 

should work.

Most recent previous business day in Python

another simplify version

lastBusDay = datetime.datetime.today()
wk_day = datetime.date.weekday(lastBusDay)
if wk_day > 4:      #if it's Saturday or Sunday
    lastBusDay = lastBusDay - datetime.timedelta(days = wk_day-4) #then make it Friday

UIButton: set image for selected-highlighted state

Correct me if I am wrong. By doing

   [button setSelected:YES];

you are clearly changing the state of the buttons as selected. So naturally by the code you have provided the image will that for the selected state in your case checked.png

how to set ul/li bullet point color?

http://www.w3schools.com/cssref/pr_list-style-type.asp

You need to use list-style-type: to change bullet type/style and the above link has all of the options listed. As others have stated the color is changed using the color property on the ul itself

To create 'black filled' bullets, use 'disc' instead of 'circle',i.e.:

list-style-type:disc

Creating SVG elements dynamically with javascript inside HTML

Add this to html:

<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>

Try this function and adapt for you program:

var svgNS = "http://www.w3.org/2000/svg";  

function createCircle()
{
    var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
    myCircle.setAttributeNS(null,"id","mycircle");
    myCircle.setAttributeNS(null,"cx",100);
    myCircle.setAttributeNS(null,"cy",100);
    myCircle.setAttributeNS(null,"r",50);
    myCircle.setAttributeNS(null,"fill","black");
    myCircle.setAttributeNS(null,"stroke","none");

    document.getElementById("mySVG").appendChild(myCircle);
}     

Go to beginning of line without opening new line in VI

There is another way:

|

That is the "pipe" - the symbol found under the backspace in ANSI layout.

Vim quickref (:help quickref) describes it as:

N      |      to column N (default: 1)

What about wrapped lines?

If you have wrap lines enabled, 0 and | will no longer take you to the beginning of the screen line. In that case use:

g0

Again, vim quickref doc:

 g0   to first character in screen line (differs from "0"
      when lines wrap)

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

What does the "@" symbol do in Powershell?

You can also wrap the output of a cmdlet (or pipeline) in @() to ensure that what you get back is an array rather than a single item.

For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:

$results = @( dir c:\autoexec.bat)

One more thing... an empty array (like to initialize a variable) is denoted @().

Best programming based games

For a modern equivalent, check out CodeRally, it's a Java programming challenge where you write a class to control a race car. The car drives around a track trying to hit check points, refilling when the gas tank runs low, and avoiding obstacles. I think you can throw tires at your opponents. You can run a tournament with several players submitting code to a central server.

There are several other programming games listed on IBM's high school outreach page, including Robocode that others already mentioned.

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

To run batch files using java if that's you're talking about...

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`

This should do it.

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

TL;DR answer

With very few exceptions, this rule is golden:

Avoid use of !

Declare variable optional (?), not implicitly unwrapped optionals (IUO) (!)

In other words, rather use:
var nameOfDaughter: String?

Instead of:
var nameOfDaughter: String!

Unwrap optional variable using if let or guard let

Either unwrap variable like this:

if let nameOfDaughter = nameOfDaughter {
    print("My daughters name is: \(nameOfDaughter)")
}

Or like this:

guard let nameOfDaughter = nameOfDaughter else { return }
print("My daughters name is: \(nameOfDaughter)")

This answer was intended to be concise, for full comprehension read accepted answer


Resources

Add property to an array of objects

or use map

Results.map(obj=> ({ ...obj, Active: 'false' }))

Edited to reflect comment by @adrianolsk to not mutate the original and instead return a new object for each.

Read the spec

Preventing an image from being draggable or selectable without using JS

A generic solution especially for Windows Edge browser (as the -ms-user-select: none; CSS rule doesn't work):

window.ondragstart = function() {return false}

Note: This can save you having to add draggable="false" to every img tag when you still need the click event (i.e. you can't use pointer-events: none), but don't want the drag icon image to appear.

Adding input elements dynamically to form

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var max_fields = 10;_x000D_
    var wrapper = $(".container1");_x000D_
    var add_button = $(".add_form_field");_x000D_
_x000D_
    var x = 1;_x000D_
    $(add_button).click(function(e) {_x000D_
        e.preventDefault();_x000D_
        if (x < max_fields) {_x000D_
            x++;_x000D_
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
        } else {_x000D_
            alert('You Reached the limits')_x000D_
        }_x000D_
    });_x000D_
_x000D_
    $(wrapper).on("click", ".delete", function(e) {_x000D_
        e.preventDefault();_x000D_
        $(this).parent('div').remove();_x000D_
        x--;_x000D_
    })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
    <button class="add_form_field">Add New Field &nbsp; _x000D_
      <span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
    </button>_x000D_
    <div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Refer Demo Here

Open Redis port for remote connections

Did you set the bind option to allow remote access on the redis server?

Before (file /etc/redis/redis.conf)

bind 127.0.0.1

After

bind 0.0.0.0

and run sudo service redis-server restart to restart the server. If that's not the problem, you might want to check any firewalls that might block the access.

Important: If you don't use a firewall (iptables, ufw..) to control who connects to the port in use, ANYONE can connect to this Redis instance. Without using Redis' AUTH that means anyone can access/change/delete your data. Be safe!

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

Make

Make is the program that’s used to install the program that’s compiled from the source code. It’s not the Linux package manager so it doesn’t keep track of the files it installs. This makes it difficult to uninstall the files afterward.

The Make Install command copies the built program and packages into the library directory and specified locations from the makefile. These locations can vary based on the examination that’s performed by the configure script.

CheckInstall

CheckInstall is the program that’s used to install or uninstall programs that are compiled from the source code. It monitors and copies the files that are installed using the make program. It also installs the files using the Linux package manager which allows it to be uninstalled like any regular package.

The CheckInstall command is used to call the Make Install command. It monitors the files that are installed and creates a binary package from them. It also installs the binary package with the Linux package manager.

Replace "source_location.deb" and "name" with your information from the Screenshot.

Execute the following commands in the source package directory:

  1. Install CheckInstall sudo apt-get install checkinstall
  2. Run the Configure script sudo ./configure
  3. Run the Make command sudo make
  4. Run CheckInstall sudo checkinstall
  5. Reinstall the package sudo dpkg --install --force-overwrite source_location.deb
  6. Remove the package sudo apt remove name

Here's an article article I wrote that covers the whole process with explanations.

How to configure port for a Spring Boot application

The default port is : 8080 but we can customize the port number in application.properties as shown below

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
server.port = 5050 -- #here we can give any port number.

Printing string variable in Java

You are printing the wrong value. Instead if the string you print the scanners object. Try this

Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);

Difference between MEAN.js and MEAN.io

They're essentially the same... They both use swig for templating, they both use karma and mocha for tests, passport integration, nodemon, etc.

Why so similar? Mean.js is a fork of Mean.io and both initiatives were started by the same guy... Mean.io is now under the umbrella of the company Linnovate and looks like the guy (Amos Haviv) stopped his collaboration with this company and started Mean.js. You can read more about the reasons here.

Now... main (or little) differences you can see right now are:


SCAFFOLDING AND BOILERPLATE GENERATION

Mean.io uses a custom cli tool named 'mean'
Mean.js uses Yeoman Generators


MODULARITY

Mean.io uses a more self-contained node packages modularity with client and server files inside the modules.
Mean.js uses modules just in the front-end (for angular), and connects them with Express. Although they were working on vertical modules as well...


BUILD SYSTEM

Mean.io has recently moved to gulp
Mean.js uses grunt


DEPLOYMENT

Both have Dockerfiles in their respective repos, and Mean.io has one-click install on Google Compute Engine, while Mean.js can also be deployed with one-click install on Digital Ocean.


DOCUMENTATION

Mean.io has ok docs
Mean.js has AWESOME docs


COMMUNITY

Mean.io has a bigger community since it was the original boilerplate
Mean.js has less momentum but steady growth


On a personal level, I like more the philosophy and openness of MeanJS and more the traction and modules/packages approach of MeanIO. Both are nice, and you'll end probably modifying them, so you can't really go wrong picking one or the other. Just take them as starting point and as a learning exercise.


ALTERNATIVE “MEAN” SOLUTIONS

MEAN is a generic way (coined by Valeri Karpov) to describe a boilerplate/framework that takes "Mongo + Express + Angular + Node" as the base of the stack. You can find frameworks with this stack that use other denomination, some of them really good for RAD (Rapid Application Development) and building SPAs. Eg:

You also have Hackathon Starter. It doesn't have A of MEAN (it is 'MEN'), but it rocks..

Have fun!

Query Mongodb on month, day, year... of a datetime

You can use MongoDB_DataObject wrapper to perform such query like below:

$model = new MongoDB_DataObject('orders');

$model->whereAdd('MONTH(created) = 4 AND YEAR(created) = 2016');

$model->find();

while ($model->fetch()) {
    var_dump($model);
}

OR, similarly, using direct query string:

$model = new MongoDB_DataObject();

$model->query('SELECT * FROM orders WHERE MONTH(created) = 4 AND YEAR(created) = 2016');

while ($model->fetch()) {
    var_dump($model);
}

How to determine the first and last iteration in a foreach loop?

You can use the counter and array length.

    $array = array(1,2,3,4);

    $i = 0;
    $len = count($array);
    foreach ($array as $item) {
        if ($i === 0) {
            // first
        } else if ($i === $len - 1) {
            // last
        }
        // …
        $i++;
    }

Extending from two classes

it is possible

public class ParallaxViewController<T extends View & Parallaxor> extends ParallaxController<T> implements AbsListView.OnScrollListener {

//blah
}

Resize Google Maps marker icon image

As mentionned in comments, this is the updated solution in favor of Icon object with documentation.

Use Icon object

var icon = {
    url: "../res/sit_marron.png", // url
    scaledSize: new google.maps.Size(50, 50), // scaled size
    origin: new google.maps.Point(0,0), // origin
    anchor: new google.maps.Point(0, 0) // anchor
};

 posicion = new google.maps.LatLng(latitud,longitud)
 marker = new google.maps.Marker({
  position: posicion,
  map: map,
  icon: icon
 });

docker error - 'name is already in use by container'

I was running into this issue that when I run docker rm (which usually works) I would get:

Error: No such image

The easiest solution to this is removing all stopped containers by running:

docker container prune

Simplest way to restart service on a remote computer

If it doesn't require human interaction which means there will be no UI that invokes this operation and I assume it would restart at some set interval? If you have access to machine, you could just set a scheduled task to execute a batch file using good old NET STOP and NET START

net stop "DNS Client"
net start "DNS client"

or if you want to get a little more sophisticated, you could try Powershell

Xampp Access Forbidden php

Try with this code below, add it in your virtual host config. Add this lines to httpd-vhosts.conf file:

<Directory "c:/<path-to-projects>/">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order Deny,Allow
        Allow from all
        Require all granted
</Directory>

I fixed the same issue by this way. Hope it helps.

Note:

after changes please test it in incognito because you redirected by cache

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

I write this, because i coudn't find answear for the same question. In my case PID was 2484.

  1. you must find a process or service with this PID: open cmd (in Windows) and write:

    tasklist
    
  2. Find your PID in this list and read name of process or service.

  3. Now you can kill this using Task Manager

  4. find this name on Process list

  5. click End Process.

That's my case. Possibly you must open services.msc and stop Service with your PID.

On my computer xampp it worked fine :)

Is there a command to restart computer into safe mode?

In the command prompt, type the command below and press Enter.

bcdedit /enum

Under the Windows Boot Loader sections, make note of the identifier value.

To start in safe mode from command prompt :

bcdedit /set {identifier} safeboot minimal 

Then enter the command line to reboot your computer.

How to install npm peer dependencies automatically?

I solved it by rewriting package.json with the exact values warnings were about.

Warnings when running npm:

npm WARN [email protected] requires a peer of es6-shim@^0.33.3 but none was installed.
npm WARN [email protected] requires a peer of [email protected]

In package.json, write

"es6-shim": "^0.33.3",
"reflect-metadata": "0.1.2",

Then, delete node_modules directory.

Finally, run the command below:

npm install

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

This can be resolved by specifying a primary key on the @new_super table, as follows:

DECLARE @new_super TABLE (
  row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
  super_id   int
);

This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

How do I make a "div" button submit the form its sitting in?

onClick="javascript:this.form.submit();">

this in div onclick don't have attribute form, you may try this.parentNode.submit() or document.forms[0].submit() will do

Also, onClick, should be onclick, some browsers don't work with onClick

Variable not accessible when initialized outside function

It really depends on where your JavaScript code is located.

The problem is probably caused by the DOM not being loaded when the line

var systemStatus = document.getElementById("system-status");

is executed. You could try calling this in an onload event, or ideally use a DOM ready type event from a JavaScript framework.

Javascript close alert box

You actually can do this you can basically listen for this pop up to happen and then confirm true before it ever "pops up",

if(window.alert){
  return true
}

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You should only need to unbind the service in onDestroy(). Then, The warning will go.

See here.

As the Activity doc tries to explain, there are three main bind/unbind groupings you will use: onCreate() and onDestroy(), onStart() and onStop(), and onResume() and onPause().

How can I calculate the number of lines changed between two commits in Git?

I just solved this problem for myself, so I'll share what I came up with. Here's the end result:

> git summary --since=yesterday
total: 114 file changes, 13800 insertions(+) 638 deletions(-)

The underlying command looks like this:

git log --numstat --format="" "$@" | awk '{files += 1}{ins += $1}{del += $2} END{print "total: "files" files, "ins" insertions(+) "del" deletions(-)"}'

Note the $@ in the log command to pass on your arguments such as --author="Brian" or --since=yesterday.

Escaping the awk to put it into a git alias was messy, so instead, I put it into an executable script on my path (~/bin/git-stat-sum), then used the script in the alias in my .gitconfig:

[alias]
    summary = !git-stat-sum \"$@\"

And it works really well. One last thing to note is that file changes is the number of changes to files, not the number of unique files changed. That's what I was looking for, but it may not be what you expect.

Here's another example or two

git summary --author=brian
git summary master..dev
# combine them as you like
git summary --author=brian master..dev
git summary --all

Really, you should be able to replace any git log command with git summary.

Angular 4/5/6 Global Variables

I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)

Radio Buttons ng-checked with ng-model

I solved my problem simply using ng-init for default selection instead of ng-checked

<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />

EOL conversion in notepad ++

That functionality is already built into Notepad++. From the "Edit" menu, select "EOL Conversion" -> "UNIX/OSX Format".

screenshot of the option for even quicker finding (or different language versions)

You can also set the default EOL in notepad++ via "Settings" -> "Preferences" -> "New Document/Default Directory" then select "Unix/OSX" under the Format box.

MySQL: How to copy rows, but change a few fields?

If you have loads of columns in your table and don't want to type out each one you can do it using a temporary table, like;

SELECT *
INTO #Temp
FROM Table WHERE Event_ID = "120"
GO

UPDATE #TEMP
SET Column = "Changed"
GO

INSERT INTO Table
SELECT *
FROM #Temp

Animate visibility modes, GONE and VISIBLE

This is a quite old question, still comments show, that still people have problems, so here is my solution with following additional features:

  • adjust the animation (speed, type, ...)
  • does not need to extend any class
  • in my case, animateLayoutChanges has problems in the new CoordinatorLayout

Function - Example (I have this function in an utility class)

public static void animateViewVisibility(final View view, final int visibility)
{
    // cancel runnning animations and remove and listeners
    view.animate().cancel();
    view.animate().setListener(null);

    // animate making view visible
    if (visibility == View.VISIBLE)
    {
        view.animate().alpha(1f).start();
        view.setVisibility(View.VISIBLE);
    }
    // animate making view hidden (HIDDEN or INVISIBLE)
    else
    {
        view.animate().setListener(new AnimatorListenerAdapter()
        {
            @Override
            public void onAnimationEnd(Animator animation)
            {
                view.setVisibility(visibility);
            }
        }).alpha(0f).start();
    }
}

Adjust animation

After calling view.animate() you can adjust the animation to whatever you want (set duration, set interpolator and more...). You may as well hide a view by scaling it instead of adjusting it's alpha value, just replace the alpha(...) with scaleX(...) or scaleY(...) in the utility method if you want that

PHP checkbox set to check based on database value

Add this code inside your input tag

<?php if ($tag_1 == 'yes') echo "checked='checked'"; ?>

Change a Git remote HEAD to point to something besides master

(There was already basically the same question "create a git symbolic ref in remote repository", which received no universal answer.)

But there are a specific answers for various git "farms" (where multiple users can manage git repos through a restricted interface: via http and ssh): http://Github.com, http://Gitorious.org, http://repo.or.cz, Girar (http://git.altlinux.org).

These specific answers might be useful for those reading this page and thinking about these specific services.

How to merge specific files from Git branches

You can stash and stash pop the file:

git checkout branch1
git checkout branch2 file.py
git stash
git checkout branch1
git stash pop

Why is php not running?

To answer the original question "Why is php not running?" The file your browser is asking for must have the .php extension. If the file has the .html extension, php will not be executed.

rename the columns name after cbind the data

If you offer cbind a set of arguments all of whom are vectors, you will get not a dataframe, but rather a matrix, in this case an all character matrix. They have different features. You can get a dataframe if some of your arguments remain dataframes, Try:

merger <- cbind(Date =as.character(Date),
             weather1[ , c("High", "Low", "Avg..High", "Avg.Low")] , 
             ScnMov =sale$Scanned.Movement[a] )

Detecting when the 'back' button is pressed on a navbar

As purrrminator says, the answer by elitalon is not completely right, since your stuff would be executed even when popping the controller programmatically.

The solution I have found so far is not very nice, but it works for me. Besides what elitalon said, I also check whether I'm popping programmatically or not:

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  if ((self.isMovingFromParentViewController || self.isBeingDismissed)
      && !self.isPoppingProgrammatically) {
    // Do your stuff here
  }
}

You have to add that property to your controller and set it to YES before popping programmatically:

self.isPoppingProgrammatically = YES;
[self.navigationController popViewControllerAnimated:YES];

Thanks for your help!

What values for checked and selected are false?

The empty string is false as a rule.

Apparently the empty string is not respected as empty in all browsers and the presence of the checked attribute is taken to mean checked. So the entire attribute must either be present or omitted.

Row count on the Filtered data

Rowz = Application.WorksheetFunction.Subtotal(2, Range("A2:A" & Rows(Rows.Count).End(xlUp).Row))

This worked for me quite well

Safely casting long to int in Java

DONT: This is not a solution!

My first approach was:

public int longToInt(long theLongOne) {
  return Long.valueOf(theLongOne).intValue();
}

But that merely just casts the long to an int, potentially creating new Long instances or retrieving them from the Long pool.


The drawbacks

  1. Long.valueOf creates a new Long instance if the number is not within Long's pool range [-128, 127].

  2. The intValue implementation does nothing more than:

    return (int)value;
    

So this can be considered even worse than just casting the long to int.

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

How to stop mysqld

When mysql was installed with Homebrew, the following command did the trick for me:

brew services stop mysql

HTML5 Canvas background image

Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img> element placed under the canvas. To draw a background onto the canvas element you can do something like the following:

Live Demo

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

canvas.width = 903;
canvas.height = 657;


var background = new Image();
background.src = "http://www.samskirrow.com/background.png";

// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
    ctx.drawImage(background,0,0);   
}

// Draw whatever else over top of it on the canvas.

Failed Apache2 start, no error log

On Apache on Linux there might be a problem that the configuration cannot be checked because of a problem with environment variables not being set. This is a false positive which only occurs when running apache2 -S from commandline (See previous answer from @simhumileco). For instance Config variable ${APACHE_RUN_DIR} is not defined.

In order to fix this run source /etc/apache2/envvars from the commandline and then run `apache2 -S' to get to the real (possible) problems.

root@fileserver:~# apache2 -S
[Thu Apr 30 10:42:06.822719 2020] [core:warn] [pid 24624] AH00111: Config variable ${APACHE_RUN_DIR} is not defined
apache2: Syntax error on line 80 of /etc/apache2/apache2.conf: DefaultRuntimeDir must be a valid directory, absolute or relative to ServerRoot
root@fileserver:~# source /etc/apache2/envvars
root@fileserver:/root# apache2 -S
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
VirtualHost configuration:
<----snip---->
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex ldap-cache: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33
root@fileserver:/root#

How to change the Title of the window in Qt?

I know this is years later but I ran into the same problem. The solution I found was to change the window title in main.cpp. I guess once the w.show(); is called the window title can no longer be changed. In my case I just wanted the title to reflect the current directory and it works.

int main(int argc, char *argv[]) 
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle(QDir::currentPath());
w.show();

return a.exec();
}

Remove a character at a certain position in a string - javascript

Hi starbeamrainbowlabs ,

You can do this with the following:

var oldValue = "pic quality, hello" ;
var newValue =  "hello";
var oldValueLength = oldValue.length ;
var newValueLength = newValue.length ;
var from = oldValue.search(newValue) ;
var to = from + newValueLength ;
var nes = oldValue.substr(0,from) + oldValue.substr(to,oldValueLength);
console.log(nes);

I tested this in my javascript console so you can also check this out Thanks

Using Mockito's generic "any()" method

Since Java 8 you can use the argument-less any method and the type argument will get inferred by the compiler:

verify(bar).doStuff(any());

Explanation

The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).

In this case the parameter type of doStuff will be the target type for any(), and the return value type of any() will get chosen to match that argument type.

This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.


Primitive types

This doesn't work with primitive types, unfortunately:

public interface IBar {
    void doPrimitiveStuff(int i);
}

verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead

The problem is that the compiler will infer Integer as the return value type of any(). Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null. The runtime will try to unbox the return value by calling the intValue method on it before passing it to doStuff, and the exception gets thrown.

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

I was getting this error; I just put a WHERE clause for the field which was used within count clause. it solved the issue. Note: if null value exist, check whether its critical for the report, as its excluded in the count.

Old query:

select city, Count(Emp_ID) as Emp_Count 
from Emp_DB
group by city

New query:

select city, Count(Emp_ID) as Emp_Count 
from Emp_DB
where Emp_ID is not null
group by city

DataGridView checkbox column - value and functionality

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
    ch1 = (DataGridViewCheckBoxCell)dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0];

    if (ch1.Value == null)
        ch1.Value=false;
    switch (ch1.Value.ToString())
    {
        case "True":
            ch1.Value = false;
            break;
        case "False":
            ch1.Value = true;
            break;
    }
    MessageBox.Show(ch1.Value.ToString());
}

best solution to find if the checkbox in the datagridview is checked or not.

Mongoose.js: Find user by username LIKE value

Here my code with expressJS:

router.route('/wordslike/:word')
    .get(function(request, response) {
            var word = request.params.word;       
            Word.find({'sentence' : new RegExp(word, 'i')}, function(err, words){
               if (err) {response.send(err);}
               response.json(words);
            });
         });

When to use margin vs padding in CSS

It's good to know the differences between margin and padding. Here are some differences:

  • Margin is outer space of an element, while padding is inner space of an element.

  • Margin is the space outside the border of an element, while padding is the space inside the border of it.

  • Margin accepts the value of auto: margin: auto, but you can't set padding to auto.

  • Margin can be set to any number, but padding must be non-negative.

  • When you style an element, padding will also be affected (e.g. background color), but not margin.

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

I have just faced the same problem. First, you need to install the appropriate Oracle client for your OS. In my case, to install it on Ubuntu x64 I have followed this instructions https://help.ubuntu.com/community/Oracle%20Instant%20Client#Install_RPMs

Then, you need to install cx_Oracle, a Python module to connect to the Oracle client. Again, assuming you are running Ubuntu in a 64bit machine, you should type in a shell:

wget -c http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm
sudo alien -i cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm

This will work for Oracle 11g if you have installed Python 2.7.x, but you can download a different cx_Oracle version in http://cx-oracle.sourceforge.net/ To check which Python version do you have, type in a terminal:

python -V

I hope it helps

Convert Mongoose docs to json

Try this options:

  UserModel.find({}, function (err, users) {
    //i got into errors using so i changed to res.send()
    return res.send( JSON.parse(JSON.stringify(users)) );
    //Or
    //return JSON.parse(JSON.stringify(users));
  }

The remote host closed the connection. The error code is 0x800704CD

I got this error when I dynamically read data from a WebRequest and never closed the Response.

    protected System.IO.Stream GetStream(string url)
    {
        try
        {
            System.IO.Stream stream = null;
            var request = System.Net.WebRequest.Create(url);
            var response = request.GetResponse();

            if (response != null) {
                stream = response.GetResponseStream();

                // I never closed the response thus resulting in the error
                response.Close(); 
            }
            response = null;
            request = null;

            return stream;
        }
        catch (Exception) { }
        return null;
    }

node.js execute system command synchronously

Node.js (since version 0.12 - so for a while) supports execSync:

child_process.execSync(command[, options])

You can now directly do this:

const execSync = require('child_process').execSync;
code = execSync('node -v');

and it'll do what you expect. (Defaults to pipe the i/o results to the parent process). Note that you can also spawnSync now.

How to Update Multiple Array Elements in mongodb

I tried the following and its working fine.

.update({'events.profile': 10}, { '$set': {'events.$.handled': 0 }},{ safe: true, multi:true }, callback function);

// callback function in case of nodejs

Keylistener in Javascript

The code is

document.addEventListener('keydown', function(event){
    alert(event.keyCode);
} );

This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)

Is there StartsWith or Contains in t sql with variables?

I would use

like 'Express Edition%'

Example:

DECLARE @edition varchar(50); 
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)

DECLARE @isExpress bit
if @edition like 'Express Edition%'
    set @isExpress = 1;
else
    set @isExpress = 0;

print @isExpress

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

Things to be done to free port 80:

  1. check if skype is running, exit from skype
  2. check services.msc if web deployment agent service is running
  3. check if IIS is running, stop it.

Once you start apache, you can sign into skype.

file_get_contents behind a proxy?

To use file_get_contents() over/through a proxy that doesn't require authentication, something like this should do :

(I'm not able to test this one : my proxy requires an authentication)

$aContext = array(
    'http' => array(
        'proxy'           => 'tcp://192.168.0.2:3128',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;

Of course, replacing the IP and port of my proxy by those which are OK for yours ;-)

If you're getting that kind of error :

Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 407 Proxy Authentication Required

It means your proxy requires an authentication.

If the proxy requires an authentication, you'll have to add a couple of lines, like this :

$auth = base64_encode('LOGIN:PASSWORD');

$aContext = array(
    'http' => array(
        'proxy'           => 'tcp://192.168.0.2:3128',
        'request_fulluri' => true,
        'header'          => "Proxy-Authorization: Basic $auth",
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;

Same thing about IP and port, and, this time, also LOGIN and PASSWORD ;-) Check out all valid http options.

Now, you are passing an Proxy-Authorization header to the proxy, containing your login and password.

And... The page should be displayed ;-)

Check last modified date of file in C#

Just use File.GetLastWriteTime. There's a sample on that page showing how to use it.

Run bash script as daemon

You can go to /etc/init.d/ - you will see a daemon template called skeleton.

You can duplicate it and then enter your script under the start function.

Why is synchronized block better than synchronized method?

The difference is in which lock is being acquired:

  • synchronized method acquires a lock on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread.

  • synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword. Meaning no other thread can acquire a lock on the locked object until the synchronized block exits.

So if you want to lock the whole object, use a synchronized method. If you want to keep other parts of the object accessible to other threads, use synchronized block.

If you choose the locked object carefully, synchronized blocks will lead to less contention, because the whole object/class is not blocked.

This applies similarly to static methods: a synchronized static method will acquire a lock in the whole class object, while a synchronized block inside a static method will acquire a lock in the object between parentheses.

How to append something to an array?

We don't have append function for Array in javascript, but we have push and unshift, imagine you have the array below:

var arr = [1, 2, 3, 4, 5];

and we like append a value to this array, we can do, arr.push(6) and it will add 6 to the end of the array:

arr.push(6); // return [1, 2, 3, 4, 5, 6];

also we can use unshift, look at how we can apply this:

arr.unshift(0); //return [0, 1, 2, 3, 4, 5];

They are main functions to add or append new values to the arrays.

phonegap open link in browser

If you happen to have jQuery around, you can intercept the click on the link like this:

$(document).on('click', 'a', function (event) {
    event.preventDefault();
    window.open($(this).attr('href'), '_system');
    return false;
});

This way you don't have to modify the links in the html, which can save a lot of time. I have set this up using a delegate, that's why you see it being tied to the document object, with the 'a' tag as the second argument. This way all 'a' tags will be handled, regardless of when they are added.

Ofcourse you still have to install the InAppBrowser plug-in:

cordova plugin add org.apache.cordova.inappbrowser

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

The following interface became deprecated in pip 10:

from pip.req import parse_requirements
from pip.download import PipSession

So I switched it just to simple text parsing:

with open('requirements.txt', 'r') as f:
    install_reqs = [
        s for s in [
            line.split('#', 1)[0].strip(' \t\n') for line in f
        ] if s != ''
    ]

Running the new Intel emulator for Android

For Windows, there are some answers explained how it works. But I'm a Mac User, I don't know how to install HAX driver for Mac as they did for Windows. Finally I found the below link and it did fix my problem. You should download HAXM of Mac and then install it.

https://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager-end-user-license-agreement-macosx/

Set QLineEdit to accept only numbers

Why don't you use a QSpinBox for this purpose ? You can set the up/down buttons invisible with the following line of codes:

// ...
QSpinBox* spinBox = new QSpinBox( this );
spinBox->setButtonSymbols( QAbstractSpinBox::NoButtons ); // After this it looks just like a QLineEdit.
//...

Google Chrome Full Black Screen

Here is what worked for me: (I got this answer from https://productforums.google.com/forum/#!topic/chrome/MJjuK65Exkg)

  1. Unpin Chrome icon from task bar so it is on the desktop.
  2. Right mouse click on said icon and left click on Properties.
  3. Click on Shortcuts tab 4A. In Target window, add this exact text: [space]--disable-gpu" 4B. The end of the text string in the Target window should now read: ...chrome.exe" --disable-gpu"
  4. Double click on the desktop icon and Chrome should open correctly. If you want, you may pin this icon to the taskbar.
  5. Left single click on the "Customize" icon in the top right, which is the 3 horizontal lines icon. Select "Settings" from the list.
  6. Select "Show advanced settings..." at the bottom.
  7. Deselect "Use hardware acceleration when available."

How do I pass a variable to the layout using Laravel' Blade templating?

I was able to solve that problem by adding this to my controller method:

    $title = 'My Title Here';
    View::share('title', $title);

$this->layout->title = 'Home page'; did not work either.

How can I check if character in a string is a letter? (Python)

data = "abcdefg hi j 12345"

digits_count = 0
letters_count = 0
others_count = 0

for i in userinput:

    if i.isdigit():
        digits_count += 1 
    elif i.isalpha():
        letters_count += 1
    else:
        others_count += 1

print("Result:")        
print("Letters=", letters_count)
print("Digits=", digits_count)

Output:

Please Enter Letters with Numbers:
abcdefg hi j 12345
Result:
Letters = 10
Digits = 5

By using str.isalpha() you can check if it is a letter.

Stack array using pop() and push()

 public class Stack {
     int[] arr;
     int MAX_SIZE;
     int top;

public Stack(int n){
    MAX_SIZE = n;
    arr = new int[MAX_SIZE];
    top=0;
}

    public boolean isEmpty(){
        if(top ==0)
            return true;
      else
        return false;
   }

public boolean push(int ele){

    if(top<MAX_SIZE){
        arr[top] = ele;
        top++;
        return true;
    }
    else{
        System.out.println("Stack is full");
        return false;
    }
}
public void show(){
    for(int element:arr){
        System.out.print(element+" ");
    }
}
public int size(){
    return top;
}
   public int peek(){
        if(!isEmpty()){
            int peekTest = arr[top-1];
            return peekTest;
                    }
   else{
       System.out.println("Stack is empty");
       return 0;
   } 
}
public int pop(){
    if(isEmpty()){
        System.out.println("Stack is Emmpty");
        return 0;
    }
    else{
        int element = arr[--top];
        return element;
    }
}

}

Compile Views in ASP.NET MVC

Also, if you use Resharper, you can active Solution Wide Analysis and it will detect any compiler errors you might have in aspx files. That is what we do...

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

Oddly enough, the issue for me was I was trying to open 2012 SQL Server Integration Services on SSMS 2008 R2. When I opened the same in SSMS 2012, it connected right away.

MySQL, Check if a column exists in a table with SQL

This work for me with sample PDO :

public function GetTableColumn() {      
$query  = $this->db->prepare("SHOW COLUMNS FROM `what_table` LIKE 'what_column'");  
try{            
    $query->execute();                                          
    if($query->fetchColumn()) { return 1; }else{ return 0; }
    }catch(PDOException $e){die($e->getMessage());}     
}

How do I find the difference between two values without knowing which is larger?

Just use abs(x - y). This'll return the net difference between the two as a positive value, regardless of which value is larger.

Map a network drive to be used by a service

You'll either need to modify the service, or wrap it inside a helper process: apart from session/drive access issues, persistent drive mappings are only restored on an interactive logon, which services typically don't perform.

The helper process approach can be pretty simple: just create a new service that maps the drive and starts the 'real' service. The only things that are not entirely trivial about this are:

  • The helper service will need to pass on all appropriate SCM commands (start/stop, etc.) to the real service. If the real service accepts custom SCM commands, remember to pass those on as well (I don't expect a service that considers UNC paths exotic to use such commands, though...)

  • Things may get a bit tricky credential-wise. If the real service runs under a normal user account, you can run the helper service under that account as well, and all should be OK as long as the account has appropriate access to the network share. If the real service will only work when run as LOCALSYSTEM or somesuch, things get more interesting, as it either won't be able to 'see' the network drive at all, or require some credential juggling to get things to work.

Git pull - Please move or remove them before you can merge

If you are getting error like

  • branch master -> FETCH_HEAD error: The following untracked working tree files would be overwritten by merge: src/dj/abc.html Please move or remove them before you merge. Aborting

Try removing the above file manually(Careful). Git will merge this file from master branch.

How do I access (read, write) Google Sheets spreadsheets with Python?

I think you're looking at the cell-based feeds section in that API doc page. Then you can just use the PUT/ GET requests within your Python script, using either commands.getstatusoutput or subprocess.

iCheck check if checkbox is checked

For those who struggle with this:

const value = $('SELECTOR').iCheck('update')[0].checked;

This directly returns true or false as boolean.

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

generate model using user:references vs user_id:integer

For the former, convention over configuration. Rails default when you reference another table with

 belongs_to :something

is to look for something_id.

references, or belongs_to is actually newer way of writing the former with few quirks.

Important is to remember that it will not create foreign keys for you. In order to do that, you need to set it up explicitly using either:

t.references :something, foreign_key: true
t.belongs_to :something_else, foreign_key: true

or (note the plural):

add_foreign_key :table_name, :somethings
add_foreign_key :table_name, :something_elses`

Get skin path in Magento?

First of all it is not recommended to have php files with functions in design folder. You should create a new module or extend (copy from core to local a helper and add function onto that class) and do not change files from app/code/core.

To answer to your question you can use:

require(Mage::getBaseDir('design').'/frontend/default/mytheme/myfunc.php');

Best practice (as a start) will be to create in /app/code/local/Mage/Core/Helper/Extra.php a php file:

<?php
class Mage_Core_Helper_Extra extends Mage_Core_Helper_Abstract
{

    public function getSomething()
    {
        return 'Someting';
    }

}

And to use it in phtml files use:

$this->helper('core/extra')->getSomething();

Or in all the places:

Mage::helper('core/extra')->getSomething();

How do I find files with a path length greater than 260 characters in Windows?

I've made an alternative to the other good answers on here that uses PowerShell, but mine also saves the list to a file. Will share it here in case anyone else needs wants something like that.

Warning: Code overwrites "longfilepath.txt" in the current working directory. I know it's unlikely you'd have one already, but just in case!

Purposely wanted it in a single line:

Out-File longfilepath.txt ; cmd /c "dir /b /s /a" | ForEach-Object { if ($_.length -gt 250) {$_ | Out-File -append longfilepath.txt}}

Detailed instructions:

  1. Run PowerShell
  2. Traverse to the directory you want to check for filepath lengths (C: works)
  3. Copy and paste the code [Right click to paste in PowerShell, or Alt + Space > E > P]
  4. Wait until it's done and then view the file: cat longfilepath.txt | sort

Explanation:

Out-File longfilepath.txt ; – Create (or overwrite) a blank file titled 'longfilepath.txt'. Semi-colon to separate commands.

cmd /c "dir /b /s /a" | – Run dir command on PowerShell, /a to show all files including hidden files. | to pipe.

ForEach-Object { if ($_.length -gt 250) {$_ | Out-File -append longfilepath.txt}} – For each line (denoted as $_), if the length is greater than 250, append that line to the file.

Hyper-V: Create shared folder between host and guest with internal network

  • Open Hyper-V Manager
  • Create a new internal virtual switch (e.g. "Internal Network Connection")
  • Go to your Virtual Machine and create a new Network Adapter -> choose "Internal Network Connection" as virtual switch
  • Start the VM
  • Assign both your host as well as guest an IP address as well as a Subnet mask (IP4, e.g. 192.168.1.1 (host) / 192.168.1.2 (guest) and 255.255.255.0)
  • Open cmd both on host and guest and check via "ping" if host and guest can reach each other (if this does not work disable/enable the network adapter via the network settings in the control panel, restart...)
  • If successfull create a folder in the VM (e.g. "VMShare"), right-click on it -> Properties -> Sharing -> Advanced Sharing -> checkmark "Share this folder" -> Permissions -> Allow "Full Control" -> Apply
  • Now you should be able to reach the folder via the host -> to do so: open Windows Explorer -> enter the path to the guest (\192.168.1.xx...) in the address line -> enter the credentials of the guest (Choose "Other User" - it can be necessary to change the domain therefore enter ".\"[username] and [password])

There is also an easy way for copying via the clipboard:

  • If you start your VM and go to "View" you can enable "Enhanced Session". If you do it is not possible to drag and drop but to copy and paste.

Enhanced Session

How to add a line to a multiline TextBox?

You have to use the AppendText method of the textbox directly. If you try to use the Text property, the textbox will not scroll down as new line are appended.

textBox1.AppendText("Hello" + Environment.NewLine);

Carriage Return\Line feed in Java

Encapsulate your writer to provide char replacement, like this:

public class WindowsFileWriter extends Writer {

    private Writer writer;

    public WindowsFileWriter(File file) throws IOException {
        try {
            writer = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-15");
        } catch (UnsupportedEncodingException e) {
            writer = new FileWriter(logfile);
        }
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        writer.write(new String(cbuf, off, len).replace("\n", "\r\n"));
    }

    @Override
    public void flush() throws IOException {
        writer.flush();
    }

    @Override
    public void close() throws IOException {
        writer.close();
    }

}

How to add buttons like refresh and search in ToolBar in Android?

Try to do this:

getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);

and if you made your custom toolbar (which i presume you did) then you can use the simplest way possible to do this:

toolbarTitle = (TextView)findViewById(R.id.toolbar_title);
toolbarSubTitle = (TextView)findViewById(R.id.toolbar_subtitle);
toolbarTitle.setText("Title");
toolbarSubTitle.setText("Subtitle");

Same goes for any other views you put in your toolbar. Hope it helps.

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

this expression is to get only numbers

    If Regex.IsMatch(mystring, "^[A-Za-z ].*|\s") Then
        MessageBox.Show("please fill the box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
       
    ElseIf (mystring = "") Then
        MessageBox.Show("please fill the box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
      
    End If

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

It is work 100%

sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

How do I remove all non alphanumeric characters from a string except dash?

Replace [^a-zA-Z0-9 -] with an empty string.

Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");

Accessing @attribute from SimpleXML

Try this

$xml->attributes()->Token

How to center an unordered list?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.

Now, add the style to the div class and use the text-align property with center as its value.

See the below example.

<style>
.myDivElement{
    text-align:center;
}
.myDivElement ul li{
   display:inline;

 }
</style>
<div class="myDivElement">
<ul>
    <li>Home</li>
    <li>About</li>
    <li>Gallery</li>
    <li>Contact</li>
</ul>
</div>

Here is the reference website Center Align Unordered List

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary)

 var result = new JsonResult()
 {
     Data = new
     {
         partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
     }
 };

I get what's expected:

{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}

Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting

Here's a simple actionresult JsonNetResult

http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

You'll see the difference (and can make sure you're using the right one) when serializing a date:

Microsoft way:

 {"wireTime":"\/Date(1355627201572)\/"}

JSON.NET way:

 {"wireTime":"2012-12-15T19:07:03.5247384-08:00"}

How to hide a column (GridView) but still access its value?

You can do it code behind.

Set visible= false for columns after data binding . After that you can again do visibility "true" in row_selection function from grid view .It will work!!

Early exit from function?

exit(); can be use to go for the next validation.

Programmatically select a row in JTable

You can do it calling setRowSelectionInterval :

table.setRowSelectionInterval(0, 0);

to select the first row.

RuntimeError: module compiled against API version a but this version of numpy is 9

I ran into the same issue tonight. It turned out to be a problem where I had multiple numpy packages installed. An older version was installed in /usr/lib/python2.7 and the correct version was installed in /usr/local/lib/python2.7.

Additionally, I had PYTHONPATH=/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages. PYTHONPATH was finding the older version of numpy before the correct version, so when inside the Python interpreter, it would import the older version of numpy.

One thing which helped was opening a python session an executing the following code:

import numpy as np 
print np.__version__ 
print np.__path__

That should tell you exactly which version Python is using, and where it's installed.

To fix the issue, I changed PYTHONPATH=/usr/local/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages. And I also setup a virtual Python environment using the Hitchiker's Guide to Python, specifically the section titled "Lower level: virtualenv" . I know I should have setup a virtual environment in the first place, but I was tired and being lazy. Oh well, lesson learned!

(Update)

Just in case the docs are moved again, here are the relevant bits on...

Creating a Python Virtual Environment

Install virtualenv via pip:

$ install virtualenv

Test the installation:

$ virtualenv --version

Optionally, et the environment variable VIRTUALENVWRAPPER_PYTHON to change the default version of python used by virtual environments, for example to use Python 3:

$ export VIRTUALENVWRAPPER_PYTHON=$(which python3)

Optionally, set the environment variable WORKON_HOME to change the default directory your Python virtual environments are created in, for example to use /opt/python_envs:

$ export WORKON_HOME=/opt/python_envs

Create a virtual environment for a project:

$ cd my_project_folder
$ virtualenv my_virtual_env_name

Activate the virtual environment, you just created. Assuming you also set WORKON_HOME=/opt/python_envs:

$ source $WORKON_HOME/my_virtual_env_name/bin/activate

Install whatever Python packages your project requires, using either of the following two methods.

Method 1 - Install using pip from command line:

$ pip install python_package_name1
$ pip install python_package_name2

Method 2 - Install using a requests.txt file:

$ echo "python_package_name1" >> requests.txt
$ echo "python_package_name2" >> requests.txt
$ pip install -r ./requests.txt

Optionally, but highly recommended, install virtualenvwrapper. It contains useful commands to make working with virtual Python environments easier:

$ pip install virtualenvwrapper
$ source /usr/local/bin/virtualenvwrapper.sh

On Windows, install virtualenvwrapper using:

$ pip install virtualenvwrapper-win

Basic usage of virtualenvwrapper Create a new virtual environment:

$ mkvirtualenv my_virtual_env_name

List all virtual environments:

$ lsvirtualenv

Activate a virtual environment:

$ workon my_virtual_env_name

Delete a virtual environment (caution! this is irreversible!):

$ rmvirtualenv my_virtual_env_name

I hope this help!

How to use http.client in Node.js if there is basic authorization

I came across this recently. Which among Proxy-Authorization and Authorization headers to set depends on the server the client is talking to. If it is a Webserver, you need to set Authorization and if it a proxy, you have to set the Proxy-Authorization header

Javascript add method to object

You can make bar a function making it a method.

Foo.bar = function(passvariable){  };

As a property it would just be assigned a string, data type or boolean

Foo.bar = "a place";

Java 8 - Difference between Optional.flatMap and Optional.map

They both take a function from the type of the optional to something.

map() applies the function "as is" on the optional you have:

if (optional.isEmpty()) return Optional.empty();
else return Optional.of(f(optional.get()));

What happens if your function is a function from T -> Optional<U>?
Your result is now an Optional<Optional<U>>!

That's what flatMap() is about: if your function already returns an Optional, flatMap() is a bit smarter and doesn't double wrap it, returning Optional<U>.

It's the composition of two functional idioms: map and flatten.

PHP read and write JSON from file

Or just use $json as an object:

$json->$user = array("first" => $first, "last" => $last);

This is how it is returned without the second parameter (as an instance of stdClass).

Text Editor which shows \r\n?

SciTE does that very well with a single keystroke. It is also able to detect the most probably current line ending of the file (in case of mixed lines) and to convert them.
No need to install, lightweight, it can be used as a tool even if you don't want to give up your favorite editor.

Get the current fragment object

you can check which fragment is currently loaded by this

        supportFragmentManager.addOnBackStackChangedListener {
        val myFragment = supportFragmentManager.fragments.last()

        if (null != myFragment && myFragment is HomeFragment) {
            //HomeFragment is visible or currently loaded
        } else {
            //your code
        }
    }

Check if a string isn't nil or empty in Lua

Can this code be simplified in one if test instead two?

nil and '' are different values. If you need to test that s is neither, IMO you should just compare against both, because it makes your intent the most clear.

That and a few alternatives, with their generated bytecode:

if not foo or foo == '' then end
     GETGLOBAL       0 -1    ; foo
     TEST            0 0 0
     JMP             3       ; to 7
     GETGLOBAL       0 -1    ; foo
     EQ              0 0 -2  ; - ""
     JMP             0       ; to 7

if foo == nil or foo == '' then end
    GETGLOBAL       0 -1    ; foo
    EQ              1 0 -2  ; - nil
    JMP             3       ; to 7
    GETGLOBAL       0 -1    ; foo
    EQ              0 0 -3  ; - ""
    JMP             0       ; to 7

if (foo or '') == '' then end
   GETGLOBAL       0 -1    ; foo
   TEST            0 0 1
   JMP             1       ; to 5
   LOADK           0 -2    ; ""
   EQ              0 0 -2  ; - ""
   JMP             0       ; to 7

The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.

How to achieve ripple animation using support library?

I made a simple class that makes ripple buttons, i never needed it in the end so its not the best, But here it is:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

public class RippleView extends Button
{
    private float duration = 250;

    private float speed = 1;
    private float radius = 0;
    private Paint paint = new Paint();
    private float endRadius = 0;
    private float rippleX = 0;
    private float rippleY = 0;
    private int width = 0;
    private int height = 0;
    private OnClickListener clickListener = null;
    private Handler handler;
    private int touchAction;
    private RippleView thisRippleView = this;

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

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

    public RippleView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init()
    {
        if (isInEditMode())
            return;

        handler = new Handler();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas)
    {
        super.onDraw(canvas);

        if(radius > 0 && radius < endRadius)
        {
            canvas.drawCircle(rippleX, rippleY, radius, paint);
            if(touchAction == MotionEvent.ACTION_UP)
                invalidate();
        }
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event)
    {
        rippleX = event.getX();
        rippleY = event.getY();

        switch(event.getAction())
        {
            case MotionEvent.ACTION_UP:
            {
                getParent().requestDisallowInterceptTouchEvent(false);
                touchAction = MotionEvent.ACTION_UP;

                radius = 1;
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                speed = endRadius / duration * 10;
                handler.postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        if(radius < endRadius)
                        {
                            radius += speed;
                            paint.setAlpha(90 - (int) (radius / endRadius * 90));
                            handler.postDelayed(this, 1);
                        }
                        else
                        {
                            clickListener.onClick(thisRippleView);
                        }
                    }
                }, 10);
                invalidate();
                break;
            }
            case MotionEvent.ACTION_CANCEL:
            {
                getParent().requestDisallowInterceptTouchEvent(false);
                touchAction = MotionEvent.ACTION_CANCEL;
                radius = 0;
                invalidate();
                break;
            }
            case MotionEvent.ACTION_DOWN:
            {
                getParent().requestDisallowInterceptTouchEvent(true);
                touchAction = MotionEvent.ACTION_UP;
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                paint.setAlpha(90);
                radius = endRadius/4;
                invalidate();
                return true;
            }
            case MotionEvent.ACTION_MOVE:
            {
                if(rippleX < 0 || rippleX > width || rippleY < 0 || rippleY > height)
                {
                    getParent().requestDisallowInterceptTouchEvent(false);
                    touchAction = MotionEvent.ACTION_CANCEL;
                    radius = 0;
                    invalidate();
                    break;
                }
                else
                {
                    touchAction = MotionEvent.ACTION_MOVE;
                    invalidate();
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    public void setOnClickListener(OnClickListener l)
    {
        clickListener = l;
    }
}

EDIT

Since many people are looking for something like this i made a class that can make other views have the ripple effect:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

public class RippleViewCreator extends FrameLayout
{
    private float duration = 150;
    private int frameRate = 15;

    private float speed = 1;
    private float radius = 0;
    private Paint paint = new Paint();
    private float endRadius = 0;
    private float rippleX = 0;
    private float rippleY = 0;
    private int width = 0;
    private int height = 0;
    private Handler handler = new Handler();
    private int touchAction;

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

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

    public RippleViewCreator(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init()
    {
        if (isInEditMode())
            return;

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(getResources().getColor(R.color.control_highlight_color));
        paint.setAntiAlias(true);

        setWillNotDraw(true);
        setDrawingCacheEnabled(true);
        setClickable(true);
    }

    public static void addRippleToView(View v)
    {
        ViewGroup parent = (ViewGroup)v.getParent();
        int index = -1;
        if(parent != null)
        {
            index = parent.indexOfChild(v);
            parent.removeView(v);
        }
        RippleViewCreator rippleViewCreator = new RippleViewCreator(v.getContext());
        rippleViewCreator.setLayoutParams(v.getLayoutParams());
        if(index == -1)
            parent.addView(rippleViewCreator, index);
        else
            parent.addView(rippleViewCreator);
        rippleViewCreator.addView(v);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    @Override
    protected void dispatchDraw(@NonNull Canvas canvas)
    {
        super.dispatchDraw(canvas);

        if(radius > 0 && radius < endRadius)
        {
            canvas.drawCircle(rippleX, rippleY, radius, paint);
            if(touchAction == MotionEvent.ACTION_UP)
                invalidate();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event)
    {
        return true;
    }

    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event)
    {
        rippleX = event.getX();
        rippleY = event.getY();

        touchAction = event.getAction();
        switch(event.getAction())
        {
            case MotionEvent.ACTION_UP:
            {
                getParent().requestDisallowInterceptTouchEvent(false);

                radius = 1;
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                speed = endRadius / duration * frameRate;
                handler.postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        if(radius < endRadius)
                        {
                            radius += speed;
                            paint.setAlpha(90 - (int) (radius / endRadius * 90));
                            handler.postDelayed(this, frameRate);
                        }
                        else if(getChildAt(0) != null)
                        {
                            getChildAt(0).performClick();
                        }
                    }
                }, frameRate);
                break;
            }
            case MotionEvent.ACTION_CANCEL:
            {
                getParent().requestDisallowInterceptTouchEvent(false);
                break;
            }
            case MotionEvent.ACTION_DOWN:
            {
                getParent().requestDisallowInterceptTouchEvent(true);
                endRadius = Math.max(Math.max(Math.max(width - rippleX, rippleX), rippleY), height - rippleY);
                paint.setAlpha(90);
                radius = endRadius/3;
                invalidate();
                return true;
            }
            case MotionEvent.ACTION_MOVE:
            {
                if(rippleX < 0 || rippleX > width || rippleY < 0 || rippleY > height)
                {
                    getParent().requestDisallowInterceptTouchEvent(false);
                    touchAction = MotionEvent.ACTION_CANCEL;
                    break;
                }
                else
                {
                    invalidate();
                    return true;
                }
            }
        }
        invalidate();
        return false;
    }

    @Override
    public final void addView(@NonNull View child, int index, ViewGroup.LayoutParams params)
    {
        //limit one view
        if (getChildCount() > 0)
        {
            throw new IllegalStateException(this.getClass().toString()+" can only have one child.");
        }
        super.addView(child, index, params);
    }
}

Select columns in PySpark dataframe

Use df.schema.names:

spark.version
# u'2.2.0'

df = spark.createDataFrame([("foo", 1), ("bar", 2)])
df.show()
# +---+---+ 
# | _1| _2|
# +---+---+
# |foo|  1| 
# |bar|  2|
# +---+---+

df.schema.names
# ['_1', '_2']

for i in df.schema.names:
  # df_new = df.withColumn(i, [do-something])
  print i
# _1
# _2

Insert default value when parameter is null

With enough defaults on a table, you can simply say:

INSERT t DEFAULT VALUES

Note that this is quite an unlikely case, however.

I've only had to use it once in a production environment. We had two closely related tables, and needed to guarantee that neither table had the same UniqueID, so we had a separate table which just had an identity column, and the best way to insert into it was with the syntax above.

Get program path in VB.NET?

Set Your Own application Path

Dim myPathsValues As String

    TextBox1.Text = Application.StartupPath
    TextBox2.Text = Len(Application.StartupPath)
    TextBox3.Text = Microsoft.VisualBasic.Right(Application.StartupPath, 10)
    myPathsValues = Val(TextBox2.Text) - 9
    TextBox4.Text = Microsoft.VisualBasic.Left(Application.StartupPath, myPathsValues) & "Reports"

How can one use multi threading in PHP applications

The Thread class is available since PECL pthreads = 2.0.0.