Programs & Examples On #Nodelist

The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live. The items in the NodeList are accessible via an integral index, starting from 0.

Fastest way to convert JavaScript NodeList to Array?

The most fast and cross browser is

for(var i=-1,l=nl.length;++i!==l;arr[i]=nl[i]);

As I compared in

http://jsbin.com/oqeda/98/edit

*Thanks @CMS for the idea!

Chromium (Similar to Google Chrome) Firefox Opera

Input group - two inputs close to each other

My solution requires no additional css and works with any combination of input-addon, input-btn and form-control. It just uses pre-existing bootstrap classes

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />_x000D_
<form style="padding:10px; margin:10px" action="" class=" form-inline">_x000D_
  <div class="form-group">_x000D_
    <div class="input-group">_x000D_
    <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="MinVal">_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="MaxVal">_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

This will be inline if there is space and wrap for smaller screens.

Full Example ( input-addon, input-btn and form-control. )

jsfiddle

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />_x000D_
<form style="padding:10px; margin:10px" action="" class=" form-inline">_x000D_
  <div class="form-group">_x000D_
    <div class="input-group">_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <br>_x000D_
_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

jquery getting post action url

Try this ocde;;

var formAction = $("#signup").attr('action');

Convert string to Color in C#

I've used something like this before:

        public static T CreateFromString<T>(string stringToCreateFrom) {

        T output = Activator.CreateInstance<T>();

        if (!output.GetType().IsEnum)
            throw new IllegalTypeException();

        try {
            output = (T) Enum.Parse(typeof (T), stringToCreateFrom, true);
        }
        catch (Exception ex) {
            string error = "Cannot parse '" + stringToCreateFrom + "' to enum '" + typeof (T).FullName + "'";
            _logger.Error(error, ex);
            throw new IllegalArgumentException(error, ex);
        }

        return output;
    }

How do I find out what version of Sybase is running

1)From OS level(UNIX):-

dataserver -v

2)From Syabse isql:-

select @@version
go

sp_version
go

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

When to use Interface and Model in TypeScript / Angular

Use Class instead of Interface that is what I discovered after all my research.

Why? A class alone is less code than a class-plus-interface. (anyway you may require a Class for data model)

Why? A class can act as an interface (use implements instead of extends).

Why? An interface-class can be a provider lookup token in Angular dependency injection.

from Angular Style Guide

Basically a Class can do all, what an Interface will do. So may never need to use an Interface.

Using a remote repository with non-standard port

SSH doesn't use the : syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config file and add:

Host git.host.de
  Port 4019

Then specify just git.host.de without a port number.

The data-toggle attributes in Twitter Bootstrap

The purpose of data-toggle in bootstrap is so you can use jQuery to find all tags of a certain type. For example, you put data-toggle="popover" in all popover tags and then you can use a JQuery selector to find all those tags and run the popover() function to initialize them. You could just as well put class="myPopover" on the tag and use the .myPopover selector to do the same thing. The documentation is confusing, because it makes it appear that something special is going on with that attribute.

This

<div class="container">
    <h3>Popover Example</h3>
    <a href="#" class="myPop" title="Popover1 Header" data-content="Some content inside the popover1">Toggle popover1</a>
    <a href="#" class="myPop" title="Popover2 Header" data-content="Some content inside the popover2">Toggle popover2</a>
</div>

<script>
    $(document).ready(function(){
        $('.myPop').popover();   
    });
</script>

works just fine.

How to clear https proxy setting of NPM?

This was already answered but I think the --global config is not covered properly.

By running npm config rm proxy you remove proxy from user configuration.
This can be easily verified by running: npm config list.

If there is proxy or https-proxy setting set in global config you have to use --global in the command to remove it.

So at the end this will clean-up proxies from both local and global configs:

npm config rm proxy
npm config rm https-proxy
npm config --global rm proxy
npm config --global rm https-proxy

What's the fastest way to delete a large folder in Windows?

Try Shift + Delete. Did 24.000 files in 2 minutes for me.

Get class list for element with jQuery

Here is a jQuery plugin which will return an array of all the classes the matched element(s) have

;!(function ($) {
    $.fn.classes = function (callback) {
        var classes = [];
        $.each(this, function (i, v) {
            var splitClassName = v.className.split(/\s+/);
            for (var j = 0; j < splitClassName.length; j++) {
                var className = splitClassName[j];
                if (-1 === classes.indexOf(className)) {
                    classes.push(className);
                }
            }
        });
        if ('function' === typeof callback) {
            for (var i in classes) {
                callback(classes[i]);
            }
        }
        return classes;
    };
})(jQuery);

Use it like

$('div').classes();

In your case returns

["Lorem", "ipsum", "dolor_spec", "sit", "amet"]

You can also pass a function to the method to be called on each class

$('div').classes(
    function(c) {
        // do something with each class
    }
);

Here is a jsFiddle I set up to demonstrate and test http://jsfiddle.net/GD8Qn/8/

Minified Javascript

;!function(e){e.fn.classes=function(t){var n=[];e.each(this,function(e,t){var r=t.className.split(/\s+/);for(var i in r){var s=r[i];if(-1===n.indexOf(s)){n.push(s)}}});if("function"===typeof t){for(var r in n){t(n[r])}}return n}}(jQuery);

Wait until page is loaded with Selenium WebDriver for Python

On a side note, instead of scrolling down 100 times, you can check if there are no more modifications to the DOM (we are in the case of the bottom of the page being AJAX lazy-loaded)

def scrollDown(driver, value):
    driver.execute_script("window.scrollBy(0,"+str(value)+")")

# Scroll down the page
def scrollDownAllTheWay(driver):
    old_page = driver.page_source
    while True:
        logging.debug("Scrolling loop")
        for i in range(2):
            scrollDown(driver, 500)
            time.sleep(2)
        new_page = driver.page_source
        if new_page != old_page:
            old_page = new_page
        else:
            break
    return True

set div height using jquery (stretch div height)

I think will work.

$('#DivID').height('675px');

Error: Unable to run mksdcard SDK tool

This is what worked for me

When I tried the Accepted ans my Android Studio hangs on start-up

This is the link

http://tools.android.com/tech-docs/linux-32-bit-libraries

and This is the Command

$ sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1

How do you add UI inside cells in a google spreadsheet using app script?

Buttons can be added to frozen rows as images. Assigning a function within the attached script to the button makes it possible to run the function. The comment which says you can not is of course a very old comment, possibly things have changed now.

How to use linux command line ftp with a @ sign in my username?

I've never seen the -u parameter. But if you want to use an "@", how about stating it as "\@"?

That way it should be interpreted as you intend. You know something like

ftp -u user\@[email protected]

How do I make a JAR from a .java file?

Ok this is the solution I would have liked to find, instead here I write it:

First create the directory structure corresponding to the package defined for the .java file, if it is my.super.application create the directory "my" and inside it "super" and inside it the .java file "App.java"

then from command line:

   javac -cp /path/to/lib1.jar:/path/to/lib2.jar path/to/my/super/App.java

Notice the above will include multiple libraries, if under windows use "," to separate multiple files otherwise under GNU/Linux use ":" To create a jar file

   jar -cvfe App.jar App my/app/

the above will create the application with its corresponding Manifest indicating the App as the main class.

Including the required libraries inside the jar file is not possible using java or jar command line parameters.

You can instead:

  1. manually extract libraries to the root folder of the jar file
  2. use an IDE such as Netbeans and insert a rule inside post-jar section of nbproject/build-impl.xml to extract the libraries inside the jar. See below.
<target name="-post-jar">
        <!-- Empty placeholder for easier customization. -->
        <!-- You can override this target in the ../build.xml file. -->
  <jar jarfile="${dist.jar}" update="true">  
            <zipfileset src="${dist.jar}" includes="**/*.class" />  
            <zipfileset src="${file.reference.iText-1.0.8.jar}" includes="**/*"/>
      <zipfileset src="${file.reference.itextpdf-3.2.1.jar}" includes="**/*"/>
  </jar>
    </target>

the file.reference names are found inside project.properties file after you added the libraries to the Netbeans IDE.

(change) vs (ngModelChange) in angular

As I have found and wrote in another topic - this applies to angular < 7 (not sure how it is in 7+)

Just for the future

we need to observe that [(ngModel)]="hero.name" is just a short-cut that can be de-sugared to: [ngModel]="hero.name" (ngModelChange)="hero.name = $event".

So if we de-sugar code we would end up with:

<select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event">

or

<[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()">

If you inspect the above code you will notice that we end up with 2 ngModelChange events and those need to be executed in some order.

Summing up: If you place ngModelChange before ngModel, you get the $event as the new value, but your model object still holds previous value. If you place it after ngModel, the model will already have the new value.

SOURCE

How to determine the version of the C++ standard used by the compiler?

Normally you should use __cplusplus define to detect c++17, but by default microsoft compiler does not define that macro properly, see https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/ - you need to either modify project settings to include /Zc:__cplusplus switch, or you could use syntax like this:

#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
     //C++17 specific stuff here
#endif

The service cannot accept control messages at this time

This helped me: just wait about a minute or two.

Wait a few minutes, then retry your operation.

Ref: https://msdn.microsoft.com/en-us/library/ms833805.aspx

How can I change the remote/target repository URL on Windows?

Take a look in .git/config and make the changes you need.

Alternatively you could use

git remote rm [name of the url you sets on adding]

and

git remote add [name] [URL]

Or just

git remote set-url [URL]

Before you do anything wrong, double check with

git help remote

Add a custom attribute to a Laravel / Eloquent model on load?

in my case, creating an empty column and setting its accessor worked fine. my accessor filling user's age from dob column. toArray() function worked too.

public function getAgeAttribute()
{
  return Carbon::createFromFormat('Y-m-d', $this->attributes['dateofbirth'])->age;
}

How do I run a command on an already existing Docker container?

Unfortunately it is impossible to override ENTRYPOINT with arguments with docker run --entrypoint to achieve this goal.

Note: you can override the ENTRYPOINT setting using --entrypoint, but this can only set the binary to exec (no sh -c will be used).

"Could not find a part of the path" error message

Is the drive E a mapped drive? Then, it can be created by another account other than the user account. This may be the cause of the error.

How do I create and access the global variables in Groovy?

Could not figure out what you want, but you need something like this ? :

?def a = { b -> b = 1 }
?bValue = a()
println b // prints 1

Now bValue contains the value of b which is a variable in the closure a. Now you can do anything with bValue Let me know if i have misunderstood your question

Program to find largest and second largest number in array

You can do it best in one pass.

largest and largest2 are set to INT_MIN on entry. Then step through the array. If largest is smaller than the number, largest2 becomes largest, then largest becomes the new number (or smaller than or equal if you want to allow duplicates). If largest is greater then the new number, test largest2.

Note that this algorithm scales to finding the top three or four in an array, before it become too cumbersome and it's better to just sort.

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

AngularJS: How to clear query parameters in the URL?

I ended up getting the answer from AngularJS forum. See this thread for details


The link is to a Google Groups thread, which is difficult to read and doesn't provide a clear answer. To remove URL parameters use

$location.url($location.path());

Generating Random Passwords

 Generate random password of specified length with 
  - Special characters   
  - Number
  - Lowecase
  - Uppercase

  public static string CreatePassword(int length = 12)
    {
        const string lower = "abcdefghijklmnopqrstuvwxyz";
        const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const string number = "1234567890";
        const string special = "!@#$%^&*";

        var middle = length / 2;
        StringBuilder res = new StringBuilder();
        Random rnd = new Random();
        while (0 < length--)
        {
            if (middle == length)
            {
                res.Append(number[rnd.Next(number.Length)]);
            }
            else if (middle - 1 == length)
            {
                res.Append(special[rnd.Next(special.Length)]);
            }
            else
            {
                if (length % 2 == 0)
                {
                    res.Append(lower[rnd.Next(lower.Length)]);
                }
                else
                {
                    res.Append(upper[rnd.Next(upper.Length)]);
                }
            }
        }
        return res.ToString();
    }

How to import existing Android project into Eclipse?

What works for me is that: File > Import > Existing Project into Workspace (under General tab), then choose the project root folder. The importing of Existing Android Code into Workspace somehow does not work on Eclipse for me.

How to get the ActionBar height?

While @birdy's answer is an option if you want to explicitly control the ActionBar size, there is a way to pull it up without locking the size that I found in support documentation. It's a little awkward but it's worked for me. You'll need a context, this example would be valid in an Activity.

// Calculate ActionBar height
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
    Int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}

Kotlin:

val tv = TypedValue()
if (requireActivity().theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
    val actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
}

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

For me, it's working with this:

BigDecimal a = new BigDecimal("9999999999.6666",precision);
BigDecimal b = new BigDecimal("21",precision);

a.divideToIntegralValue(b).setScale(2)

Datetime equal or greater than today in MySQL

SELECT * FROM users WHERE created >= NOW();

if the column is datetime type.

Checkbox angular material checked by default

You can use

<mat-checkbox [attr.checked] = "myCondition ? 'checked' : null">

if the checked attribute is set to null, it gets removed from the html tag

or you can use Vega's anwser which should work too (mine is a completion that can be usefull if you don't want to link it with ngModel)

Does Python have an argc argument?

You're better off looking at argparse for argument parsing.

http://docs.python.org/dev/library/argparse.html

Just makes it easy, no need to do the heavy lifting yourself.

Execute PHP function with onclick

In javascript, make an ajax function,

function myAjax() {
      $.ajax({
           type: "POST",
           url: 'your_url/ajax.php',
           data:{action:'call_this'},
           success:function(html) {
             alert(html);
           }

      });
 }

Then call from html,

<a href="" onclick="myAjax()" class="deletebtn">Delete</a>

And in your ajax.php,

if($_POST['action'] == 'call_this') {
  // call removeday() here
}

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

TL;DR: Use __builtin intrinsics instead; they might happen to help.

I was able to make gcc 4.8.4 (and even 4.7.3 on gcc.godbolt.org) generate optimal code for this by using __builtin_popcountll which uses the same assembly instruction, but gets lucky and happens to make code that doesn't have an unexpectedly long loop-carried dependency because of the false dependency bug.

I am not 100% sure of my benchmarking code, but objdump output seems to share my views. I use some other tricks (++i vs i++) to make the compiler unroll loop for me without any movl instruction (strange behaviour, I must say).

Results:

Count: 20318230000  Elapsed: 0.411156 seconds   Speed: 25.503118 GB/s

Benchmarking code:

#include <stdint.h>
#include <stddef.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

uint64_t builtin_popcnt(const uint64_t* buf, size_t len){
  uint64_t cnt = 0;
  for(size_t i = 0; i < len; ++i){
    cnt += __builtin_popcountll(buf[i]);
  }
  return cnt;
}

int main(int argc, char** argv){
  if(argc != 2){
    printf("Usage: %s <buffer size in MB>\n", argv[0]);
    return -1;
  }
  uint64_t size = atol(argv[1]) << 20;
  uint64_t* buffer = (uint64_t*)malloc((size/8)*sizeof(*buffer));

  // Spoil copy-on-write memory allocation on *nix
  for (size_t i = 0; i < (size / 8); i++) {
    buffer[i] = random();
  }
  uint64_t count = 0;
  clock_t tic = clock();
  for(size_t i = 0; i < 10000; ++i){
    count += builtin_popcnt(buffer, size/8);
  }
  clock_t toc = clock();
  printf("Count: %lu\tElapsed: %f seconds\tSpeed: %f GB/s\n", count, (double)(toc - tic) / CLOCKS_PER_SEC, ((10000.0*size)/(((double)(toc - tic)*1e+9) / CLOCKS_PER_SEC)));
  return 0;
}

Compile options:

gcc --std=gnu99 -mpopcnt -O3 -funroll-loops -march=native bench.c -o bench

GCC version:

gcc (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4

Linux kernel version:

3.19.0-58-generic

CPU information:

processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 70
model name  : Intel(R) Core(TM) i7-4870HQ CPU @ 2.50 GHz
stepping    : 1
microcode   : 0xf
cpu MHz     : 2494.226
cache size  : 6144 KB
physical id : 0
siblings    : 1
core id     : 0
cpu cores   : 1
apicid      : 0
initial apicid  : 0
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx rdtscp lm constant_tsc nopl xtopology nonstop_tsc eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm arat pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid xsaveopt
bugs        :
bogomips    : 4988.45
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Try like this...

select CONVERT (varchar(10), getdate(), 103) AS [DD/MM/YYYY]

For more info : http://www.sql-server-helper.com/tips/date-formats.aspx

HTML Table width in percentage, table rows separated equally

you can try this, I would do it with CSS, but i think you want it with tables without CSS.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
   <body leftmargin=0 rightmargin=0>
      <table cellpadding="0" cellspacing="0" width="100%" border="1" height="350px"> 
         <tr>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
         </tr>
      </table> 
   </body>
</html>

Redis strings vs Redis hashes to represent JSON: efficiency?

It depends on how you access the data:

Go for Option 1:

  • If you use most of the fields on most of your accesses.
  • If there is variance on possible keys

Go for Option 2:

  • If you use just single fields on most of your accesses.
  • If you always know which fields are available

P.S.: As a rule of the thumb, go for the option which requires fewer queries on most of your use cases.

Google Maps shows "For development purposes only"

Now google maps is free for development only.

If you want to use map free like earlier, then create an account with valid details (billing, payment, etc.) google gives $200 MONTHLY CREDIT Which is EQUIVALENT To FREE USAGE

For more details please see Googles new price details: google map new pricing

Also see the old price details: Old one

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

The jquery.numeric plugin has some bugs that I notified the author of. It allows multiple decimal points in Safari and Opera, and you can't type backspace, arrow keys, or several other control characters in Opera. I needed positive integer input so I ended up just writing my own in the end.

$(".numeric").keypress(function(event) {
  // Backspace, tab, enter, end, home, left, right
  // We don't support the del key in Opera because del == . == 46.
  var controlKeys = [8, 9, 13, 35, 36, 37, 39];
  // IE doesn't support indexOf
  var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
  // Some browsers just don't raise events for control keys. Easy.
  // e.g. Safari backspace.
  if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
      (49 <= event.which && event.which <= 57) || // Always 1 through 9
      (48 == event.which && $(this).attr("value")) || // No 0 first digit
      isControlKey) { // Opera assigns values for control keys.
    return;
  } else {
    event.preventDefault();
  }
});

Register 32 bit COM DLL to 64 bit Windows 7

Below link saved the day

https://msdn.microsoft.com/en-us/library/ms229076(VS.80).aspx

use the relevant RegSvcs as specified in the above link

c:\Windows\Microsoft. NET\Framework\v4.0.30319\RegSvcs.exe ....\Shared\Your.dll /tlb:Your.tlb

Leverage browser caching, how on apache or .htaccess?

First we need to check if we have enabled mod_headers.c and mod_expires.c.

sudo apache2 -l

If we don't have it, we need to enable them

sudo a2enmod headers

Then we need to restart apache

sudo apache2 restart

At last, add the rules on .htaccess (seen on other answers), for example

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
Header set Cache-Control "public"
</FilesMatch>

How to convert XML to JSON in Python?

One possibility would be to use Objectify or ElementTree from the lxml module. An older version ElementTree is also available in the python xml.etree module as well. Either of these will get your xml converted to Python objects which you can then use simplejson to serialize the object to JSON.

While this may seem like a painful intermediate step, it starts making more sense when you're dealing with both XML and normal Python objects.

How to enumerate an enum

My solution works in .NET Compact Framework (3.5) and supports type checking at compile time:

public static List<T> GetEnumValues<T>() where T : new() {
    T valueType = new T();
    return typeof(T).GetFields()
        .Select(fieldInfo => (T)fieldInfo.GetValue(valueType))
        .Distinct()
        .ToList();
}

public static List<String> GetEnumNames<T>() {
    return typeof (T).GetFields()
        .Select(info => info.Name)
        .Distinct()
        .ToList();
}
  • If anyone knows how to get rid of the T valueType = new T(), I'd be happy to see a solution.

A call would look like this:

List<MyEnum> result = Utils.GetEnumValues<MyEnum>();

SQL Server remove milliseconds from datetime

Please try this

select substring('12:20:19.8470000',1,(CHARINDEX('.','12:20:19.8470000',1)-1))


(No column name)
12:20:19

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

If you don't have cocoa pods installed you need to:

sudo gem install cocoapods

Then run:

cd /ios
pod install

delete the build folder in ios folder of your react native project

run:

react-native run-ios

if error persists:

  • delete build folder again
  • open the /ios folder in Xcode
  • navigate File -> Project Settings -> Build System -> change (Shared workspace settings and Per-User workspace settings): Build System -> Legacy Build System

How to create an 2D ArrayList in java?

This can be achieve by creating object of List data structure, as follows

List list = new ArrayList();

For more information refer this link

How to create a Multidimensional ArrayList in Java?

How to use "not" in xpath?

not() is a function in xpath (as opposed to an operator), so

//a[not(contains(@id, 'xx'))]

How do I create documentation with Pydoc?

As RocketDonkey suggested, your module itself needs to have some docstrings.

For example, in myModule/__init__.py:

"""
The mod module
"""

You'd also want to generate documentation for each file in myModule/*.py using

pydoc myModule.thefilename

to make sure the generated files match the ones that are referenced from the main module documentation file.

Importing files from different folder

You can use importlib to import modules where you want to import a module from a folder using a string like so:

import importlib

scriptName = 'Snake'

script = importlib.import_module('Scripts\\.%s' % scriptName)

This example has a main.py which is the above code then a folder called Scripts and then you can call whatever you need from this folder by changing the scriptName variable. You can then use script to reference to this module. such as if I have a function called Hello() in the Snake module you can run this function by doing so:

script.Hello()

I have tested this in Python 3.6

Table border left and bottom

You need to use the border property as seen here: jsFiddle

HTML:

<table width="770">
    <tr>
        <td class="border-left-bottom">picture (border only to the left and bottom ) </td>
        <td>text</td>
    </tr>
    <tr>
        <td>text</td>
        <td class="border-left-bottom">picture (border only to the left and bottom) </td>
    </tr>
</table>`

CSS:

td.border-left-bottom{
    border-left: solid 1px #000;
    border-bottom: solid 1px #000;
}

Why split the <script> tag when writing it with document.write()?

The </script> inside the Javascript string litteral is interpreted by the HTML parser as a closing tag, causing unexpected behaviour (see example on JSFiddle).

To avoid this, you can place your javascript between comments (this style of coding was common practice, back when Javascript was poorly supported among browsers). This would work (see example in JSFiddle):

<script type="text/javascript">
    <!--
    if (jQuery === undefined) {
        document.write('<script type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></script>');
    }
    // -->
</script>

...but to be honest, using document.write is not something I would consider best practice. Why not manipulating the DOM directly?

<script type="text/javascript">
    <!--
    if (jQuery === undefined) {
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', 'http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js');
        document.body.appendChild(script);
    }
    // -->
</script>

Python extract pattern matches

You can use groups (indicated with '(' and ')') to capture parts of the string. The match object's group() method then gives you the group's contents:

>>> import re
>>> s = 'name my_user_name is valid'
>>> match = re.search('name (.*) is valid', s)
>>> match.group(0)  # the entire match
'name my_user_name is valid'
>>> match.group(1)  # the first parenthesized subgroup
'my_user_name'

In Python 3.6+ you can also index into a match object instead of using group():

>>> match[0]  # the entire match 
'name my_user_name is valid'
>>> match[1]  # the first parenthesized subgroup
'my_user_name'

Python display text with font & color?

I wrote a wrapper, that will cache text surfaces, only re-render when dirty. googlecode/ninmonkey/nin.text/demo/

Convert HashBytes to VarChar

I have found the solution else where:

SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)

Convert list of ints to one number?

Just for completeness, here's a variant that uses print() (works on Python 2.6-3.x):

from __future__ import print_function
try: from cStringIO import StringIO
except ImportError:
     from io import StringIO

def to_int(nums, _s = StringIO()):
    print(*nums, sep='', end='', file=_s)
    s = _s.getvalue()
    _s.truncate(0)
    return int(s)

Time performance of different solutions

I've measured performance of @cdleary's functions. The results are slightly different.

Each function tested with the input list generated by:

def randrange1_10(digit_count): # same as @cdleary
    return [random.randrange(1, 10) for i in xrange(digit_count)]

You may supply your own function via --sequence-creator=yourmodule.yourfunction command-line argument (see below).

The fastest functions for a given number of integers in a list (len(nums) == digit_count) are:

  • len(nums) in 1..30

    def _accumulator(nums):
        tot = 0
        for num in nums:
            tot *= 10
            tot += num
        return tot
    
  • len(nums) in 30..1000

    def _map(nums):
        return int(''.join(map(str, nums)))
    
    def _imap(nums):
        return int(''.join(imap(str, nums)))
    

Figure: N = 1000

|------------------------------+-------------------|
| Fitting polynom              | Function          |
|------------------------------+-------------------|
| 1.00  log2(N)   +  1.25e-015 | N                 |
| 2.00  log2(N)   +  5.31e-018 | N*N               |
| 1.19  log2(N)   +      1.116 | N*log2(N)         |
| 1.37  log2(N)   +      2.232 | N*log2(N)*log2(N) |
|------------------------------+-------------------|
| 1.21  log2(N)   +      0.063 | _interpolation    |
| 1.24  log2(N)   -      0.610 | _genexp           |
| 1.25  log2(N)   -      0.968 | _imap             |
| 1.30  log2(N)   -      1.917 | _map              |

Figure: N = 1000_000

To plot the first figure download cdleary.py and make-figures.py and run (numpy and matplotlib must be installed to plot):

$ python cdleary.py 

Or

$ python make-figures.py --sort-function=cdleary._map \
> --sort-function=cdleary._imap \
> --sort-function=cdleary._interpolation \
> --sort-function=cdleary._genexp --sort-function=cdleary._sum \
> --sort-function=cdleary._reduce --sort-function=cdleary._builtins \
> --sort-function=cdleary._accumulator \
> --sequence-creator=cdleary.randrange1_10 --maxn=1000 

Only allow specific characters in textbox

As mentioned in a comment (and another answer as I typed) you need to register an event handler to catch the keydown or keypress event on a text box. This is because TextChanged is only fired when the TextBox loses focus

The below regex lets you match those characters you want to allow

Regex regex = new Regex(@"[0-9+\-\/\*\(\)]");
MatchCollection matches = regex.Matches(textValue);

and this does the opposite and catches characters that aren't allowed

Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textValue);

I'm not assuming there'll be a single match as someone could paste text into the textbox. in which case catch textchanged

textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
private void textBox1_TextChanged(object sender, EventArgs e)
{
    Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
    MatchCollection matches = regex.Matches(textBox1.Text);
    if (matches.Count > 0) {
       //tell the user
    }
}

and to validate single key presses

textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for a naughty character in the KeyDown event.
    if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^\-^\/^\*^\(^\)]"))
    {
        // Stop the character from being entered into the control since it is illegal.
        e.Handled = true;
    }
}

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

How do I run Redis on Windows?

One of the most easy way to run Redis on windows host is to use Docker Redis container. Just fire up Hyper-V, Download Docker and run Redis

What is a raw type and why shouldn't we use it?

A raw-type is the a lack of a type parameter when using a generic type.

Raw-type should not be used because it could cause runtime errors, like inserting a double into what was supposed to be a Set of ints.

Set set = new HashSet();
set.add(3.45); //ok

When retrieving the stuff from the Set, you don't know what is coming out. Let's assume that you expect it to be all ints, you are casting it to Integer; exception at runtime when the double 3.45 comes along.

With a type parameter added to your Set, you will get a compile error at once. This preemptive error lets you fix the problem before something blows up during runtime (thus saving on time and effort).

Set<Integer> set = new HashSet<Integer>();
set.add(3.45); //NOT ok.

Complex JSON nesting of objects and arrays

You can try use this function to find any object in nested nested array of arrays of kings.

Example

function findTByKeyValue (element, target){
        var found = true;
        for(var key in target) { 
            if (!element.hasOwnProperty(key) || element[key] !== target[key])   { 
                found = false;
                break;
            }
        }
        if(found) {
            return element;
        }
        if(typeof(element) !== "object") { 
            return false;
        }
        for(var index in element) { 
            var result = findTByKeyValue(element[index],target);
            if(result) { 
                return result; 
            }
        } 
    };

findTByKeyValue(problems,{"name":"somethingElse","strength":"500 mg"}) =====> result equal to object associatedDrug#2

Take nth column in a text file

For the sake of completeness:

while read _ _ one _ two _; do
    echo "$one $two"
done < file.txt

Instead of _ an arbitrary variable (such as junk) can be used as well. The point is just to extract the columns.

Demo:

$ while read _ _ one _ two _; do echo "$one $two"; done < /tmp/file.txt
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495

How do I make a semi transparent background?

Use rgba():

.transparent {
  background-color: rgba(255,255,255,0.5);
}

This will give you 50% opacity while the content of the box will continue to have 100% opacity.

If you use opacity:0.5, the content will be faded as well as the background. Hence do not use it.

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

I solved this problem by using: chown -R etc/asterisk chown -R var/lib/asterisk

this is bacause, as said here, I wasn't running as administrator. So, I made my user as owner of the Asterisk directories.

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

Query to list all stored procedures

USE DBNAME

select ROUTINE_NAME from information_schema.routines 
where routine_type = 'PROCEDURE'


GO 

This will work on mssql.

How can I do division with variables in a Linux shell?

I believe it was already mentioned in other threads:

calc(){ awk "BEGIN { print "$*" }"; }

then you can simply type :

calc 7.5/3.2
  2.34375

In your case it will be:

x=20; y=3;
calc $x/$y

or if you prefer, add this as a separate script and make it available in $PATH so you will always have it in your local shell:

#!/bin/bash
calc(){ awk "BEGIN { print $* }"; }

Convert a Unix timestamp to time in JavaScript

Another way - from an ISO 8601 date.

_x000D_
_x000D_
var timestamp = 1293683278;_x000D_
var date = new Date(timestamp * 1000);_x000D_
var iso = date.toISOString().match(/(\d{2}:\d{2}:\d{2})/)_x000D_
alert(iso[1]);
_x000D_
_x000D_
_x000D_

Check if a variable is between two numbers with Java

Assuming you are programming in Java, this works:

if (90 >= angle  &&  angle <= 180 )  {

(don't you mean 90 is less than angle? If so: 90 <= angle)

Assign multiple values to array in C

You can use:

GLfloat coordinates[8] = {1.0f, ..., 0.0f};

but this is a compile-time initialisation - you can't use that method in the current standard to re-initialise (although I think there are ways to do it in the upcoming standard, which may not immediately help you).

The other two ways that spring to mind are to blat the contents if they're fixed:

GLfloat base_coordinates[8] = {1.0f, ..., 0.0f};
GLfloat coordinates[8];
:
memcpy (coordinates, base_coordinates, sizeof (coordinates));

or provide a function that looks like your initialisation code anyway:

void setCoords (float *p0, float p1, ..., float p8) {
    p0[0] = p1; p0[1] = p2; p0[2] = p3; p0[3] = p4;
    p0[4] = p5; p0[5] = p6; p0[6] = p7; p0[7] = p8;
}
:
setCoords (coordinates, 1.0f, ..., 0.0f);

keeping in mind those ellipses (...) are placeholders, not things to literally insert in the code.

How to change an application icon programmatically in Android?

As mentioned before you need use <activity-alias> to change the application icon. To avoid killing the application after enabling appropriate activity-alias you need to do this after the application is killed. To find out if the application was killed you can use this method

  1. Create activity aliases in AndroidManifest.xml
<activity android:name=".ui.MainActivity"/>

<activity-alias
    android:name=".one"
    android:icon="@mipmap/ic_launcher_one"
    android:targetActivity=".ui.MainActivity"
    android:enabled="true">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity-alias>

<activity-alias
    android:name=".two"
    android:icon="@mipmap/ic_launcher_two"
    android:targetActivity=".ui.MainActivity"
    android:enabled="false">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity-alias>
  1. ?reate a service that will change the active activity-alias after killing the application. You need store the name of new active activity-alias somewhere (e.g. SharedPreferences)
class ChangeAppIconService: Service() {
    private val aliases = arrayOf(".one", ".two")

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onTaskRemoved(rootIntent: Intent?) {
        changeAppIcon()
        stopSelf()
    }

    fun changeAppIcon() {
        val sp = getSharedPreferences("appSettings", Context.MODE_PRIVATE)

        sp.getString("activeActivityAlias", ".one").let { aliasName ->
            if (!isAliasEnabled(aliasName)) {
                setAliasEnabled(aliasName)
            }
        }
    }

    private fun isAliasEnabled(aliasName: String): Boolean {
        return packageManager.getComponentEnabledSetting(
            ComponentName(
                this,
                "${BuildConfig.APPLICATION_ID}$aliasName"
            )
        ) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
    }

    private fun setAliasEnabled(aliasName: String) {
        aliases.forEach {
            val action = if (it == aliasName)
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED
            else
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                
            packageManager.setComponentEnabledSetting(
                ComponentName(
                    this,
                    "${BuildConfig.APPLICATION_ID}$aliasName"
                ),
                action,
                PackageManager.DONT_KILL_APP
            )
        }
    }
}
  1. Add service to AndroidManifest.xml
<service 
    android:name=".ChangeAppIconService"
    android:stopWithTask="false"
    />
  1. Start ChangeAppIconService in MainActivity.onCreate
class MainActivity: Activity {

    ...

    override fun onCreate(savedInstanceState: Bundle?) {
       ...

       startService(Intent(this, ChangeAppIconService::class.java))

       ...
    }

    ...

}

Make an Android button change background on click through XML

I used this to change the background for my button

            button.setBackground(getResources().getDrawable(R.drawable.primary_button));

"button" is the variable holding my Button, and the image am setting in the background is primary_button

Example use of "continue" statement in Python?

Usually the situation where continue is necessary/useful, is when you want to skip the remaining code in the loop and continue iteration.

I don't really believe it's necessary, since you can always use if statements to provide the same logic, but it might be useful to increase readability of code.

How to start/stop/restart a thread in Java?

It is impossible to terminate a thread unless the code running in that thread checks for and allows termination.

You said: "Sadly I must kill/restart it ... I don't have complete control over the contents of the thread and for my situation it requires a restart"

If the contents of the thread does not allow for termination of its exectuion then you can not terminate that thread.

In your post you said: "My first attempt was with ExecutorService but I can't seem to find a way for it restart a task. When I use .shutdownnow()..."

If you look at the source of "shutdownnow" it just runs through and interrupts the currently running threads. This will not stop their execution unless the code in those threads checks to see if it has been ineterrupted and, if so, stops execution itself. So shutdownnow is probably not doing what you think.

Let me illustrate what I mean when I say that the contents of the thread must allow for that thread to be terminated:

myExecutor.execute(new Runnable() {
 public void run() {
  while (true) {
    System.out.println("running");
  }
 }
 });
myExecutor.shutdownnow();

That thread will continue to run forever, even though shutdownnow was called, because it never checks to see if it has been terminated or not. This thread, however, will shut down:

myExecutor.execute(new Runnable() {
 public void run() {
  while (!Thread.interrupted()) {
    System.out.println("running");
  }
 }
 });
myExecutor.shutdownnow();

Since this thread checks to see whether or not it has been interrupted / shut down / terminated.

So if you want a thread that you can shut down, you need to make sure it checks to see if it has been interrupted. If you want a thread that you can "shut down" and "restart" you can make a runnable that can take new tasks as was mentioned before.

Why can you not shut down a running thread? Well I actually lied, you can call "yourThread.stop()" but why is this a bad idea? The thread could be in a synchronized (or other critical section, but we will limit ourselves to setions guarded by the syncrhonized key word here) section of code when you stop it. synch blocks are supposed to be executed in their entirity and only by one thread before being accessed by some other thread. If you stop a thread in the middle of a synch block, the protection put into place by the synch block is invalidated and your program will get into an unknown state. Developers make put stuff in synch blocks to keep things in synch, if you use threadInstance.stop() you destroy the meaning of synchronize, what the developer of that code was trying to accomplish and how the developer of that code expected his synchronized blocks to behave.

How do I install Maven with Yum?

You can add maven to the yum libraries like this:

wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

Now you can install maven like this:

yum install apache-maven

Once done, maven 3 will be installed and mvn -version will show you which version you've got - I had 3.2.1.

This worked perfectly for me on CentOS 6 with one exception. It installed OpenJDK 1.6 and made it the default Java version, even though I'd already manually installed JDK 8 (possibly because I'd manually installed it). To change it back use alternatives:

alternatives --config java
alternatives --config javac

and choose the correct version.

Read text from response

Your "application/xrds+xml" was giving me issues, I was receiving a Content-Length of 0 (no response).

After removing that, you can access the response using response.GetResponseStream().

HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;

//request.Accept = "application/xrds+xml";  
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

WebHeaderCollection header = response.Headers;

var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
    string responseText = reader.ReadToEnd();
}

How do I reflect over the members of dynamic object?

If the IDynamicMetaObjectProvider can provide the dynamic member names, you can get them. See GetMemberNames implementation in the apache licensed PCL library Dynamitey (which can be found in nuget), it works for ExpandoObjects and DynamicObjects that implement GetDynamicMemberNames and any other IDynamicMetaObjectProvider who provides a meta object with an implementation of GetDynamicMemberNames without custom testing beyond is IDynamicMetaObjectProvider.

After getting the member names it's a little more work to get the value the right way, but Impromptu does this but it's harder to point to just the interesting bits and have it make sense. Here's the documentation and it is equal or faster than reflection, however, unlikely to be faster than a dictionary lookup for expando, but it works for any object, expando, dynamic or original - you name it.

Check status of one port on remote host

I think you're looking for Hping (http://www.hping.org/), which has a Windows version.

"The interface is inspired to the ping(8) unix command, but hping isn't only able to send ICMP echo requests. It supports TCP, UDP, ICMP..."

It's also very useful if you want to see where along a route that a TCP port is being blocked (like by a firewall), where ICMP might not be.

Add leading zeroes to number in Java?

String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

String formatted = String.format("%03d", num);
  • 0 - to pad with zeros
  • 3 - to set width to 3

Convert from MySQL datetime to another format with PHP

An easier way would be to format the date directly in the MySQL query, instead of PHP. See the MySQL manual entry for DATE_FORMAT.

If you'd rather do it in PHP, then you need the date function, but you'll have to convert your database value into a timestamp first.

LINQ to SQL Left Outer Join

Not quite - since each "left" row in a left-outer-join will match 0-n "right" rows (in the second table), where-as yours matches only 0-1. To do a left outer join, you need SelectMany and DefaultIfEmpty, for example:

var query = from c in db.Customers
            join o in db.Orders
               on c.CustomerID equals o.CustomerID into sr
            from x in sr.DefaultIfEmpty()
            select new {
               CustomerID = c.CustomerID, ContactName = c.ContactName,
               OrderID = x == null ? -1 : x.OrderID };   

(or via the extension methods)

Connecting PostgreSQL 9.2.1 with Hibernate

This is the hibernate.cfg.xml file to connect postgresql 9.5 and this is help to you basic configuration.

 <?xml version='1.0' encoding='utf-8'?>

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration
>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://localhost:5433/hibernatedb</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">password</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.waseem.UserDetails"/>
    </session-factory>
</hibernate-configuration>

Make sure File Location should be under src/main/resources/hibernate.cfg.xml

How can I retrieve the remote git address of a repo?

When you want to show an URL of remote branches, try:

git remote -v

Should I use JSLint or JSHint JavaScript validation?

There is also an another actively developed alternative - JSCS — JavaScript Code Style:

JSCS is a code style linter for programmatically enforcing your style guide. You can configure JSCS for your project in detail using over 150 validation rules, including presets from popular style guides like jQuery, Airbnb, Google, and more.

It comes with multiple presets that you can choose from by simply specifying the preset in the .jscsrc configuration file and customize it - override, enable or disable any rules:

{
    "preset": "jquery",
    "requireCurlyBraces": null
}

There are also plugins and extensions built for popular editors.

Also see:

The mysqli extension is missing. Please check your PHP configuration

I had the same problem and I solved it. You can solve it too if you follow these steps:

  1. you have to install PHP to C:/php or your current version locate it to this path and specify it as a system variable
  2. then open xampp program and click config and open php.ini and uncomment the following lines:

    extension=pdo_mysql
    extension=pdo_mysql
    extension=openssl
    

Difference between id and name attributes in HTML

Below is an interesting use of the id attribute. It is used within the tag and used to identify the form for elements outside of the boundaries so that they will be included with the other fields within the form.

 <form action="action_page.php" id="form1">
 First name: <input type="text" name="fname"><br>
 <input type="submit" value="Submit">
 </form>

 <p>The "Last name" field below is outside the form element, but still part of the form.</p>
 Last name: <input type="text" name="lname" form="form1">

org.json.simple cannot be resolved

Try importing this in build.gradle dependencies

compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'

Remove All Event Listeners of Specific Type

The quick and dirty way

element.onmousedown = null;

now you can go back to adding event listeners via

element.addEventListener('mousedown', handler, ...);

Jquery - How to make $.post() use contentType=application/json?

You can't send application/json directly -- it has to be a parameter of a GET/POST request.

So something like

$.post(url, {json: "...json..."}, function());

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

I'd use an Inline Function from performance perspective, see below: Note that symbols like '+','-' etc will not be removed

CREATE FUNCTION [dbo].[UDF_RemoveNumericStringsFromString]
 (
 @str varchar(100)
 )
 RETURNS TABLE AS RETURN
 WITH Tally (n) as 
  (
  -- 100 rows
   SELECT TOP (Len(@Str)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
   FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
   CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
  )

  SELECT OutStr =  STUFF(
       (SELECT SUBSTRING(@Str, n,1) st
        FROM Tally
        WHERE ISNUMERIC(SUBSTRING(@Str, n,1)) = 1
        FOR XML PATH(''),type).value('.', 'varchar(100)'),1,0,'')
  GO

  /*Use it*/
  SELECT OutStr
  FROM dbo.UDF_RemoveNumericStringsFromString('fjkfhk759734977fwe9794t23')
  /*Result set
   759734977979423 */

You can define it with more than 100 characters...

JQuery select2 set default value from an option in list?

For ajax select2 multiple select dropdown i did like this;

  //preset element values
  //topics is an array of format [{"id":"","text":""}, .....]
        $(id).val(topics);
          setTimeout(function(){
           ajaxTopicDropdown(id,
                2,location.origin+"/api for gettings topics/",
                "Pick a topic", true, 5);                      
            },1);
        // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

Copy or rsync command

The command as written will create new directories and files with the current date and time stamp, and yourself as the owner. If you are the only user on your system and you are doing this daily it may not matter much. But if preserving those attributes matters to you, you can modify your command with

cp -pur /home/abc/* /mnt/windowsabc/

The -p will preserve ownership, timestamps, and mode of the file. This can be pretty important depending on what you're backing up.

The alternative command with rsync would be

rsync -avh /home/abc/* /mnt/windowsabc

With rsync, -a indicates "archive" which preserves all those attributes mentioned above. -v indicates "verbose" which just lists what it's doing with each file as it runs. -z is left out here for local copies, but is for compression, which will help if you are backing up over a network. Finally, the -h tells rsync to report sizes in human-readable formats like MB,GB,etc.

Out of curiosity, I ran one copy to prime the system and avoid biasing against the first run, then I timed the following on a test run of 1GB of files from an internal SSD drive to a USB-connected HDD. These simply copied to empty target directories.

cp -pur    : 19.5 seconds
rsync -ah  : 19.6 seconds
rsync -azh : 61.5 seconds

Both commands seem to be about the same, although zipping and unzipping obviously tax the system where bandwidth is not a bottleneck.

Javascript foreach loop on associative array object

You can Do this

var array = [];

// assigning values to corresponding keys
array[0] = "Main page";
array[1] = "Guide page";
array[2] = "Articles page";
array[3] = "Forum board";


array.forEach(value => {
    console.log(value)
})

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

How to set min-height for bootstrap container

Two things are happening here.

  1. You are not using the container class properly.
  2. You are trying to override Bootstrap's CSS for the container class

Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.

What you want to do is the following:

<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
    <div class="row">
        <div class="col-md-4 myClassName">  <!-- myClassName is defined in my CSS as you defined your container -->
            <img src="#.jpg" height="200px" width="300px">
        </div>
    </div>
</div>

Here you can find more info on the Bootstrap grid system.

That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...

.container {
   padding-right: 15px;
   padding-left: 15px;
   margin-right: auto;
   margin-left: auto;
   max-width: 900px;
   overflow:hidden;
   min-height:0px !important;
}

But I have always found that the "!important" clause just makes for messy CSS.

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

In Java, can you modify a List while iterating through it?

There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

How do I list / export private keys from a keystore?

First of all, be careful! All of your security depends on the… er… privacy of your private keys. Keytool doesn't have key export built in to avoid accidental disclosure of this sensitive material, so you might want to consider some extra safeguards that could be put in place to protect your exported keys.

Here is some simple code that gives you unencrypted PKCS #8 PrivateKeyInfo that can be used by OpenSSL (see the -nocrypt option of its pkcs8 utility):

KeyStore keys = ...
char[] password = ...
Enumeration<String> aliases = keys.aliases();
while (aliases.hasMoreElements()) {
  String alias = aliases.nextElement();
  if (!keys.isKeyEntry(alias))
    continue;
  Key key = keys.getKey(alias, password);
  if ((key instanceof PrivateKey) && "PKCS#8".equals(key.getFormat())) {
    /* Most PrivateKeys use this format, but check for safety. */
    try (FileOutputStream os = new FileOutputStream(alias + ".key")) {
      os.write(key.getEncoded());
      os.flush();
    }
  }
}

If you need other formats, you can use a KeyFactory to get a transparent key specification for different types of keys. Then you can get, for example, the private exponent of an RSA private key and output it in your desired format. That would make a good topic for a follow-up question.

Git pull a certain branch from GitHub

I did

git branch -f new_local_branch_name origin/remote_branch_name

Instead of

git branch -f new_local_branch_name upstream/remote_branch_name

As suggested by @innaM. When I used the upstream version, it said 'fatal: Not a valid object name: 'upstream/remote_branch_name''. I did not do git fetch origin as a comment suggested, but instead simply replaced upstream with origin. I guess they are equivalent.

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

Few steps to add Access-Control-Allow-Origin header to localhost or *.

Step 1: Create Cors middleware :

php artisan make:middleware Cors

Step 2: Set header in Cors middleware like this

public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->headers->set('Access-Control-Allow-Origin' , '*');
        $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');

        return $response;
    }

Step 3: We need to add Cors class in app/Http/Kernel.php

 protected $middleware = [
        ....
        \App\Http\Middleware\Cors::class,
    ];

Here no needed to check any middleware because we add Cors class in $middleware in app/Http/Kernel.php

Can't choose class as main class in IntelliJ

Here is the complete procedure for IDEA IntelliJ 2019.3:

  1. File > Project Structure

  2. Under Project Settings > Modules

  3. Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.

  4. Apply changes.

How do I center a window onscreen in C#?

Use Location property of the form. Set it to the desired top left point

desired x = (desktop_width - form_witdh)/2

desired y = (desktop_height - from_height)/2

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

PHP and MySQL Select a Single Value

Try this

$value = mysql_result($result, 0);

How would I get a cron job to run every 30 minutes?

Try this:

0,30 * * * * your command goes here

According to the official Mac OS X crontab(5) manpage, the / syntax is supported. Thus, to figure out why it wasn't working for you, you'll need to look at the logs for cron. In those logs, you should find a clear failure message.

Note: Mac OS X appears to use Vixie Cron, the same as Linux and the BSDs.

Setting onSubmit in React.js

You can pass the event as argument to the function and then prevent the default behaviour.

var OnSubmitTest = React.createClass({
        render: function() {
        doSomething = function(event){
           event.preventDefault();
           alert('it works!');
        }

        return <form onSubmit={this.doSomething}>
        <button>Click me</button>
        </form>;
    }
});

where is gacutil.exe?

On Windows 2012 R2, you can't install Visual Studio or SDK. You can use powershell to register assemblies into GAC. It didn't need any special installation for me.

Set-location "C:\Temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Temp\myGacLibrary.dll")

If you need to get the name and PublicKeyToken see this question.

Bootstrap carousel multiple frames at once

Try this code


 <div id="recommended-item-carousel" class="carousel slide" data-ride="carousel">
    <div class="carousel-inner">
        <div class="item active">

            <div class="col-sm-3">
                <div class="product-image-wrapper">
                    <div class="single-products">
                        <div class="productinfo text-center">
                            <img src="img/home/recommend1.jpg" alt="" />
                            <h2>$56</h2>
                            <p>
                                Easy Polo Black Edition
                            </p>
                            <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                        </div>

                    </div>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="product-image-wrapper">
                    <div class="single-products">
                        <div class="productinfo text-center">
                            <img src="img/home/recommend2.jpg" alt="" />
                            <h2>$56</h2>
                            <p>
                                Easy Polo Black Edition
                            </p>
                            <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                        </div>

                    </div>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="product-image-wrapper">
                    <div class="single-products">
                        <div class="productinfo text-center">
                            <img src="img/home/recommend3.jpg" alt="" />
                            <h2>$56</h2>
                            <p>
                                Easy Polo Black Edition
                            </p>
                            <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <div class="item">
            <div class="col-sm-3">
                <div class="product-image-wrapper">
                    <div class="single-products">
                        <div class="productinfo text-center">
                            <img src="img/home/recommend1.jpg" alt="" />
                            <h2>$56</h2>
                            <p>
                                Easy Polo Black Edition
                            </p>
                            <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                        </div>

                    </div>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="product-image-wrapper">
                    <div class="single-products">
                        <div class="productinfo text-center">
                            <img src="img/home/recommend2.jpg" alt="" />
                            <h2>$56</h2>
                            <p>
                                Easy Polo Black Edition
                            </p>
                            <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                        </div>

                    </div>
                </div>
            </div>
            <div class="col-sm-3">
                <div class="product-image-wrapper">
                    <div class="single-products">
                        <div class="productinfo text-center">
                            <img src="img/home/recommend3.jpg" alt="" />
                            <h2>$56</h2>
                            <p>
                                Easy Polo Black Edition
                            </p>
                            <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
    <a class="left recommended-item-control" href="#recommended-item-carousel" data-slide="prev"> <i class="fa fa-angle-left"></i> </a>
    <a class="right recommended-item-control" href="#recommended-item-carousel" data-slide="next"> <i class="fa fa-angle-right"></i> </a>
</div>

random.seed(): What does it do?

>>> random.seed(9001)   
>>> random.randint(1, 10)  
1     
>>> random.seed(9001)     
>>> random.randint(1, 10)    
1           
>>> random.seed(9001)          
>>> random.randint(1, 10)                 
1                  
>>> random.seed(9001)         
>>> random.randint(1, 10)          
1     
>>> random.seed(9002)                
>>> random.randint(1, 10)             
3

You try this.

Let's say 'random.seed' gives a value to random value generator ('random.randint()') which generates these values on the basis of this seed. One of the must properties of random numbers is that they should be reproducible. When you put same seed, you get the same pattern of random numbers. This way you are generating them right from the start. You give a different seed- it starts with a different initial (above 3).

Given a seed, it will generate random numbers between 1 and 10 one after another. So you assume one set of numbers for one seed value.

How do I determine if a checkbox is checked?

Place the var lfckv inside the function. When that line is executed, the body isn't parsed yet and the element "lifecheck" doesn't exist. This works perfectly fine:

_x000D_
_x000D_
function exefunction() {_x000D_
  var lfckv = document.getElementById("lifecheck").checked;_x000D_
  alert(lfckv);_x000D_
}
_x000D_
<label><input id="lifecheck" type="checkbox" >Lives</label>_x000D_
<button onclick="exefunction()">Check value</button>
_x000D_
_x000D_
_x000D_

ReSharper "Cannot resolve symbol" even when project builds

When I disabled ReSharper, Visual Studio was also giving the same error, even though the project built successfully. What I did to resolve the issue was:

  1. Remove the project from the solution.
  2. Right-click the solution, Add Existing Project, select the project file and add it again.

After performing these steps, the syntax errors went away in Visual Studio, and after I enabled ReSharper again, it also had no errors.

How to reload the current state?

For angular v1.2.26, none of the above works. An ng-click that calls the above methods will have to be clicked twice in order to make the state reload.

So I ended up emulating 2 clicks using $timeout.

$provide.decorator('$state',
        ["$delegate", "$stateParams", '$timeout', function ($delegate, $stateParams, $timeout) {
            $delegate.forceReload = function () {
                var reload = function () {
                    $delegate.transitionTo($delegate.current, angular.copy($stateParams), {
                        reload: true,
                        inherit: true,
                        notify: true
                    })
                };
                reload();
                $timeout(reload, 100);
            };
            return $delegate;
        }]);

How do I check how many options there are in a dropdown menu?

Use the length property or the size method to find out how many items are in a jQuery collection. Use the descendant selector to select all <option>'s within a <select>.

HTML:

<select id="myDropDown">
<option>1</option>
<option>2</option>
.
.
.
</select>

JQuery:

var numberOfOptions = $('select#myDropDown option').length

And a quick note, often you will need to do something in jquery for a very specific thing, but you first need to see if the very specific thing exists. The length property is the perfect tool. example:

   if($('#myDropDown option').length > 0{
      //do your stuff..
    } 

This 'translates' to "If item with ID=myDropDown has any descendent 'option' s, go do what you need to do.

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

short answer - add following line in the jsp which will define the base
base href="/{root of your application}/"

Convert JavaScript String to be all lower case?

In case you want to build it yourself:

function toLowerCase(string) {

let lowerCaseString = "";

for (let i = 0; i < string.length; i++) {
    //find ASCII charcode
    let charcode = string.charCodeAt(i);

    //if uppercase
    if (charcode > 64 && charcode < 97){
        //convert to lowercase
        charcode = charcode + 32
    }

    //back to char
    let lowercase = String.fromCharCode(charcode);

    //append
    lowerCaseString = lowerCaseString.concat(lowercase);
}

return lowerCaseString

}

Print an ArrayList with a for-each loop

Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:

// add values
list.add("one");
list.add("two");

// your code
for (String object: list) {
    System.out.println(object);
}

error : expected unqualified-id before return in c++

if (chapeau) {

You forgot the ending brace to this if statement, so the subsequent else if is considered a syntax error. You need to add the brace when the if statement body is complete:

if (chapeau) {
    cout << "le Professeur Violet";
}
else if (moustaches) {
    cout << "le Colonel Moutarde";
}
// ...

Combining multiple commits before pushing in Git

And my way of squashing multiple push is (perhaps you pushed to your own branch many commits and now you wish to do a pull request and you don't want to clutter them with many commits which you have already pushed). The way I do that (no other simpler option as far as I can tell is).

  1. Create new branch for the sake of squash (branch from the original branch you wish to pull request to).
  2. Push the newly created branch.
  3. Merge branch with commits (already pushed) to new branch.
  4. Rebase new branch and squash.
  5. Push new branch.
  6. Create new pull request for new branch which now has single commit.

Example:

git checkout from_branch_you_wish_to_pull_request_to
git checkout -b new_branch_will_have_single_squashed_commit
git push -u new_branch_will_have_single_squashed_commit
git merge older_branch_with_all_those_multiple_commits
git rebase -i (here you squash)
git push origin new_branch_will_have_single_squashed_commit

You can now pull request into from_branch_you_wish_to_pull_request_to

Terminating a Java Program

Because System.exit() is just another method to the compiler. It doesn't read ahead and figure out that the whole program will quit at that point (the JVM quits). Your OS or shell can read the integer that is passed back in the System.exit() method. It is standard for 0 to mean "program quit and everything went OK" and any other value to notify an error occurred. It is up to the developer to document these return values for any users.

return on the other hand is a reserved key word that the compiler knows well. return returns a value and ends the current function's run moving back up the stack to the function that invoked it (if any). In your code above it returns void as you have not supplied anything to return.

Why isn't .ico file defined when setting window's icon?

This works for me with Python3 on Linux:

import tkinter as tk

# Create Tk window
root = tk.Tk()

# Add icon from GIF file where my GIF is called 'icon.gif' and
# is in the same directory as this .py file
root.tk.call('wm', 'iconphoto', root._w, tk.PhotoImage(file='icon.gif'))

IIS Config Error - This configuration section cannot be used at this path

I came across this thread and solve the issue by below steps, My problem may be different. Hope this can help some one .

In Turn windows feature on and off navigate to server roles and select the least below mentioned items .

enter image description here

Cheers !

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

I got exactly the same error message and in my case it turned out i didn't list the controller JS file (e.g. first-ctrl.js) in my index.html

How can I convert a DateTime to an int?

I think you want (this won't fit in a int though, you'll need to store it as a long):

long result = dateDate.Year * 10000000000 + dateDate.Month * 100000000 + dateDate.Day * 1000000 + dateDate.Hour * 10000 + dateDate.Minute * 100 + dateDate.Second;

Alternatively, storing the ticks is a better idea.

Event listener for when element becomes visible?

Javascript events deal with User Interaction, if your code is organised enough you should be able to call the initialising function in the same place where the visibility changes (i.e. you shouldn't change myElement.style.display on many places, instead, call a function/method that does this and anything else you might want).

How to trace the path in a Breadth-First Search?

I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.

In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour will have to be the end, and once that happens the shortest path is found and program can return.

I would modify the the method as follow, pay close attention to the for loop

graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}


    def bfs(graph_to_search, start, end):
        queue = [[start]]
        visited = set()

    while queue:
        # Gets the first path in the queue
        path = queue.pop(0)

        # Gets the last node in the path
        vertex = path[-1]

        # Checks if we got to the end
        if vertex == end:
            return path
        # We check if the current node is already in the visited nodes set in order not to recheck it
        elif vertex not in visited:
            # enumerate all adjacent nodes, construct a new path and push it into the queue
            for current_neighbour in graph_to_search.get(vertex, []):
                new_path = list(path)
                new_path.append(current_neighbour)
                queue.append(new_path)

                #No need to visit other neighbour. Return at once
                if current_neighbour == end
                    return new_path;

            # Mark the vertex as visited
            visited.add(vertex)


print bfs(graph, 1, 13)

The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.

Save attachments to a folder and rename them

Public Sub Extract_Outlook_Email_Attachments()

Dim OutlookOpened As Boolean
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outFolder As Outlook.MAPIFolder
Dim outAttachment As Outlook.Attachment
Dim outItem As Object
Dim saveFolder As String
Dim outMailItem As Outlook.MailItem
Dim inputDate As String, subjectFilter As String


saveFolder = "Y:\Wingman" ' THIS IS WHERE YOU WANT TO SAVE THE ATTACHMENT TO

If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\"

subjectFilter = ("Daily Operations Custom All Req Statuses Report") ' THIS IS WHERE YOU PLACE THE EMAIL SUBJECT FOR THE CODE TO FIND

OutlookOpened = False
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
    Set outApp = New Outlook.Application
    OutlookOpened = True
End If
On Error GoTo 0

If outApp Is Nothing Then
    MsgBox "Cannot start Outlook.", vbExclamation
    Exit Sub
End If

Set outNs = outApp.GetNamespace("MAPI")
Set outFolder = outNs.GetDefaultFolder(olFolderInbox)

If Not outFolder Is Nothing Then
    For Each outItem In outFolder.Items
        If outItem.Class = Outlook.OlObjectClass.olMail Then
            Set outMailItem = outItem
                If InStr(1, outMailItem.Subject, subjectFilter) > 0 Then 'removed the quotes around subjectFilter
                    For Each outAttachment In outMailItem.Attachments
                    outAttachment.SaveAsFile saveFolder & outAttachment.filename

                    Set outAttachment = Nothing

                    Next
                End If
        End If
    Next
End If

If OutlookOpened Then outApp.Quit

Set outApp = Nothing

End Sub

PDF Blob - Pop up window not showing content

You need to set the responseType to arraybuffer if you would like to create a blob from your response data:

$http.post('/fetchBlobURL',{myParams}, {responseType: 'arraybuffer'})
   .success(function (data) {
       var file = new Blob([data], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
       window.open(fileURL);
});

more information: Sending_and_Receiving_Binary_Data

How to validate array in Laravel?

You have to loop over the input array and add rules for each input as described here: Loop Over Rules

Here is a some code for ya:

$input = Request::all();
$rules = [];

foreach($input['name'] as $key => $val)
{
    $rules['name.'.$key] = 'required|distinct|min:3';
}

$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';

$validator = Validator::make($input, $rules);

//Now check validation:
if ($validator->fails()) 
{ 
  /* do something */ 
}

How to combine 2 plots (ggplot) into one plot?

Just combine them. I think this should work but it's untested:

p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + 
     geom_smooth(fill="blue", colour="darkblue", size=1)

p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) + 
     geom_smooth(data=visual2, fill="red", colour="red", size=1)

print(p)

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

All sprints are iterations but not all iterations are sprints. Iteration is a common term in iterative and incremental development (IID). Scrum is one specialized flavor of IID so it makes sense to specialize the terminology as well. It also helps brand the methodology different from other IID methodologies :)

As to the sprint length: anything goes as long as the sprint is timeboxed i.e. it is finished on the planned date and not "when it's ready". (Or alternatively, in rare occasions, the sprint is terminated prematurely to start a new sprint in case some essential boundary conditions are changed.)

It does help to have the sprints of similar durations. There's less to remember about the sprint schedule and your planning gets more accurate. I like to keep mine at 2 calendar weeks, which will resolve into 8..10 business days outside holiday seasons.

How to POST URL in data of a curl request

I don't think it's necessary to use semi-quotes around the variables, try:

curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"

%2f is the escape code for a /.

http://www.december.com/html/spec/esccodes.html

Also, do you need to specify a port? ( just checking :) )

Address already in use: JVM_Bind

As an aside, under Windows, ProcessExplorer is fantastic for observing the existing TCP/IP connections for each process.

Convert boolean to int in Java

int myInt = myBoolean ? 1 : 0;

^^

PS : true = 1 and false = 0

Get data from php array - AJAX - jQuery

When you echo $array;, the result is Array, result[0] then represents the first character in Array which is A.

One way to handle this problem would be like this:

ajax.php

<?php
$array = array(1,2,3,4,5,6);
foreach($array as $a)
    echo $a.",";
?>

jquery code

$(function(){ /* short for $(document).ready(function(){ */

    $('#prev').click(function(){

        $.ajax({type:    'POST',
                 url:     'ajax.php',
                 data:    'id=testdata',
                 cache:   false,
                 success: function(data){
                     var tmp = data.split(",");
                     $('#content1').html(tmp[0]);
                 }
                });
    });

});

PHP is_numeric or preg_match 0-9 validation

is_numeric() tests whether a value is a number. It doesn't necessarily have to be an integer though - it could a decimal number or a number in scientific notation.

The preg_match() example you've given only checks that a value contains the digits zero to nine; any number of them, and in any sequence.

Note that the regular expression you've given also isn't a perfect integer checker, the way you've written it. It doesn't allow for negatives; it does allow for a zero-length string (ie with no digits at all, which presumably shouldn't be valid?), and it allows the number to have any number of leading zeros, which again may not be the intended.

[EDIT]

As per your comment, a better regular expression might look like this:

/^[1-9][0-9]*$/

This forces the first digit to only be between 1 and 9, so you can't have leading zeros. It also forces it to be at least one digit long, so solves the zero-length string issue.

You're not worried about negatives, so that's not an issue.

You might want to restrict the number of digits, because as things stand, it will allow strings that are too big to be stored as integers. To restrict this, you would change the star into a length restriction like so:

/^[1-9][0-9]{0,15}$/

This would allow the string to be between 1 and 16 digits long (ie the first digit plus 0-15 further digits). Feel free to adjust the numbers in the curly braces to suit your own needs. If you want a fixed length string, then you only need to specify one number in the braces.

Hope that helps.

Convert INT to VARCHAR SQL

Actually you don't need to use STR Or Convert. Just select 'xxx'+LTRIM(ColumnName) does the job. Possibly, LTRIM uses Convert or STR under the hood.

LTRIM also removes need for providing length and usually default 10 is good enough for integer to string conversion.

SELECT LTRIM(ColumnName) FROM TableName

How to select between brackets (or quotes or ...) in Vim?

A simple keymap in vim would solve this issue. map viq F”lvf”hh This above command maps viq to the keys to search between quotes. Replace " with any character and create your keymaps. Stick this in vimrc during startup and you should be able to use it everytime.

Git stash pop- needs merge, unable to refresh index

git reset if you don't want to commit these changes.

How to add new contacts in android

This is working fine for me:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            int rawContactInsertIndex = ops.size();

            ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
                    .withValue(RawContacts.ACCOUNT_TYPE, null)
                    .withValue(RawContacts.ACCOUNT_NAME, null).build());
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
                    .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(StructuredName.DISPLAY_NAME, "Vikas Patidar") // Name of the person
                    .build());
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(
                            ContactsContract.Data.RAW_CONTACT_ID,   rawContactInsertIndex)
                    .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
                    .withValue(Phone.NUMBER, "9999999999") // Number of the person
                    .withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of mobile number                    
            try
            {
                ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            }
            catch (RemoteException e)
            { 
                // error
            }
            catch (OperationApplicationException e) 
            {
                // error
            }       

Eclipse add Tomcat 7 blank server name

It is a bug in Eclipse. I had exactly the same problem, also on Ubuntu with Eclipse Java EE Juno.

Here is the workaround that worked for me:

  1. Close Eclipse
  2. In {workspace-directory}/.metadata/.plugins/org.eclipse.core.runtime/.settings delete the following two files:
    • org.eclipse.wst.server.core.prefs
    • org.eclipse.jst.server.tomcat.core.prefs
  3. Restart Eclipse

Source: eclipse.org Forum

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

I faced the same issue although i added [System.Web.Mvc.AllowHtml] to the concerning property as described in some answers.

In my case, i have an UnhandledExceptionFilter class that accesses the Request object before MVC validation takes place (and therefore AllowHtml has not effect) and this access raises a [HttpRequestValidationException] A potentially dangerous Request.Form value was detected from the client.

This means, accessing certain properties of a Request object implicitly fires validation (in my case its the Params property).

A solution to prevent validation is documented on MSDN

To disable request validation for a specific field in a request (for example, for an input element or query string value), call the Request.Unvalidated method when you get the item, as shown in the following example

Therefore, if you have code like this

var lParams = aRequestContext.HttpContext.Request.Params;
if (lParams.Count > 0)
{
  ...

change it to

var lUnvalidatedRequest = aRequestContext.HttpContext.Request.Unvalidated;

var lForm = lUnvalidatedRequest.Form;
if (lForm.Count > 0)
{
  ...

or just use the Form property which does not seem to fire validation

var lForm = aRequestContext.HttpContext.Request.Form;
if (lForm.Count > 0)
{
  ...

Visual Studio "Could not copy" .... during build

I experienced the error-messages when attempting to build the primary WinForms (XAF) project. I could only execute the application one time then needed to shutdown the VS2015 IDE and restart before a rebuild could be performed. After some digging in the project's property pages - in the "debug" property page, a check box was selected - Enable the Visual Studio Hosting Process. I unchecked and restarted the IDE, the application is now building without - "unable to copy the {project}.exe" messages.

What is the purpose of the Visual Studio Hosting Process?

IndexError: list index out of range and python

Yes,

You are trying to access an element of the list that does not exist.

MyList = ["item1", "item2"]
print MyList[0] # Will work
print MyList[1] # Will Work
print MyList[2] # Will crash.

Have you got an off-by-one error?

How to create a new variable in a data.frame based on a condition?

If you have a very limited number of levels, you could try converting y into factor and change its levels.

> xy <- data.frame(x = c(1, 2, 4), y = c(1, 4, 5))
> xy$w <- as.factor(xy$y)
> levels(xy$w) <- c("good", "fair", "bad")
> xy
  x y    w
1 1 1 good
2 2 4 fair
3 4 5  bad

How to specify in crontab by what user to run script?

Instead of creating a crontab to run as the root user, create a crontab for the user that you want to run the script. In your case, crontab -u www-data -e will edit the crontab for the www-data user. Just put your full command in there and remove it from the root user's crontab.

_csv.Error: field larger than field limit (131072)

Sometimes, a row contain double quote column. When csv reader try read this row, not understood end of column and fire this raise. Solution is below:

reader = csv.reader(cf, quoting=csv.QUOTE_MINIMAL)

Disable XML validation in Eclipse

You have two options:

  1. Configure Workspace Settings (disable the validation for the current workspace): Go to Window > Preferences > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator

  2. Check enable project specific settings (disable the validation for this project): Right-click on the project, select Properties > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator

Right-click on the project and select Validate to make the errors disappear.

How do I abort/cancel TPL Tasks?

Task are being executed on the ThreadPool (at least, if you are using the default factory), so aborting the thread cannot affect the tasks. For aborting tasks, see Task Cancellation on msdn.

CSS :selected pseudo class similar to :checked, but for <select> elements

Actually you can only style few CSS properties on :modified option elements. color does not work, background-color either, but you can set a background-image.

You can couple this with gradients to do the trick.

_x000D_
_x000D_
option:hover,_x000D_
option:focus,_x000D_
option:active,_x000D_
option:checked {_x000D_
  background: linear-gradient(#5A2569, #5A2569);_x000D_
}
_x000D_
<select>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Works on gecko/webkit.

cannot find zip-align when publishing app

If zipalign command is not found from Command-Line add file path of zipalign to environmental variables. As mentioned above, it's never good to change exe file location.

For Windows users:

Add to User->PATH->"path to zipalign folder"

In my case it path was C:\adt-bundle-windows-x86_64-20140702\sdk\build-tools\android-4.4W. In that folder is zipalign.exe

This link can help you with setting path and understanding it http://www.voidspace.org.uk/python/articles/command_line.shtml#path

Countdown timer using Moment js

The following also requires the moment-duration-format plugin:

$.fn.countdown = function ( options ) {
    var $target = $(this);
    var defaults = {
        seconds: 0,
        format: 'hh:mm:ss',
        stopAtZero: true
    };
    var settings = $.extend(defaults, options);
    var eventTime = Date.now() + ( settings.seconds * 1000 );
    var diffTime = eventTime - Date.now();
    var duration = moment.duration( diffTime, 'milliseconds' );
    var interval = 0;
    $target.text( duration.format( settings.format, { trim: false }) );
    var counter = setInterval(function () {
        $target.text( moment.duration( duration.asSeconds() - ++interval, 'seconds' ).format( settings.format, { trim: false }) );
        if( settings.stopAtZero && interval >= settings.seconds ) clearInterval( counter );
    }, 1000);
};

Usage example:

$('#someDiv').countdown({
    seconds: 30*60,
    format: 'mm:ss'
});

asp.net: Invalid postback or callback argument

I had this same problem with a datalist I"m dynamically binding, adding EnableViewState="false" quieted the error message. I figure if I'm binding programmatically, then the control is being populated on each post back, the view state doesn't have to be maintained if it may or may not change on each call back, that's why I'm dynamically binding it, lol.

How to Detect Browser Window /Tab Close Event?

Yes there is! After a lot of headache i found one solution to this.

Monitor.php

This php file will be monitoring the browser close event. Once the browser is closed the connection_aborted will return 1 hence the loop will break.

<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);

echo connection_aborted();
while(1)
{
echo "Whatever you echo here wont be printed anywhere but it is required in order to work.";
flush();
if(connection_aborted())
{
break;
// Breaks only when browser is closed
}
}

/*
Action you want to take after browser is closed.
Write your code here
*/
?>

Caller.php

This is the file which will call Monitor.php

<?php
Header('Location: monitor.php');
?>

Parent.html

This will be the file which you will actually interact with. On loading this will directly make an AJAX call to Caller.php which will automatically start Monitor.php in background mode.

<script>

 var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            }
         }

   xmlhttp.open("GET", "Caller.php", true);
        xmlhttp.send();   

</script>

So the final flow is Parent.html----->Caller.php----->Monitor.php

Finding the 'type' of an input element

If you want to check the type of input within form, use the following code:

<script>
    function getFind(obj) {
    for (i = 0; i < obj.childNodes.length; i++) {
        if (obj.childNodes[i].tagName == "INPUT") {
            if (obj.childNodes[i].type == "text") {
                alert("this is Text Box.")
            }
            if (obj.childNodes[i].type == "checkbox") {
                alert("this is CheckBox.")
            }
            if (obj.childNodes[i].type == "radio") {
                alert("this is Radio.")
            }
        }
        if (obj.childNodes[i].tagName == "SELECT") {
            alert("this is Select")
        }
    }
}
</script>     

<script>    
    getFind(document.myform);  
</script>

Passing Variable through JavaScript from one html page to another page

Without reading your code but just your scenario, I would solve by using localStorage. Here's an example, I'll use prompt() for short.

On page1:

window.onload = function() {
   var getInput = prompt("Hey type something here: ");
   localStorage.setItem("storageName",getInput);
}

On page2:

window.onload = alert(localStorage.getItem("storageName"));

You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.

How to get the position of a character in Python?

A solution with numpy for quick access to all indexes:

string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')

Greater than and less than in one statement

Nowadays you can use lodash:

var x = 1;
var y = 5;
var z = 3;
_.inRange(z,x,y);
//results true

Add CSS to <head> with JavaScript?

Edit: As Atspulgs comment suggest, you can achieve the same without jQuery using the querySelector:

document.querySelector('head').innerHTML += '<link rel="stylesheet" href="styles.css" type="text/css"/>';

Older answer below.


You could use the jQuery library to select your head element and append HTML to it, in a manner like:

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');

You can find a complete tutorial for this problem here

CSS @font-face not working with Firefox, but working with Chrome and IE

In my case, I sloved problem with inserting font-face style code

<style type="text/css">
@font-face { 
font-family: 'Amazone';font-style: normal; 
/*font-weight:100; -webkit-font-smoothing: antialiased; font-smooth:always;*/ 
src: local('Amazone'), url(font/Amazone.woff) format('woff');} 
</style>

direclty in header on your index.html or php page, in style tag. Works for me!

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

I had a similar situation, but the client config was using a basicHttpBinding. The issue turned out to be that the service was using SOAP 1.2 and you can't specify SOAP 1.2 in a basicHttpBinding. I modified the client config to use a customBinding instead and everything worked. Here are the details of my customBinding for reference. The service I was trying to consume was over HTTPS using UserNameOverTransport.

<customBinding>
    <binding name="myBindingNameHere" sendTimeout="00:03:00">
        <security authenticationMode="UserNameOverTransport" includeTimestamp="false">
            <secureConversationBootstrap />
        </security>
        <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
              messageVersion="Soap12" writeEncoding="utf-8">
            <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                maxBytesPerRead="4096" maxNameTableCharCount="16384" />
        </textMessageEncoding>
        <httpsTransport manualAddressing="false" maxBufferPoolSize="4194304"
              maxReceivedMessageSize="4194304" allowCookies="false" authenticationScheme="Basic"
              bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
              keepAliveEnabled="true" maxBufferSize="4194304" proxyAuthenticationScheme="Anonymous"
              realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
              useDefaultWebProxy="true" requireClientCertificate="false" />
    </binding>
</customBinding>

How to refresh an access form

No, it is like I want to run Form_Load of Form A,if it is possible

-- Varun Mahajan

The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:

Form B:

Sub RunFormALoad()
   Forms!FormA.ToDoOnLoad
End Sub

Form A:

Public Sub Form_Load()
    ToDoOnLoad
End Sub    

Sub ToDoOnLoad()
    txtText = "Hi"
End Sub

how to refresh Select2 dropdown menu after ajax loading different content?

It's common for other components to be listening to the change event, or for custom event handlers to be attached that may have side effects. Select2 does not have a custom event (like select2:update) that can be triggered other than change. You can rely on jQuery's event namespacing to limit the scope to Select2 though by triggering the *change.select2 event.

$('#state').trigger('change.select2'); // Notify only Select2 of changes

Handling null values in Freemarker

Use ?? operator at the end of your <#if> statement.

This example demonstrates how to handle null values for two lists in a Freemaker template.

List of cars:
<#if cars??>
    <#list cars as car>${car.owner};</#list>
</#if>
List of motocycles:
<#if motocycles??>
    <#list motocycles as motocycle>${motocycle.owner};</#list>
</#if>

HTML5 Canvas: Zooming

If you have a source image or canvas element and your 400x400 canvas you want to draw into you can use the drawImage method to achieve zooming.

So for example, the full view might be like this

ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);

And a zoomed view might be like this

ctx.drawImage(img, img.width / 4, img.height / 4, img.width / 2, img.height / 2, 0, 0, canvas.width, canvas.height);

The first parameter to drawImage is the image element or canvas element to draw, the next 4 are the x, y, width and height to sample from the source and the last 4 parameters are the x, y, width and height of the region to draw in the canvas. It will then handle the scaling for you.

You would just need to pick the width and height for the source sample based on the zoom level and the x and y based on where the mouse is clicked minus half the calculated width and height (but you will need to ensure the rectangle isn't out of bounds).

Google Colab: how to read data from my google drive?

from google.colab import drive
drive.mount('/content/drive')

This worked perfect for me I was later able to use the os library to access my files just like how I access them on my PC

Use of String.Format in JavaScript?

Here's a solution that just works with String.prototype:

String.prototype.format = function() {
    var s = this;
    for (var i = 0; i < arguments.length; i++) {       
        var reg = new RegExp("\\{" + i + "\\}", "gm");             
        s = s.replace(reg, arguments[i]);
    }
    return s;
}

Search text in stored procedure in SQL Server

This query is search text in stored procedure from all databases.

DECLARE @T_Find_Text VARCHAR(1000) = 'Foo'

IF OBJECT_ID('tempdb..#T_DBNAME') IS NOT NULL DROP TABLE #T_DBNAME
IF OBJECT_ID('tempdb..#T_PROCEDURE') IS NOT NULL DROP TABLE #T_PROCEDURE

CREATE TABLE #T_DBNAME
(
    IDX int IDENTITY(1,1) PRIMARY KEY 
    , DBName VARCHAR(255)
)

CREATE TABLE #T_PROCEDURE
(
    IDX int IDENTITY(1,1) PRIMARY KEY 
    , DBName VARCHAR(255)
    , Procedure_Name VARCHAR(MAX)
    , Procedure_Description VARCHAR(MAX)
)

INSERT INTO #T_DBNAME (DBName)
SELECT name FROM master.dbo.sysdatabases

DECLARE @T_C_IDX INT = 0
DECLARE @T_C_DBName VARCHAR(255)
DECLARE @T_SQL NVARCHAR(MAX)
DECLARE @T_SQL_PARAM NVARCHAR(MAX) 

SET @T_SQL_PARAM =   
    '   @T_C_DBName VARCHAR(255)
        , @T_Find_Text VARCHAR(255)
    '  


WHILE EXISTS(SELECT TOP 1 IDX FROM #T_DBNAME WHERE IDX > @T_C_IDX ORDER BY IDX ASC)
BEGIN

    SELECT TOP 1 
    @T_C_DBName = DBName 
    FROM #T_DBNAME WHERE IDX > @T_C_IDX ORDER BY IDX ASC

    SET @T_SQL = ''

    SET @T_SQL = @T_SQL + 'INSERT INTO #T_PROCEDURE(DBName, Procedure_Name, Procedure_Description)'
    SET @T_SQL = @T_SQL + 'SELECT SPECIFIC_CATALOG, ROUTINE_NAME, ROUTINE_DEFINITION '
    SET @T_SQL = @T_SQL + 'FROM ' + @T_C_DBName +  '.INFORMATION_SCHEMA.ROUTINES  '
    SET @T_SQL = @T_SQL + 'WHERE ROUTINE_DEFINITION LIKE ''%''+ @T_Find_Text + ''%'' '
    SET @T_SQL = @T_SQL + 'AND ROUTINE_TYPE = ''PROCEDURE'' '

    BEGIN TRY
        EXEC SP_EXECUTESQL  @T_SQL, @T_SQL_PARAM, @T_C_DBName, @T_Find_Text
    END TRY
    BEGIN CATCH
        SELECT @T_C_DBName + ' ERROR'
    END CATCH

    SET @T_C_IDX = @T_C_IDX + 1
END

SELECT IDX, DBName, Procedure_Name FROM #T_PROCEDURE ORDER BY DBName ASC

Chrome Dev Tools - Modify javascript and reload

Great news, the fix is coming in March 2018, see this link: https://developers.google.com/web/updates/2018/01/devtools

"Local Overrides let you make changes in DevTools, and keep those changes across page loads. Previously, any changes that you made in DevTools would be lost when you reloaded the page. Local Overrides work for most file types

How it works:

  • You specify a directory where DevTools should save changes. When you make changes in DevTools, DevTools saves a copy of the modified file to your directory.
  • When you reload the page, DevTools serves the local, modified file, rather than the network resource.

To set up Local Overrides:

  1. Open the Sources panel.
  2. Open the Overrides tab.
  3. Click Setup Overrides.
  4. Select which directory you want to save your changes to.
  5. At the top of your viewport, click Allow to give DevTools read and write access to the directory.
  6. Make your changes."

UPDATE (March 19, 2018): It's live, detailed explanations here: https://developers.google.com/web/updates/2018/01/devtools#overrides

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

I was solving same problem recently. I was designing a write cmdlet for my Subtitle module. I had six different user stories:

  • Subtitle only
  • Subtitle and path (original file name is used)
  • Subtitle and new file name (original path is used)
  • Subtitle and name suffix is used (original path and modified name is used).
  • Subtile, new path and new file name is is used.
  • Subtitle, new path and suffix is used.

I end up in the big frustration because I though that 4 parameters will be enough. Like most of the times, the frustration was pointless because it was my fault. I didn't know enough about parameter sets.

After some research in documentation, I realized where is the problem. With knowledge how the parameter sets should be used, I developed a general and simple approach how to solve this problem. A pencil and a sheet of paper is required but a spreadsheet editor is better:

  1. Write down all intended ways how the cmdlet should be used => user stories.
  2. Keep adding parameters with meaningful names and mark the use of the parameters until you have a unique collection set => no repetitive combination of parameters.
  3. Implement parameter sets into your code.
  4. Prepare tests for all possible user stories.
  5. Run tests (big surprise, right?). IDEs doesn't checks parameter sets collision, tests could save lots of trouble later one.

Example:

Unique parameter binding resolution approach.

The practical example could be seen over here.

BTW: The parameter uniqueness within parameter sets is the reason why the ParameterSetName property doesn't support [String[]]. It doesn't really make any sense.

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

For your example, you'd add this:

interface JQuery{
    printArea():void;
}

Edit: oops, basarat is correct below. I'm not sure why I thought it was compiling but I've updated this answer.

Disable form autofill in Chrome without disabling autocomplete

This might help: https://stackoverflow.com/a/4196465/683114

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
    $(window).load(function(){
        $('input:-webkit-autofill').each(function(){
            var text = $(this).val();
            var name = $(this).attr('name');
            $(this).after(this.outerHTML).remove();
            $('input[name=' + name + ']').val(text);
        });
    });
}

It looks like on load, it finds all inputs with autofill, adds their outerHTML and removes the original, while preserving value and name (easily changed to preserve ID etc)

If this preserves the autofill text, you could just set

var text = "";   /* $(this).val(); */

From the original form where this was posted, it claims to preserve autocomplete. :)

Good luck!

Open S3 object as a string with Boto3

I had a problem to read/parse the object from S3 because of .get() using Python 2.7 inside an AWS Lambda.

I added json to the example to show it became parsable :)

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

NOTE (for python 2.7): My object is all ascii, so I don't need .decode('utf-8')

NOTE (for python 3.6+): We moved to python 3.6 and discovered that read() now returns bytes so if you want to get a string out of it, you must use:

j = json.loads(obj['Body'].read().decode('utf-8'))

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

I have faced this problem in many occassions when I try to start an old rails 2.3.5 project after having worked with rails 3>. In my case to solve the problem, I must do a rubygems update to version 1.4.2, this is:

sudo gem update --system 1.4.2

$ is not a function - jQuery error

Use jQuery for $. I tried and work.

Java Best Practices to Prevent Cross Site Scripting

The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not during processing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib) <c:out> tag or fn:escapeXml function for this. E.g.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>

and

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">

That's it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).

If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. & would become &amp;amp; instead of &amp; so that the enduser would literally see &amp; instead of & in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.

See also:

"The page you are requesting cannot be served because of the extension configuration." error message

Use aspnet_regiis.exe to register version of .NET framework you are using.

This is a common issue and happens when IIS is installed after VS or .NET framework.

Note - for Windows 8/10 users, see the other answer by JohnOpincar below. And also the comment/tip from Kevin Brydon.

mvn command not found in OSX Mavrerick

steps to install maven :

  1. download the maven file from http://maven.apache.org/download.cgi
  2. $tar xvf apache-maven-3.5.4-bin.tar.gz
  3. copy the apache folder to desired place $cp -R apache-maven-3.5.4 /Users/locals
  4. go to apache directory $cd /Users/locals/apache-maven-3.5.4/
  5. create .bash_profile $vim ~/.bash_profile
  6. write these two command : export M2_HOME=/Users/manisha/apache-maven-3.5.4 export PATH=$PATH:$M2_HOME/bin 7 save and quit the vim :wq!
  7. restart the terminal and type mvn -version

Save PHP array to MySQL?

I would suggest using implode/explode with a character that you know will not be contained in any of the individual array items. Then store it in SQL as a string.

If/else else if in Jquery for a condition

See this answer. val() is comparing a string, not a numeric value.

What is the size of a boolean variable in Java?

It's virtual machine dependent.

Java: Difference between the setPreferredSize() and setSize() methods in components

IIRC ...

setSize sets the size of the component.

setPreferredSize sets the preferred size. The Layoutmanager will try to arrange that much space for your component.

It depends on whether you're using a layout manager or not ...

Python 3 - Encode/Decode vs Bytes/Str

To add to Lennart Regebro's answer There is even the third way that can be used:

encoded3 = str.encode(original, 'utf-8')
print(encoded3)

Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.


A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.

Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.

In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".

The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

JQuery - Call the jquery button click event based on name property

$('element[name="element_name"]').click(function(){
    //do stuff
});

in your case:

$('input[name="btnName"]').click(function(){
    //do stuff
});

Android: how to make keyboard enter button say "Search" and handle its click?

In the layout set your input method options to search.

<EditText
    android:imeOptions="actionSearch" 
    android:inputType="text" />

In the java add the editor action listener.

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            performSearch();
            return true;
        }
        return false;
    }
});

How to make an Android Spinner with initial text "Select One"?

This is my way:

List<String> list = new ArrayList<String>();
list.add("string1");
list.add("string2");
list.add("string3");
list.add("[Select one]");
final int listsize = list.size() - 1;
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list) {
 @Override
public int getCount() {
    return(listsize); // Truncate the list
}
};
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(dataAdapter);

mySpinner.setSelection(listsize); // Hidden item to appear in the spinner

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

Problem solved!

I was having all my website set up first in XAMMP, then I had to transfer it to LAMP, in a SUSE installation of LAMP, where I got this error.

The problem is that these parameters in the database.php file should not be initialised. Just leave username and password blank. That's just it.

(My first and lame guess would be that's because of old version of mysql, as built-in installations come with older versions.

In C# check that filename is *possibly* valid (not that it exists)

Think it's too late to answer but... :) in case of path with volume name you could write something like this:

using System;
using System.Linq;
using System.IO;

// ...

var drives = Environment.GetLogicalDrives();
var invalidChars = Regex.Replace(new string(Path.GetInvalidFileNameChars()), "[\\\\/]", "");
var drive = drives.FirstOrDefault(d => filePath.StartsWith(d));
if (drive != null) {
    var fileDirPath = filePath.Substring(drive.Length);
    if (0 < fileDirPath.Length) {
        if (fileDirPath.IndexOfAny(invalidChars.ToCharArray()) == -1) {
            if (Path.Combine(drive, fileDirPath) != drive) {
                // path correct and we can proceed
            }
        }
    }
}

Excel Validation Drop Down list using VBA

Private Sub main()

'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
    .Delete
    'replace "=A1:A6" with the range the data is in.
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
    Operator:=xlBetween, Formula1:="=Sheet1!A1:A6"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With
End Sub

Show current assembly instruction in GDB

You can do

display/i $pc

and every time GDB stops, it will display the disassembly of the next instruction.

GDB-7.0 also supports set disassemble-next-line on, which will disassemble the entire next line, and give you more of the disassembly context.

How do I pass JavaScript variables to PHP?

PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.

If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.

Here's a previous question that you can follow for more information: Ajax Tutorial

Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.

<?php
if(isset($_POST))
{
  print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <input type="text" name="data" value="1" />
  <input type="submit" value="Submit" />
</form>

Clicking submit will submit the page, and print out the submitted data.