Programs & Examples On #Esx

ESX is VMware's bare-metal hypervisor and forms the basis of its enterprise virtualization platform.

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

  1. Find the path from error log and open the file in explorer 2)select the file and right-click -> properties
  2. Then check the 'unblock' option and click on apply enter image description here

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

rbind error: "names do not match previous names"

easy enough to use the unname() function:

data.frame <- unname(data.frame)

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

My solution is as follows:

I didn't find a root folder under C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files.

Google told me that it might be a permission issue against current user, then I found I have a current Identity: IIS APPPOOL in the malfunctioning server where the rest of the server has Current Identity: NT AUTHORITY\NETWORK SERVICE.

Then I changed Current Identity from IIS APPPOOL to NT AUTHORITY\NETWORK SERVICE.

From here, I found that resetting the web app rebuilds the temporary ASP.NET cache, solving the issue.

Using ResourceManager

I went through a similar issue. If you consider your "YeagerTechResources.Resources", it means that your Resources.resx is at the root folder of your project.

Be careful to include the full path eg : "project\subfolder(s)\file[.resx]" to the ResourceManager constructor.

Simultaneously merge multiple data.frames in a list

Here is a generic wrapper which can be used to convert a binary function to multi-parameters function. The benefit of this solution is that it is very generic and can be applied to any binary functions. You just need to do it once and then you can apply it any where.

To demo the idea, I use simple recursion to implement. It can be of course implemented with more elegant way that benefits from R's good support for functional paradigm.

fold_left <- function(f) {
return(function(...) {
    args <- list(...)
    return(function(...){
    iter <- function(result,rest) {
        if (length(rest) == 0) {
            return(result)
        } else {
            return(iter(f(result, rest[[1]], ...), rest[-1]))
        }
    }
    return(iter(args[[1]], args[-1]))
    })
})}

Then you can simply wrap any binary functions with it and call with positional parameters (usually data.frames) in the first parentheses and named parameters in the second parentheses (such as by = or suffix =). If no named parameters, leave second parentheses empty.

merge_all <- fold_left(merge)
merge_all(df1, df2, df3, df4, df5)(by.x = c("var1", "var2"), by.y = c("var1", "var2"))

left_join_all <- fold_left(left_join)
left_join_all(df1, df2, df3, df4, df5)(c("var1", "var2"))
left_join_all(df1, df2, df3, df4, df5)()

ORA-01008: not all variables bound. They are bound

You have two references to the :lot_priprc binding variable -- while it should require you to only set the variable's value once and bind it in both places, I've had problems where this didn't work and had to treat each copy as a different variable. A pain, but it worked.

move a virtual machine from one vCenter to another vCenter

I've figure it out the solution to my problem:

  • Step 1: from within the vSphere client, while connected to vCenter1, select the VM and then from "File" menu select "Export"->"Export OVF Template" (Note: make sure the VM is Powered Off otherwise this feature is not available - it will be gray). This action will allow you to save on your machine/laptop the VM (as an .vmdk, .ovf and a .mf file).
  • Step 2: Connect to the vCenter2 with your vSphere client and from "File" menu select "Deploy OVF Template..." and then select the location where the VM was saved in the previous step.

That was all!
Thanks!

PHP Warning: Invalid argument supplied for foreach()

This means that you are doing a foreach on something that is not an array.

Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.

Then fix the one where it isn't an array.

How to reproduce this error:

<?php
$skipper = "abcd";
foreach ($skipper as $item){       //the warning happens on this line.
    print "ok";
}
?>

Make sure $skipper is an array.

How to reference image resources in XAML?

One of the benefit of using the resource file is accessing the resources by names, so the image can change, the image name can change, as long as the resource is kept up to date correct image will show up.

Here is a cleaner approach to accomplish this: Assuming Resources.resx is in 'UI.Images' namespace, add the namespace reference in your xaml like this:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UI="clr-namespace:UI.Images" 

Set your Image source like this:

<Image Source={Binding {x:Static UI:Resources.Search}} /> where 'Search' is name of the resource.

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

Could not find any resources appropriate for the specified culture or the neutral culture

I found that deleting the designer.cs file, excluding the resx file from the project and then re-including it often fixed this kind of issue, following a namespace refactoring (as per CFinck's answer)

Loop through all the resources in a .resx file

If you want to use LINQ, use resourceSet.OfType<DictionaryEntry>(). Using LINQ allows you, for example, to select resources based on their index (int) instead of key (string):

ResourceSet resourceSet = Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (var entry in resourceSet.OfType<DictionaryEntry>().Select((item, i) => new { Index = i, Key = item.Key, Value = item.Value }))
{
    Console.WriteLine(@"[{0}] {1}", entry.Index, entry.Key);
}

read string from .resx file in C#

Open .resx file and set "Access Modifier" to Public.

var <Variable Name> = Properties.Resources.<Resource Name>

How to use localization in C#

ResourceManager and .resx are bit messy.

You could use Lexical.Localization¹ which allows embedding default value and culture specific values into the code, and be expanded in external localization files for futher cultures (like .json or .resx).

public class MyClass
{
    /// <summary>
    /// Localization root for this class.
    /// </summary>
    static ILine localization = LineRoot.Global.Type<MyClass>();

    /// <summary>
    /// Localization key "Ok" with a default string, and couple of inlined strings for two cultures.
    /// </summary>
    static ILine ok = localization.Key("Success")
            .Text("Success")
            .fi("Onnistui")
            .sv("Det funkar");

    /// <summary>
    /// Localization key "Error" with a default string, and couple of inlined ones for two cultures.
    /// </summary>
    static ILine error = localization.Key("Error")
            .Format("Error (Code=0x{0:X8})")
            .fi("Virhe (Koodi=0x{0:X8})")
            .sv("Sönder (Kod=0x{0:X8})");

    public void DoOk()
    {
        Console.WriteLine( ok );
    }

    public void DoError()
    {
        Console.WriteLine( error.Value(0x100) );
    }
}

¹ (I'm maintainer of that library)

How to force a checkbox and text on the same line?

Try this CSS:

label {
  display: inline-block;
}

XAMPP Apache Webserver localhost not working on MAC OS

If you are also running skype at the same time. It will give you error:

port 80 running a another webserver

First close skype and restart your apache it will work fine.

Redirecting unauthorized controller in ASP.NET MVC

Create a custom authorization attribute based on AuthorizeAttribute and override OnAuthorization to perform the check how you want it done. Normally, AuthorizeAttribute will set the filter result to HttpUnauthorizedResult if the authorization check fails. You could have it set it to a ViewResult (of your Error view) instead.

EDIT: I have a couple of blog posts that go into more detail:

Example:

    [AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
    public class MasterEventAuthorizationAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// The name of the master page or view to use when rendering the view on authorization failure.  Default
        /// is null, indicating to use the master page of the specified view.
        /// </summary>
        public virtual string MasterName { get; set; }

        /// <summary>
        /// The name of the view to render on authorization failure.  Default is "Error".
        /// </summary>
        public virtual string ViewName { get; set; }

        public MasterEventAuthorizationAttribute()
            : base()
        {
            this.ViewName = "Error";
        }

        protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
        {
            validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
        }

        public override void OnAuthorization( AuthorizationContext filterContext )
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException( "filterContext" );
            }

            if (AuthorizeCore( filterContext.HttpContext ))
            {
                SetCachePolicy( filterContext );
            }
            else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                // auth failed, redirect to login page
                filterContext.Result = new HttpUnauthorizedResult();
            }
            else if (filterContext.HttpContext.User.IsInRole( "SuperUser" ))
            {
                // is authenticated and is in the SuperUser role
                SetCachePolicy( filterContext );
            }
            else
            {
                ViewDataDictionary viewData = new ViewDataDictionary();
                viewData.Add( "Message", "You do not have sufficient privileges for this operation." );
                filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData };
            }

        }

        protected void SetCachePolicy( AuthorizationContext filterContext )
        {
            // ** IMPORTANT **
            // Since we're performing authorization at the action level, the authorization code runs
            // after the output caching module. In the worst case this could allow an authorized user
            // to cause the page to be cached, then an unauthorized user would later be served the
            // cached page. We work around this by telling proxies not to cache the sensitive page,
            // then we hook our custom authorization code into the caching mechanism so that we have
            // the final say on whether a page should be served from the cache.
            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
            cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
            cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
        }


    }

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6



Suppress logs using standard python library 'logging'


Place this code on the top of your existing code

import logging
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)

How to fully delete a git repository created with init?

To fully delete the .git repository in your computer (in Windows 8 and above):

  1. The .git repository is normally hidden in windows
  2. So you need to mark the "hidden items" to show the hidden folders
  3. At the top site of you directory you find "view" option
  4. Inside "view" option you find "hidden items" and mark it
  5. Then you see the .git repository then you can delete it

How to import Angular Material in project?

I am using Angular CLI 9.1.4 and all i did was just run:

ng add @angular/material

And all the angular material packages were installed and my package.json file was updated.

This is the easiest way to get that done.

Escape text for HTML

For those in the future looking for a simple way to do this in Razor pages, use the following:

In .cshtml:

@Html.Raw(Html.Encode("<span>blah<span>"))

In .cshtml.cs:

string rawHtml = Html.Raw(Html.Encode("<span>blah<span>"));

how to move elasticsearch data from one server to another

The selected answer makes it sound slightly more complex than it is, the following is what you need (install npm first on your system).

npm install -g elasticdump
elasticdump --input=http://mysrc.com:9200/my_index --output=http://mydest.com:9200/my_index --type=mapping
elasticdump --input=http://mysrc.com:9200/my_index --output=http://mydest.com:9200/my_index --type=data

You can skip the first elasticdump command for subsequent copies if the mappings remain constant.

I have just done a migration from AWS to Qbox.io with the above without any problems.

More details over at:

https://www.npmjs.com/package/elasticdump

Help page (as of Feb 2016) included for completeness:

elasticdump: Import and export tools for elasticsearch

Usage: elasticdump --input SOURCE --output DESTINATION [OPTIONS]

--input
                    Source location (required)
--input-index
                    Source index and type
                    (default: all, example: index/type)
--output
                    Destination location (required)
--output-index
                    Destination index and type
                    (default: all, example: index/type)
--limit
                    How many objects to move in bulk per operation
                    limit is approximate for file streams
                    (default: 100)
--debug
                    Display the elasticsearch commands being used
                    (default: false)
--type
                    What are we exporting?
                    (default: data, options: [data, mapping])
--delete
                    Delete documents one-by-one from the input as they are
                    moved.  Will not delete the source index
                    (default: false)
--searchBody
                    Preform a partial extract based on search results
                    (when ES is the input,
                    (default: '{"query": { "match_all": {} } }'))
--sourceOnly
                    Output only the json contained within the document _source
                    Normal: {"_index":"","_type":"","_id":"", "_source":{SOURCE}}
                    sourceOnly: {SOURCE}
                    (default: false)
--all
                    Load/store documents from ALL indexes
                    (default: false)
--bulk
                    Leverage elasticsearch Bulk API when writing documents
                    (default: false)
--ignore-errors
                    Will continue the read/write loop on write error
                    (default: false)
--scrollTime
                    Time the nodes will hold the requested search in order.
                    (default: 10m)
--maxSockets
                    How many simultaneous HTTP requests can we process make?
                    (default:
                      5 [node <= v0.10.x] /
                      Infinity [node >= v0.11.x] )
--bulk-mode
                    The mode can be index, delete or update.
                    'index': Add or replace documents on the destination index.
                    'delete': Delete documents on destination index.
                    'update': Use 'doc_as_upsert' option with bulk update API to do partial update.
                    (default: index)
--bulk-use-output-index-name
                    Force use of destination index name (the actual output URL)
                    as destination while bulk writing to ES. Allows
                    leveraging Bulk API copying data inside the same
                    elasticsearch instance.
                    (default: false)
--timeout
                    Integer containing the number of milliseconds to wait for
                    a request to respond before aborting the request. Passed
                    directly to the request library. If used in bulk writing,
                    it will result in the entire batch not being written.
                    Mostly used when you don't care too much if you lose some
                    data when importing but rather have speed.
--skip
                    Integer containing the number of rows you wish to skip
                    ahead from the input transport.  When importing a large
                    index, things can go wrong, be it connectivity, crashes,
                    someone forgetting to `screen`, etc.  This allows you
                    to start the dump again from the last known line written
                    (as logged by the `offset` in the output).  Please be
                    advised that since no sorting is specified when the
                    dump is initially created, there's no real way to
                    guarantee that the skipped rows have already been
                    written/parsed.  This is more of an option for when
                    you want to get most data as possible in the index
                    without concern for losing some rows in the process,
                    similar to the `timeout` option.
--inputTransport
                    Provide a custom js file to us as the input transport
--outputTransport
                    Provide a custom js file to us as the output transport
--toLog
                    When using a custom outputTransport, should log lines
                    be appended to the output stream?
                    (default: true, except for `$`)
--help
                    This page

Examples:

# Copy an index from production to staging with mappings:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=mapping
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=data

# Backup index data to a file:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=/data/my_index_mapping.json \
  --type=mapping
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=/data/my_index.json \
  --type=data

# Backup and index to a gzip using stdout:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=$ \
  | gzip > /data/my_index.json.gz

# Backup ALL indices, then use Bulk API to populate another ES cluster:
elasticdump \
  --all=true \
  --input=http://production-a.es.com:9200/ \
  --output=/data/production.json
elasticdump \
  --bulk=true \
  --input=/data/production.json \
  --output=http://production-b.es.com:9200/

# Backup the results of a query to a file
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=query.json \
  --searchBody '{"query":{"term":{"username": "admin"}}}'

------------------------------------------------------------------------------
Learn more @ https://github.com/taskrabbit/elasticsearch-dump`enter code here`

Create autoincrement key in Java DB using NetBeans IDE

I couldn't get the accepted answer to work using the Netbeans IDE "Create Table" GUI, and I'm on Netbeans 8.2. To get it to working, create the id column with the following options e.g.

enter image description here

and then use 'New Entity Classes from Database' option to generate the entity for the table (I created a simple table called PERSON with an ID column created exactly as above and a NAME column which is simple varchar(255) column). These generated entities leave it to the user to add the auto generated id mechanism.

GENERATION.AUTO seems to try and use sequences which Derby doesn't seem to like (error stating failed to generate sequence/sequence does not exist), GENERATION.SEQUENCE therefore doesn't work either, GENERATION.IDENTITY doesn't work (get error stating ID is null), so that leaves GENERATION.TABLE.

Set your persistence unit's 'Table Generation Strategy' button to Create. This will create tables that don't exist in the DB when your jar is run (loaded?) i.e. the table your PU needs to create in order to store ID increments. In your entity replace the generated annotations above your id field with the following...

enter image description here

I also created a controller for my entity class using 'JPA Controller Classes from Entity Classes' option. I then create a simple main class to test the id was auto generated i.e.

enter image description here

The result is that the PERSON_ID_TABLE is generated correctly and my PERSON table has two PERSON entries in it with correct, auto generated ids.

Preserve line breaks in angularjs

It's so simple with CSS (it works, I swear).

.angular-with-newlines {
  white-space: pre;
}
  • Look ma! No extra HTML tags!

What are the differences between numpy arrays and matrices? Which one should I use?

Scipy.org recommends that you use arrays:

*'array' or 'matrix'? Which should I use? - Short answer

Use arrays.

  • They are the standard vector/matrix/tensor type of numpy. Many numpy function return arrays, not matrices.

  • There is a clear distinction between element-wise operations and linear algebra operations.

  • You can have standard vectors or row/column vectors if you like.

The only disadvantage of using the array type is that you will have to use dot instead of * to multiply (reduce) two tensors (scalar product, matrix vector multiplication etc.).

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

Just rename the command or file name ln -s /usr/bin/nodejs /usr/bin/node by this command

Getting the class of the element that fired an event using JQuery

If you are using jQuery 1.7:

alert($(this).prop("class"));

or:

alert($(event.target).prop("class"));

Can anyone recommend a simple Java web-app framework?

Check out WaveMaker for building a quick, simple webapp. They have a browser based drag-and-drop designer for Dojo/JavaScript widgets, and the backend is 100% Java.

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

Android - border for button

Please look here about creating a shape drawable http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

Once you have done this, in the XML for your button set android:background="@drawable/your_button_border"

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

Creating custom function in React component

Another way:

export default class Archive extends React.Component { 

  saySomething = (something) => {
    console.log(something);
  }

  handleClick = (e) => {
    this.saySomething("element clicked");
  }

  componentDidMount() {
    this.saySomething("component did mount");
  }

  render() {
    return <button onClick={this.handleClick} value="Click me" />;
  }
}

In this format you don't need to use bind

How to delete items from a dictionary while iterating over it?

There is a way that may be suitable if the items you want to delete are always at the "beginning" of the dict iteration

while mydict:
    key, value = next(iter(mydict.items()))
    if should_delete(key, value):
       del mydict[key]
    else:
       break

The "beginning" is only guaranteed to be consistent for certain Python versions/implementations. For example from What’s New In Python 3.7

the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.

This way avoids a copy of the dict that a lot of the other answers suggest, at least in Python 3.

How to sort ArrayList<Long> in decreasing order?

You can use the following code which is given below;

Collections.sort(list, Collections.reverseOrder());

or if you are going to use custom comparator you can use as it is given below

Collections.sort(list, Collections.reverseOrder(new CustomComparator());

Where CustomComparator is a comparator class that compares the object which is present in the list.

How to wait for the 'end' of 'resize' event and only then perform an action?

This is what I use for delaying repeated actions, it can be called in multiple places in your code:

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

Usage:

$(window).resize(function () { 
   debounce(function() {
          //...
    }, 500);
});

How do I remove packages installed with Python's easy_install?

To list installed Python packages, you can use yolk -l. You'll need to use easy_install yolk first though.

PHP not displaying errors even though display_errors = On

Although this is old post... i had similar situation that gave me headache. Finally, i figured that i was including sub pages in index.php with "@include ..." "@" hides all errors even if display_errors is ON

SQL WHERE ID IN (id1, id2, ..., idn)

In most database systems, IN (val1, val2, …) and a series of OR are optimized to the same plan.

The third way would be importing the list of values into a temporary table and join it which is more efficient in most systems, if there are lots of values.

You may want to read this articles:

CXF: No message body writer found for class - automatically mapping non-simple resources

In my scenario, i faced similar error, when the rest url without port number is not properly configured for load balancing. I verified the rest url with portnumber and this issue was not occurring. so we had to update the load balancing configuration to resolve this issue.

How to show x and y axes in a MATLAB graph?

Easiest solution:

plot([0,0],[0.0], xData, yData);

This creates an invisible line between the points [0,0] to [0,0] and since Matlab wants to include these points it will shows the axis.

/bin/sh: pushd: not found

sudo dpkg-reconfigure dash 

Then select no.

Creating a system overlay window (always on top)

I'm one of the developers of the Tooleap SDK. We also provide a way for developers to display always on top windows and buttons, and and we have dealt with a similar situation.

One problem the answers here haven't addressed is that of the Android "Secured Buttons".

Secured buttons have the filterTouchesWhenObscured property which means they can't be interacted with, if placed under a window, even if that window does not receive any touches. Quoting the Android documentation:

Specifies whether to filter touches when the view's window is obscured by another visible window. When set to true, the view will not receive touches whenever a toast, dialog or other window appears above the view's window. Refer to the {@link android.view.View} security documentation for more details.

An example of such a button is the install button when you try to install third party apks. Any app can display such a button if adding to the view layout the following line:

android:filterTouchesWhenObscured="true"

If you display an always-on-top window over a "Secured Button", so all the secured button parts that are covered by an overlay will not handle any touches, even if that overlay is not clickable. So if you are planing to display such a window, you should provide a way for the user to move it or dismiss it. And if a part of your overlay is transparent, take into account that your user might be confused why is a certain button in the underlying app is not working for him suddenly.

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

How to clear gradle cache?

My ~/.gradle/caches/ folder was using 14G.

After using the following solution, it went from 14G to 1.7G.

$ rm -rf ~/.gradle/caches/transforms-*
$ rm -rf ~/.gradle/caches/build-cache-*

Bonus

This command shows you in detail the used cache space

$ sudo du -ah --max-depth = 1 ~/.gradle/caches/ | sort -hr

Get final URL after curl is redirected

You can do this with wget usually. wget --content-disposition "url" additionally if you add -O /dev/null you will not be actually saving the file.

wget -O /dev/null --content-disposition example.com

How to make child element higher z-index than parent?

Use non-static position along with greater z-index in child element:

.parent {
    position: absolute
    z-index: 100;
}

.child {
    position: relative;
    z-index: 101;
}

Python Pandas - Missing required dependencies ['numpy'] 1

Try:

    sudo apt-get install libatlas-base-dev

It should work now.

Else, try uninstall and reinstall numpy and pandas.

How to simulate a mouse click using JavaScript?

Here's a pure JavaScript function which will simulate a click (or any mouse event) on a target element:

function simulatedClick(target, options) {

  var event = target.ownerDocument.createEvent('MouseEvents'),
      options = options || {},
      opts = { // These are the default values, set up for un-modified left clicks
        type: 'click',
        canBubble: true,
        cancelable: true,
        view: target.ownerDocument.defaultView,
        detail: 1,
        screenX: 0, //The coordinates within the entire page
        screenY: 0,
        clientX: 0, //The coordinates within the viewport
        clientY: 0,
        ctrlKey: false,
        altKey: false,
        shiftKey: false,
        metaKey: false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
        button: 0, //0 = left, 1 = middle, 2 = right
        relatedTarget: null,
      };

  //Merge the options with the defaults
  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      opts[key] = options[key];
    }
  }

  //Pass in the options
  event.initMouseEvent(
      opts.type,
      opts.canBubble,
      opts.cancelable,
      opts.view,
      opts.detail,
      opts.screenX,
      opts.screenY,
      opts.clientX,
      opts.clientY,
      opts.ctrlKey,
      opts.altKey,
      opts.shiftKey,
      opts.metaKey,
      opts.button,
      opts.relatedTarget
  );

  //Fire the event
  target.dispatchEvent(event);
}

Here's a working example: http://www.spookandpuff.com/examples/clickSimulation.html

You can simulate a click on any element in the DOM. Something like simulatedClick(document.getElementById('yourButtonId')) would work.

You can pass in an object into options to override the defaults (to simulate which mouse button you want, whether Shift/Alt/Ctrl are held, etc. The options it accepts are based on the MouseEvents API.

I've tested in Firefox, Safari and Chrome. Internet Explorer might need special treatment, I'm not sure.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

You can use this, it works fine:

<input type="date" class="form1"  
  value="{{date | date:MM/dd/yyyy}}"
  ng-model="date" 
  name="id" 
  validatedateformat 
  data-date-format="mm/dd/yyyy"
  maxlength="10" 
  id="id" 
  calendar 
  maxdate="todays"
  ng-click="openCalendar('id')">
    <span class="input-group-addon">
      <span class="glyphicon glyphicon-calendar" ng-click="openCalendar('id')"></span>
    </span>
</input>

How to generate random number in Bash?

Try this from your shell:

$ od -A n -t d -N 1 /dev/urandom

Here, -t d specifies that the output format should be signed decimal; -N 1 says to read one byte from /dev/urandom.

Console output in a Qt GUI app?

First of all, why would you need to output to console in a release mode build? Nobody will think to look there when there's a gui...

Second, qDebug is fancy :)

Third, you can try adding console to your .pro's CONFIG, it might work.

Can I dynamically add HTML within a div tag from C# on load event?

You can add a div with runat="server" to the page:

<div runat="server" id="myDiv">
</div>

and then set its InnerHtml property from the code-behind:

myDiv.InnerHtml = "your html here";

If you want to modify the DIV's contents on the client side, then you can use javascript code similar to this:

<script type="text/javascript">
    Sys.Application.add_load(MyLoad);
    function MyLoad(sender) {
        $get('<%= div.ClientID %>').innerHTML += " - text added on client";
    }
</script>

How to redirect DNS to different ports

You can use SRV records:

_service._proto.name. TTL class SRV priority weight port target.

Service: the symbolic name of the desired service.

Proto: the transport protocol of the desired service; this is usually either TCP or UDP.

Name: the domain name for which this record is valid, ending in a dot.

TTL: standard DNS time to live field.

Class: standard DNS class field (this is always IN).

Priority: the priority of the target host, lower value means more preferred.

Weight: A relative weight for records with the same priority.

Port: the TCP or UDP port on which the service is to be found.

Target: the canonical hostname of the machine providing the service, ending in a dot.

Example:

_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.

So what I think you're looking for is to add something like this to your DNS hosts file:

_sip._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25566 tekkit.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25567 pvp.arboristal.com.

On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:

<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>

Passing data from controller to view in Laravel

$books[] = [
            'title' => 'Mytitle',
            'author' => 'MyAuthor,
            
        ];

//pass data to other view
return view('myView.blade.php')->with('books');
or
return view('myView.blade.php','books');
or
return view('myView.blade.php',compact('books'));

----------------------------------------------------


//to use this on myView.blade.php
<script>
    myVariable = {!! json_encode($books) !!};
    console.log(myVariable);
</script>

How to print HTML content on click of a button, but not the page?

Here is a pure css version

_x000D_
_x000D_
.example-print {_x000D_
    display: none;_x000D_
}_x000D_
@media print {_x000D_
   .example-screen {_x000D_
       display: none;_x000D_
    }_x000D_
    .example-print {_x000D_
       display: block;_x000D_
    }_x000D_
}
_x000D_
<div class="example-screen">You only see me in the browser</div>_x000D_
_x000D_
<div class="example-print">You only see me in the print</div>
_x000D_
_x000D_
_x000D_

How to check if an array is empty?

you may use yourArray.length to findout number of elements in an array.

Make sure yourArray is not null before doing yourArray.length, otherwise you will end up with NullPointerException.

MySql server startup error 'The server quit without updating PID file '

I had the same problem. The reason is quite simple. I installed 2 mysql server. One from Mac Port, the other from downloaded package. So I just follow the instruction here and uninstalled the one from package. How do you uninstall MySQL from Mac OS X? After that, mysql is working well.

How to check if a date is in a given range?

Use the DateTime class if you have PHP 5.3+. Easier to use, better functionality.

DateTime internally supports timezones, with the other solutions is up to you to handle that.

<?php    
/**
 * @param DateTime $date Date that is to be checked if it falls between $startDate and $endDate
 * @param DateTime $startDate Date should be after this date to return true
 * @param DateTime $endDate Date should be before this date to return true
 * return bool
 */
function isDateBetweenDates(DateTime $date, DateTime $startDate, DateTime $endDate) {
    return $date > $startDate && $date < $endDate;
}

$fromUser = new DateTime("2012-03-01");
$startDate = new DateTime("2012-02-01 00:00:00");
$endDate = new DateTime("2012-04-30 23:59:59");

echo isDateBetweenDates($fromUser, $startDate, $endDate);

iterating through json object javascript

Here is my recursive approach:

function visit(object) {
    if (isIterable(object)) {
        forEachIn(object, function (accessor, child) {
            visit(child);
        });
    }
    else {
        var value = object;
        console.log(value);
    }
}

function forEachIn(iterable, functionRef) {
    for (var accessor in iterable) {
        functionRef(accessor, iterable[accessor]);
    }
}

function isIterable(element) {
    return isArray(element) || isObject(element);
}

function isArray(element) {
    return element.constructor == Array;
}

function isObject(element) {
    return element.constructor == Object;
}

Control the size of points in an R scatterplot?

Try the cex argument:

?par

  • cex
    A numerical value giving the amount by which plotting text and symbols should be magnified relative to the default. Note that some graphics functions such as plot.default have an argument of this name which multiplies this graphical parameter, and some functions such as points accept a vector of values which are recycled. Other uses will take just the first value if a vector of length greater than one is supplied.

How to add a ListView to a Column in Flutter?

Expanded Widget increases it’s size as much as it can with the space available Since ListView essentially has an infinite height it will cause an error.

 Column(
  children: <Widget>[
    Flexible(
      child: ListView(...),
    )
  ],
)

Here we should use Flexible widget as it will only take the space it required as Expanded take full screen even if there are not enough widgets to render on full screen.

TypeScript function overloading

You can declare an overloaded function by declaring the function as having a type which has multiple invocation signatures:

interface IFoo
{
    bar: {
        (s: string): number;
        (n: number): string;
    }
}

Then the following:

var foo1: IFoo = ...;

var n: number = foo1.bar('baz');     // OK
var s: string = foo1.bar(123);       // OK
var a: number[] = foo1.bar([1,2,3]); // ERROR

The actual definition of the function must be singular and perform the appropriate dispatching internally on its arguments.

For example, using a class (which could implement IFoo, but doesn't have to):

class Foo
{
    public bar(s: string): number;
    public bar(n: number): string;
    public bar(arg: any): any 
    {
        if (typeof(arg) === 'number')
            return arg.toString();
        if (typeof(arg) === 'string')
            return arg.length;
    }
}

What's interesting here is that the any form is hidden by the more specifically typed overrides.

var foo2: new Foo();

var n: number = foo2.bar('baz');     // OK
var s: string = foo2.bar(123);       // OK
var a: number[] = foo2.bar([1,2,3]); // ERROR

current/duration time of html5 video?

HTML:

<video
    id="video-active"
    class="video-active"
    width="640"
    height="390"
    controls="controls">
    <source src="myvideo.mp4" type="video/mp4">
</video>
<div id="current">0:00</div>
<div id="duration">0:00</div>

JavaScript:

$(document).ready(function(){
  $("#video-active").on(
    "timeupdate", 
    function(event){
      onTrackedVideoFrame(this.currentTime, this.duration);
    });
});

function onTrackedVideoFrame(currentTime, duration){
    $("#current").text(currentTime); //Change #current to currentTime
    $("#duration").text(duration)
}

Notes:

Every 15 to 250ms, or whenever the MediaController's media controller position changes, whichever happens least often, the user agent must queue a task to fire a simple event named timeupdate at the MediaController.

http://www.w3.org/TR/html5/embedded-content-0.html#media-controller-position

Google Maps how to Show city or an Area outline

so I have a solution that isn't perfect but it worked for me. Use the polygon example from Google, and use the pinpoint on Google Maps to get lat & long locations.

Calgary pinpoint

I used what I call "ocular copy & paste" where you look at the screen and then write in the numbers you want ;-)

<style>
  #map {
    height: 500px;
  }
</style>
<script>

// This example creates a simple polygon representing the host city of the 
// Greatest Outdoor Show On Earth.

 function initMap() {
   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 9,
      center: {lat: 51.039, lng: -114.204},
      mapTypeId: 'terrain'
    });

    // Define the LatLng coordinates for the polygon's path.
    var triangleCoords = [
      {lat: 51.183, lng: -114.234},
      {lat: 51.154, lng: -114.235},
      {lat: 51.156, lng: -114.261},
      {lat: 51.104, lng: -114.259},
      {lat: 51.106, lng: -114.261},
      {lat: 51.102, lng: -114.272},
      {lat: 51.081, lng: -114.271},
      {lat: 51.081, lng: -114.234},
      {lat: 51.009, lng: -114.236},
      {lat: 51.008, lng: -114.141},
      {lat: 50.995, lng: -114.142},
      {lat: 50.998, lng: -114.160},
      {lat: 50.984, lng: -114.163},
      {lat: 50.987, lng: -114.141},
      {lat: 50.979, lng: -114.141},
      {lat: 50.921, lng: -114.141},
      {lat: 50.921, lng: -114.210},
      {lat: 50.893, lng: -114.210},
      {lat: 50.892, lng: -114.140},
      {lat: 50.888, lng: -114.139},
      {lat: 50.878, lng: -114.094},
      {lat: 50.878, lng: -113.994},
      {lat: 50.840, lng: -113.954},
      {lat: 50.854, lng: -113.905},
      {lat: 50.922, lng: -113.906},
      {lat: 50.935, lng: -113.877},
      {lat: 50.943, lng: -113.877},
      {lat: 50.955, lng: -113.912},
      {lat: 51.183, lng: -113.910}
    ];

    // Construct the polygon.
    var bermudaTriangle = new google.maps.Polygon({
      paths: triangleCoords,
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    });
    bermudaTriangle.setMap(map);
  }
</script>


<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap">
</script>

This gets you the outline for Calgary. I've attached an image here.

How to remove title bar from the android activity?

You just add following lines of code in style.xml file

<style name="AppTheme.NoTitleBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>

change apptheme in AndroidManifest.xml file

android:theme="@style/AppTheme.NoTitleBar"

What's the difference between a Python module and a Python package?

Any Python file is a module, its name being the file's base name without the .py extension. A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file.

The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type module. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules. As an example, consider the xml package in the Python standard library: its xml directory contains an __init__.py file and four sub-directories; the sub-directory etree contains an __init__.py file and, among others, an ElementTree.py file. See what happens when you try to interactively import package/modules:

>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>

In Python there also are built-in modules, such as sys, that are written in C, but I don't think you meant to consider those in your question.

How to set breakpoints in inline Javascript in Google Chrome?

My situation and what I did to fix it:
I have a javascript file included on an HTML page as follows:
Page Name: test.html

<!DOCTYPE html>
<html>
    <head>
        <script src="scripts/common.js"></script>
        <title>Test debugging JS in Chrome</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>
         <script type="text/javascript">
            document.write("something");
         </script>

        </div>
     </body>
</html>

Now entering the Javascript Debugger in Chrome, I click the Scripts Tab, and drop down the list as shown above. I can clearly see scripts/common.js however I could NOT see the current html page test.html in the drop down, therefore I could not debug the embedded javascript:

<script type="text/javascript">
  document.write("something");
</script>

That was perplexing. However, when I removed the obsolete type="text/javascript" from the embedded script:

<script>
  document.write("something");
</script>

..and refreshed / reloaded the page, voila, it appeared in the drop down list, and all was well again.
I hope this is helpful to anyone who is having issues debugging embedded javascript on an html page.

Measuring execution time of a function in C++

You can have a simple class which can be used for this kind of measurements.

class duration_printer {
public:
    duration_printer() : __start(std::chrono::high_resolution_clock::now()) {}
    ~duration_printer() {
        using namespace std::chrono;
        high_resolution_clock::time_point end = high_resolution_clock::now();
        duration<double> dur = duration_cast<duration<double>>(end - __start);
        std::cout << dur.count() << " seconds" << std::endl;
    }
private:
    std::chrono::high_resolution_clock::time_point __start;
};

The only thing is needed to do is to create an object in your function at the beginning of that function

void veryLongExecutingFunction() {
    duration_calculator dc;
    for(int i = 0; i < 100000; ++i) std::cout << "Hello world" << std::endl;
}

int main() {
    veryLongExecutingFunction();
    return 0;
}

and that's it. The class can be modified to fit your requirements.

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.

Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.

Try something like this:

var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

Android Percentage Layout Height

Just as you said, I'd recommend weights. Percentages would be incredibly useful (don't know why they aren't supported), but one way you could do it is like so:

<LinearLayout
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    >
    <LinearLayout
        android:layout_height="0dp"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        >
    </LinearLayout>
    <View
        android:layout_height="0dp"
        android:layout_width="fill_parent"
        android:layout_weight="1"
    />
</LinearLayout>

The takeaway being that you have an empty View that will take up the remaining space. Not ideal, but it does what you're looking for.

How to convert an int value to string in Go?

fmt.Sprintf, strconv.Itoa and strconv.FormatInt will do the job. But Sprintf will use the package reflect, and it will allocate one more object, so it's not an efficient choice.

enter image description here

Difference between File.separator and slash in paths

With the Java libraries for dealing with files, you can safely use / (slash, not backslash) on all platforms. The library code handles translating things into platform-specific paths internally.

You might want to use File.separator in UI, however, because it's best to show people what will make sense in their OS, rather than what makes sense to Java.

Update: I have not been able, in five minutes of searching, to find the "you can always use a slash" behavior documented. Now, I'm sure I've seen it documented, but in the absense of finding an official reference (because my memory isn't perfect), I'd stick with using File.separator because you know that will work.

preg_match in JavaScript?

var myregexp = /\[(\d+)\]\[(\d+)\]/;
var match = myregexp.exec(text);
if (match != null) {
    var productId = match[1];
    var shopId = match[2];
} else {
    // no match
}

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

Maven skip tests

I had some inter-dependency with the tests in order to build the package.

The following command manage to override the need for the test artifact in order to complete the goal:

mvn -DskipTests=true  package

How to solve static declaration follows non-static declaration in GCC C code?

Try -Wno-traditional.

But better, add declarations for your static functions:

static void foo (void);

// ... somewhere in code
    foo ();

static void foo ()
{
    // do sth
}

@Autowired - No qualifying bean of type found for dependency

My guess is that here

<context:component-scan base-package="pl.com.radzikowski.webmail" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

all annotations are first disabled by use-default-filters="false" and then only @Controller annotation enabled. Thus, your @Component annotation is not enabled.

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

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

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

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

#include<iostream>

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

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

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

Create the binding file binding.gyp:

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

Run the following commands:

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

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

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

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

How to list processes attached to a shared memory segment in linux?

I don't think you can do this with the standard tools. You can use ipcs -mp to get the process ID of the last process to attach/detach but I'm not aware of how to get all attached processes with ipcs.

With a two-process-attached segment, assuming they both stayed attached, you can possibly figure out from the creator PID cpid and last-attached PID lpid which are the two processes but that won't scale to more than two processes so its usefulness is limited.

The cat /proc/sysvipc/shm method seems similarly limited but I believe there's a way to do it with other parts of the /proc filesystem, as shown below:

When I do a grep on the procfs maps for all processes, I get entries containing lines for the cpid and lpid processes.

For example, I get the following shared memory segment from ipcs -m:

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0x00000000 123456     pax        600        1024       2          dest

and, from ipcs -mp, the cpid is 3956 and the lpid is 9999 for that given shared memory segment (123456).

Then, with the command grep 123456 /proc/*/maps, I see:

/proc/3956/maps: blah blah blah 123456 /SYSV000000 (deleted)
/proc/9999/maps: blah blah blah 123456 /SYSV000000 (deleted)

So there is a way to get the processes that attached to it. I'm pretty certain that the dest status and (deleted) indicator are because the creator has marked the segment for destruction once the final detach occurs, not that it's already been destroyed.

So, by scanning of the /proc/*/maps "files", you should be able to discover which PIDs are currently attached to a given segment.

Android TextView padding between lines

This supplemental answer shows the effect of changing the line spacing.

enter image description here

You can set the multiplier and/or extra spacing with

textView.setLineSpacing(float add, float mult)

Or you can get the values with

int lineHeight = textView.getLineHeight();
float add = tvSampleText.getLineSpacingExtra();          // API 16+
float mult = tvSampleText.getLineSpacingMultiplier();    // API 16+

where the formula is

lineHeight = fontMetricsLineHeight * mult + add

The default multiplier is 1 and the default extra spacing is 0.

What's the right way to decode a string that has special HTML entities in it?

Don’t use the DOM to do this. Using the DOM to decode HTML entities (as suggested in the currently accepted answer) leads to differences in cross-browser results.

For a robust & deterministic solution that decodes character references according to the algorithm in the HTML Standard, use the he library. From its README:

he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine. An online demo is available.

Here’s how you’d use it:

he.decode("We&#39;re unable to complete your request at this time.");
? "We're unable to complete your request at this time."

Disclaimer: I'm the author of the he library.

See this Stack Overflow answer for some more info.

adb is not recognized as internal or external command on windows

If you go to your android-sdk/tools folder I think you'll find a message :

The adb tool has moved to platform-tools/

If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"

Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

So you should also add C:/android-sdk/platform-tools to you environment path. Also after you modify the PATH variable make sure that you start a new CommandPrompt window.

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

I think I encountered the same problem as you. I addressed this problem with the following steps:

1) Go to Google Developers Console

2) Set JavaScript origins:

3) Set Redirect URIs:

Javascript-Setting background image of a DIV via a function and function parameter

You need to concatenate your string.

document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';

The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.

I would even suggest creating the string separate:

function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
    var urlString = 'url(buttons/' + imagePrefix + '.png)';
    document.getElementById(tabName).style.backgroundImage =  urlString;
}

As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html

How to outline text in HTML / CSS

Try this:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
 font: Tahoma, Geneva, sans-serif;_x000D_
 font-size: 64px;_x000D_
    color: white;_x000D_
    text-shadow:_x000D_
    /* Outline */_x000D_
    -1px -1px 0 #000000,_x000D_
    1px -1px 0 #000000,_x000D_
    -1px 1px 0 #000000,_x000D_
    1px 1px 0 #000000,  _x000D_
    -2px 0 0 #000000,_x000D_
    2px 0 0 #000000,_x000D_
    0 2px 0 #000000,_x000D_
    0 -2px 0 #000000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

...and you might also want to do this too:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
 font: Tahoma, Geneva, sans-serif;_x000D_
 font-size: 64px;_x000D_
    color: white;_x000D_
    text-shadow:_x000D_
    /* Outline 1 */_x000D_
    -1px -1px 0 #000000,_x000D_
    1px -1px 0 #000000,_x000D_
    -1px 1px 0 #000000,_x000D_
    1px 1px 0 #000000,  _x000D_
    -2px 0 0 #000000,_x000D_
    2px 0 0 #000000,_x000D_
    0 2px 0 #000000,_x000D_
    0 -2px 0 #000000, _x000D_
    /* Outline 2 */_x000D_
    -2px -2px 0 #ff0000,_x000D_
    2px -2px 0 #ff0000,_x000D_
    -2px 2px 0 #ff0000,_x000D_
    2px 2px 0 #ff0000,  _x000D_
    -3px 0 0 #ff0000,_x000D_
    3px 0 0 #ff0000,_x000D_
    0 3px 0 #ff0000,_x000D_
    0 -3px 0 #ff0000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

You can do as many Outlines as you like, and there's enough scope for coming up with lots of creative ideas.

Have fun!

jQuery add text to span within a div

Careful - append() will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>').

Use text() to replace element content with text, or append(document.createTextNode(x)) to append a text node.

How to send json data in the Http request using NSURLRequest

You can try this code for send json string

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:@"www.test.com?xyz.php&param=%@",jsonString];

dyld: Library not loaded ... Reason: Image not found

In our case, it's an iOS app, built on Xcode 11.5, using cocoapods (and cocoapods-binary if you will).

We were seeing this crash:

dyld: Library not loaded: @rpath/PINOperation.framework/PINOperation
  Referenced from: /private/var/containers/Bundle/Application/4C5F5E4C-8B71-4351-A0AB-C20333544569/Tellus.app/Frameworks/PINRemoteImage.framework/PINRemoteImage
  Reason: image not found

Turns out that I had to delete the pods cache and re-run pod install, so Xcode would point this diff:

enter image description here

Getting index value on razor foreach

In case you want to count the references from your model( ie: Client has Address as reference so you wanna count how many address would exists for a client) in a foreach loop at your view such as:

 @foreach (var item in Model)
                        {
                            <tr>
                                <td>
                                    @Html.DisplayFor(modelItem => item.DtCadastro)
                                </td>

                                <td style="width:50%">
                                    @Html.DisplayFor(modelItem => item.DsLembrete)
                                </td>
                                <td>
                                    @Html.DisplayFor(modelItem => item.DtLembrete)
                                </td>
                                <td>
                                    @{ 
                                        var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();
                                    }
                                    <button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
                                    <button class="btn-link associar" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Create/@item.IdLembrete"><i class="fas fa-plus"></i></button>
                                </td>
                                <td class="text-right">
                                    <button class="btn-link delete" data-id="@item.IdLembrete" data-path="/Lembretes/Delete/@item.IdLembrete">Excluir</button>
                                </td>
                            </tr>
                        }

do as coded:

@{ var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();}

and use it like this:

<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>

ps: don't forget to add INCLUDE to that reference at you DbContext inside, for example, your Index action controller, in case this is an IEnumerable model.

Go doing a GET request and building the Querystring

As a commenter mentioned you can get Values from net/url which has an Encode method. You could do something like this (req.URL.Query() returns the existing url.Values)

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
)

func main() {
    req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")
    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popular?another_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

http://play.golang.org/p/L5XCrw9VIG

How to query DATETIME field using only date in Microsoft SQL Server?

select * from invoice where TRANS_DATE_D>= to_date  ('20170831115959','YYYYMMDDHH24MISS')
and TRANS_DATE_D<= to_date  ('20171031115959','YYYYMMDDHH24MISS');

How to get EditText value and display it on screen through TextView?

First get the text from edit text view

edittext.getText().toString()

and Store the obtained text in a string, say value.

value = edittext.getText().toString()

Then set value as the text for textview.

textview.setText(value)

How to split a string of space separated numbers into integers?

Here is my answer for python 3.

some_string = "2 3 8 61 "

list(map(int, some_string.strip().split()))

Deserializing a JSON file with JavaScriptSerializer()

For .Net 4+:

string s = "{ \"user\" : {    \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}}";

var serializer = new JavaScriptSerializer();
dynamic usr = serializer.DeserializeObject(s);
var UserId = usr["user"]["id"];

For .Net 2/3.5: This code should work on JSON with 1 level

samplejson.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
var UserId = result["id"];
 %>
 <%=UserId %>

And for a 2 level JSON:

sample2.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"user\" : {    \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
Dictionary<string, object> usr = (result["user"] as Dictionary<string, object>);
var UserId = usr["id"];
 %>
 <%= UserId %>

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

__FILE__, __LINE__, and __FUNCTION__ usage in C++

__FUNCTION__ is non standard, __func__ exists in C99 / C++11. The others (__LINE__ and __FILE__) are just fine.

It will always report the right file and line (and function if you choose to use __FUNCTION__/__func__). Optimization is a non-factor since it is a compile time macro expansion; it will never affect performance in any way.

How do I connect to this localhost from another computer on the same network?

Provided both machines are in the same workgroup, open cmd.exe on the machine you want to connect to, type ipconfig and note the IP at the IPv4 Address line.

Then, on the machine you want to connect with, use http:// + the IP of the target machine.

That should do it.

How to configure heroku application DNS to Godaddy Domain?

You can't use the naked domain of your-domain.com if it is not redirected to the www.your-domain.com. Heroku use the www.yourdomain.com which act here as a subdomain. So when you follow the default instruction to use your-domain.com then you will need to assign both of them.

We can actually assign only the naked domain without the www.your-domain.com. Use only your-domain.com when the domain's dns provider (NameServers) support ALIAS or ANAME for the @ Record to example.herokuapp.com without CNAME www.your-domain.com to it.

It will let you to point www.your-domain.com to other hosting separately (independent).

How can I reverse a NSArray in Objective-C?

There is a easy way to do it.

    NSArray *myArray = @[@"5",@"4",@"3",@"2",@"1"];
    NSMutableArray *myNewArray = [[NSMutableArray alloc] init]; //this object is going to be your new array with inverse order.
    for(int i=0; i<[myNewArray count]; i++){
        [myNewArray insertObject:[myNewArray objectAtIndex:i] atIndex:0];
    }
    //other way to do it
    for(NSString *eachValue in myArray){
        [myNewArray insertObject:eachValue atIndex:0];
    }

    //in both cases your new array will look like this
    NSLog(@"myNewArray: %@", myNewArray);
    //[@"1",@"2",@"3",@"4",@"5"]

I hope this helps.

Failed to instantiate module error in Angular js

Or the minified version of the file...

<script src="angular-route.min.js"></script>

More information about this here:

"This error occurs when a module fails to load due to some exception. The error message above should provide additional context."

"In AngularJS 1.2.0 and later, ngRoute has been moved to its own module. If you are getting this error after upgrading to 1.2.x, be sure that you've installed ngRoute."

Listed under section Error: $injector:modulerr Module Error in the Angularjs docs.

What are the uses of the exec command in shell scripts?

The exec built-in command mirrors functions in the kernel, there are a family of them based on execve, which is usually called from C.

exec replaces the current program in the current process, without forking a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;

  1. We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile, the last statement says something like:

     exec appln-program
    

    so now there is no shell to go back to. Even if appln-program crashes, the end-user cannot get to a shell, because it is not there - the exec replaced it.

  2. We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh, and everyone just put into their .login (csh start-up file) a call to ksh. While that worked, it left a stray csh process running, and the logout was two stage which could get confusing. So we changed it to exec ksh which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh is not a login-shell).

  3. Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4 etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.

You have obviously seen exec used somewhere, perhaps if you showed the code that's bugging you we could justify its use.

Edit: I realised that my answer above is incomplete. There are two uses of exec in shells like ksh and bash - used for opening file descriptors. Here are some examples:

exec 3< thisfile          # open "thisfile" for reading on file descriptor 3
exec 4> thatfile          # open "thatfile" for writing on file descriptor 4
exec 8<> tother           # open "tother" for reading and writing on fd 8
exec 6>> other            # open "other" for appending on file descriptor 6
exec 5<&0                 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4                 # copy write file descriptor 4 onto 7
exec 3<&-                 # close the read file descriptor 3
exec 6>&-                 # close the write file descriptor 6

Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec reverts to the original meaning:

  exec 3 < thisfile       # oops, overwrite the current program with command "3"

There are several ways you can use these, on ksh use read -u or print -u, on bash, for example:

read <&3
echo stuff >&4

What is a LAMP stack?

For anyone still looking into this in order to learn specifically what a stack is, the term "stack" is referring to a "solution stack." A solution stack is simply a complete set of software to address a given problem, usually by combining to provide the platform or infrastructure necessary. This term is the parent of both "server stack" and "web stack." Accordingly, a LAMP stack is a specific and complete set of software specifically aimed at serving dynamic content over the web.

Some extra reading:

https://www.techopedia.com/definition/28154/solution-stack https://en.wikipedia.org/wiki/Solution_stack

Programmatically scroll to a specific position in an Android ListView

I have set OnGroupExpandListener and override onGroupExpand() as:

and use setSelectionFromTop() method which Sets the selected item and positions the selection y pixels from the top edge of the ListView. (If in touch mode, the item will not be selected but it will still be positioned appropriately.) (android docs)

    yourlist.setOnGroupExpandListener (new ExpandableListView.OnGroupExpandListener()
    {

        @Override
        public void onGroupExpand(int groupPosition) {

            expList.setSelectionFromTop(groupPosition, 0);
            //your other code
        }
    });

Convert.ToDateTime: how to set format

How about this:

    string test = "01-12-12";
    try{
         DateTime dateTime = DateTime.Parse(test);
         test = dateTime.ToString("dd/yyyy");
    }
    catch (FormatException exc)
    {
        MessageBox.Show(exc.Message);
    }

Where test will be equal to "12/2012"

Hope it helps!

Please read HERE.

best way to preserve numpy arrays on disk

The lookup time is slow because when you use mmap to does not load content of array to memory when you invoke load method. Data is lazy loaded when particular data is needed. And this happens in lookup in your case. But second lookup won`t be so slow.

This is nice feature of mmap when you have a big array you do not have to load whole data into memory.

To solve your can use joblib you can dump any object you want using joblib.dump even two or more numpy arrays, see the example

firstArray = np.arange(100)
secondArray = np.arange(50)
# I will put two arrays in dictionary and save to one file
my_dict = {'first' : firstArray, 'second' : secondArray}
joblib.dump(my_dict, 'file_name.dat')

How do I update all my CPAN modules to their latest versions?

Try perl -MCPAN -e "upgrade /(.\*)/". It works fine for me.

Using Node.JS, how do I read a JSON file into (server) memory?

If you are looking for a complete solution for Async loading a JSON file from Relative Path with Error Handling

  // Global variables
  // Request path module for relative path
    const path = require('path')
  // Request File System Module
   var fs = require('fs');


// GET request for the /list_user page.
router.get('/listUsers', function (req, res) {
   console.log("Got a GET request for list of users");

     // Create a relative path URL
    let reqPath = path.join(__dirname, '../mock/users.json');

    //Read JSON from relative path of this file
    fs.readFile(reqPath , 'utf8', function (err, data) {
        //Handle Error
       if(!err) {
         //Handle Success
          console.log("Success"+data);
         // Parse Data to JSON OR
          var jsonObj = JSON.parse(data)
         //Send back as Response
          res.end( data );
        }else {
           //Handle Error
           res.end("Error: "+err )
        }
   });
})

Directory Structure:

enter image description here

Concatenating variables and strings in React

You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id} - you need to indicate which are variables and which are string literals. Since anything inside {} is an inline JSX expression, you can do:

href={"#demo" + this.state.id}

This will use the string literal #demo and concatenate it to the value of this.state.id. This can then be applied to all strings. Consider this:

var text = "world";

And this:

{"Hello " + text + " Andrew"}

This will yield:

Hello world Andrew 

You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr} (interpolated expression), which is closer to what you seem to be trying to do:

href={`#demo${this.state.id}`}

This will basically substitute the value of this.state.id, concatenating it to #demo. It is equivalent to doing: "#demo" + this.state.id.

Insert a line at specific line number with sed or awk

POSIX sed (and for example OS X's sed, the sed below) require i to be followed by a backslash and a newline. Also at least OS X's sed does not include a newline after the inserted text:

$ seq 3|gsed '2i1.5'
1
1.5
2
3
$ seq 3|sed '2i1.5'
sed: 1: "2i1.5": command i expects \ followed by text
$ seq 3|sed $'2i\\\n1.5'
1
1.52
3
$ seq 3|sed $'2i\\\n1.5\n'
1
1.5
2
3

To replace a line, you can use the c (change) or s (substitute) commands with a numeric address:

$ seq 3|sed $'2c\\\n1.5\n'
1
1.5
3
$ seq 3|gsed '2c1.5'
1
1.5
3
$ seq 3|sed '2s/.*/1.5/'
1
1.5
3

Alternatives using awk:

$ seq 3|awk 'NR==2{print 1.5}1'
1
1.5
2
3
$ seq 3|awk '{print NR==2?1.5:$0}'
1
1.5
3

awk interprets backslashes in variables passed with -v but not in variables passed using ENVIRON:

$ seq 3|awk -v v='a\ba' '{print NR==2?v:$0}'
1
a
3
$ seq 3|v='a\ba' awk '{print NR==2?ENVIRON["v"]:$0}'
1
a\ba
3

Both ENVIRON and -v are defined by POSIX.

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

Despite the fact that this is a very old question and probably many of the beforementioned ideas solved many problems, I still want to share the solution with the community that fixed my problem.

I found that the problem was a function called "hasItem" which I was using to check whether or not a JSON-Array contains a specific item. In my case I checked for a value of type Long.

And this led to the problem.

Somehow, the Matchers have problems with values of type Long. (I do not use JUnit or Rest-Assured so much so idk. exactly why, but I guess that the returned JSON-data does just contain Integers.)

So what I did to actually fix the problem was the following. Instead of using:

long ID = ...;

...
.then().assertThat()
  .body("myArray", hasItem(ID));

you just have to cast to Integer. So the working code looked like this:

long ID = ...;

...
.then().assertThat()
  .body("myArray", hasItem((int) ID));

That's probably not the best solution, but I just wanted to mention that the exception can also be thrown because of wrong/unknown data types.

Where is the correct location to put Log4j.properties in an Eclipse project?

I'm finding out that the location of the log4j.properties file depends on the type of Eclipse project.

Specifically, for an Eclipse Dynamic Web Project, most of the answers that involve adding the log4j.properties to the war file do not actually add the properties file in the correct location, especially for Tomcat/Apache.

Here is some of my research and my solution to the issue (again specifically for a Dynamic Web Project running on Tomcat/Apache 6.0)

  • Please refer to this article around how Tomcat will load classes. It's different than the normal class loader for Java. (https://www.mulesoft.com/tcat/tomcat-classpath) Note that it only looks in two places in the war file, WEB-INF/classes and WEB-INF/lib.

  • Note that with a Dynamic Web Project, it is not wise to store your .properties file in the build/../classes directory, as this directory is wiped whenever you clean-build your project.

  • Tomcat does not handle .property files in the WEB-INF/lib location.

  • You cannot store the log4j.properties file in the src directory, as Eclipse abstracts that directory away from your view.

  • The one way I have found to resolve this is to alter the build and add an additional directory that will eventually load into the WEB-INF/classes directory in the war file. Specifically....

(1) Right click your project in the project explorer, select 'New'->'Folder'. You can name the folder anything, but the standard in this case is 'resources'. The new folder should appear at the root level of your project.

(2) Move the log4j.properties file into this new folder.

(3) Right click the project again, and select 'Build-Path'->'Configure Build Path'. Select the 'Sources' tab. Click the 'Add Folder' button. Browse to find your new folder you created in step (1) above. Select 'OK'.

(4) Once back to the eclipse Project Explorer view, note that the folder has now moved to the 'Java Resources' area (ie it's no longer at the root due to eclipse presentation abstraction).

(5) Clean build your project.

(6) To validate that the .properties file now exists in WEB-INF/classes in your war file, export a war file to an easy location (right click Project -> Export -> War file) and checkout the contents. Note that the log4j.properties file now appears in the WEB-INF/classes.

(7) Promote your project to Tomcat/Apache and note that log4j now works.

Now that log4j works, start logging, solve world problems, take some time off, and enjoy a tasty adult beverage.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

Warning: Do not use this in production code!

As a workaround, you can switch off certificate validation. Only ever do this to obtain confirmation that the error is being throw because of a bad certificate.

Call this method before you call smtpclient.Send():

    [Obsolete("Do not use this in Production code!!!",true)]
    static void NEVER_EAT_POISON_Disable_CertificateValidation()
    {
        // Disabling certificate validation can expose you to a man-in-the-middle attack
        // which may allow your encrypted message to be read by an attacker
        // https://stackoverflow.com/a/14907718/740639
        ServicePointManager.ServerCertificateValidationCallback =
            delegate (
                object s,
                X509Certificate certificate,
                X509Chain chain,
                SslPolicyErrors sslPolicyErrors
            ) {
                return true;
            };
    }

What is the difference between json.load() and json.loads() functions

In python3.7.7, the definition of json.load is as below according to cpython source code:

def load(fp, *, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):

    return loads(fp.read(),
        cls=cls, object_hook=object_hook,
        parse_float=parse_float, parse_int=parse_int,
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

json.load actually calls json.loads and use fp.read() as the first argument.

So if your code is:

with open (file) as fp:
    s = fp.read()
    json.loads(s)

It's the same to do this:

with open (file) as fp:
    json.load(fp)

But if you need to specify the bytes reading from the file as like fp.read(10) or the string/bytes you want to deserialize is not from file, you should use json.loads()

As for json.loads(), it not only deserialize string but also bytes. If s is bytes or bytearray, it will be decoded to string first. You can also find it in the source code.

def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
    containing a JSON document) to a Python object.

    ...

    """
    if isinstance(s, str):
        if s.startswith('\ufeff'):
            raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
                                  s, 0)
    else:
        if not isinstance(s, (bytes, bytearray)):
            raise TypeError(f'the JSON object must be str, bytes or bytearray, '
                            f'not {s.__class__.__name__}')
        s = s.decode(detect_encoding(s), 'surrogatepass')

How to access array elements in a Django template?

Remember that the dot notation in a Django template is used for four different notations in Python. In a template, foo.bar can mean any of:

foo[bar]       # dictionary lookup
foo.bar        # attribute lookup
foo.bar()      # method call
foo[bar]       # list-index lookup

It tries them in this order until it finds a match. So foo.3 will get you your list index because your object isn't a dict with 3 as a key, doesn't have an attribute named 3, and doesn't have a method named 3.

Eclipse: Enable autocomplete / content assist

For me, it helped after I changed the theme to 'mac' since I am running on a MacOSX.

Eclipse: >Preferences > General > Appearance > Choose 'Mac' from the menu.

How to convert a UTF-8 string into Unicode?

So the issue is that UTF-8 code unit values have been stored as a sequence of 16-bit code units in a C# string. You simply need to verify that each code unit is within the range of a byte, copy those values into bytes, and then convert the new UTF-8 byte sequence into UTF-16.

public static string DecodeFromUtf8(this string utf8String)
{
    // copy the string as UTF-8 bytes.
    byte[] utf8Bytes = new byte[utf8String.Length];
    for (int i=0;i<utf8String.Length;++i) {
        //Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
        utf8Bytes[i] = (byte)utf8String[i];
    }

    return Encoding.UTF8.GetString(utf8Bytes,0,utf8Bytes.Length);
}

DecodeFromUtf8("d\u00C3\u00A9j\u00C3\u00A0"); // déjà

This is easy, however it would be best to find the root cause; the location where someone is copying UTF-8 code units into 16 bit code units. The likely culprit is somebody converting bytes into a C# string using the wrong encoding. E.g. Encoding.Default.GetString(utf8Bytes, 0, utf8Bytes.Length).


Alternatively, if you're sure you know the incorrect encoding which was used to produce the string, and that incorrect encoding transformation was lossless (usually the case if the incorrect encoding is a single byte encoding), then you can simply do the inverse encoding step to get the original UTF-8 data, and then you can do the correct conversion from UTF-8 bytes:

public static string UndoEncodingMistake(string mangledString, Encoding mistake, Encoding correction)
{
    // the inverse of `mistake.GetString(originalBytes);`
    byte[] originalBytes = mistake.GetBytes(mangledString);
    return correction.GetString(originalBytes);
}

UndoEncodingMistake("d\u00C3\u00A9j\u00C3\u00A0", Encoding(1252), Encoding.UTF8);

Remove title in Toolbar in appcompat-v7

I dont know whether this is the correct way or not but I have changed my style like this.

<style name="NoActionBarStyle" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

Failed to load resource under Chrome

Check the network tab to see if Chrome failed to download any resource file.

Loading another html page from javascript

You can use the following code :

<!DOCTYPE html>
<html>
    <body onLoad="triggerJS();">

    <script>
        function triggerJS(){
        location.replace("http://www.google.com");
        /*
        location.assign("New_WebSite_Url");
        //Use assign() instead of replace if you want to have the first page in the history (i.e if you want the user to be able to navigate back when New_WebSite_Url is loaded)
        */
        }
    </script>

    </body>
</html>

Check if a number has a decimal place/is a whole number

You can use the bitwise operations that do not change the value (^ 0 or ~~) to discard the decimal part, which can be used for rounding. After rounding the number, it is compared to the original value:

function isDecimal(num) {
  return (num ^ 0) !== num;
}

console.log( isDecimal(1) ); // false
console.log( isDecimal(1.5) ); // true
console.log( isDecimal(-0.5) ); // true

how to add value to a tuple?

Tuples are immutable and not supposed to be changed - that is what the list type is for. You could replace each tuple by originalTuple + (newElement,), thus creating a new tuple. For example:

t = (1,2,3)
t = t + (1,)
print t
(1,2,3,1)

But I'd rather suggest to go with lists from the beginning, because they are faster for inserting items.

And another hint: Do not overwrite the built-in name list in your program, rather call the variable l or some other name. If you overwrite the built-in name, you can't use it anymore in the current scope.

How to play ringtone/alarm sound in Android

Your example is basically what I'm using. It never works on the emulator, however, because the emulator doesn't have any ringtones by default, and content://settings/system/ringtone doesn't resolve to anything playable. It works fine on my actual phone.

Mutex lock threads

A process consists of at least one thread (think of the main function). Multi threaded code will just spawn more threads. Mutexes are used to create locks around shared resources to avoid data corruption / unexpected / unwanted behaviour. Basically it provides for sequential execution in an asynchronous setup - the requirement for which stems from non-const non-atomic operations on shared data structures.

A vivid description of what mutexes would be the case of people (threads) queueing up to visit the restroom (shared resource). While one person (thread) is using the bathroom easing him/herself (non-const non-atomic operation), he/she should ensure the door is locked (mutex), otherwise it could lead to being caught in full monty (unwanted behaviour)

Can you get the number of lines of code from a GitHub repository?

If you go to the graphs/contributors page, you can see a list of all the contributors to the repo and how many lines they've added and removed.

Unless I'm missing something, subtracting the aggregate number of lines deleted from the aggregate number of lines added among all contributors should yield the total number of lines of code in the repo. (EDIT: it turns out I was missing something after all. Take a look at orbitbot's comment for details.)

UPDATE:

This data is also available in GitHub's API. So I wrote a quick script to fetch the data and do the calculation:

_x000D_
_x000D_
'use strict';

async function countGithub(repo) {
    const response = await fetch(`https://api.github.com/repos/${repo}/stats/contributors`)
    const contributors = await response.json();
    const lineCounts = contributors.map(contributor => (
        contributor.weeks.reduce((lineCount, week) => lineCount + week.a - week.d, 0)
    ));
    const lines = lineCounts.reduce((lineTotal, lineCount) => lineTotal + lineCount);
    window.alert(lines);
}

countGithub('jquery/jquery'); // or count anything you like
_x000D_
_x000D_
_x000D_

Just paste it in a Chrome DevTools snippet, change the repo and click run.

Disclaimer (thanks to lovasoa):

Take the results of this method with a grain of salt, because for some repos (sorich87/bootstrap-tour) it results in negative values, which might indicate there's something wrong with the data returned from GitHub's API.

UPDATE:

Looks like this method to calculate total line numbers isn't entirely reliable. Take a look at orbitbot's comment for details.

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

Had a related issue with a different, but similar fix:

I had a Windows service project set to "Any-CPU" using a 64-bit DLL. Same error message. Tried a whole bunch of things, but nothing worked. Finally, I went into project Properties -> Build and noticed that project had "Prefer 32-bit" checked. Unchecked this and no more error.

My guess is that the windows service was expecting a 32-bit DLL, and couldn't find it.

How to use IntelliJ IDEA to find all unused code?

Just use Analyze | Inspect Code with appropriate inspection enabled (Unused declaration under Declaration redundancy group).

Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"

YouTube URL in Video Tag

This would be easy to do :

<iframe width="420" height="345"
src="http://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>

Is just an example.

How to render pdfs using C#

You can add a NuGet package CefSharp.WinForms to your application and then add a ChromiumWebBroweser control to your form. In the code you can write:

chromiumWebBrowser1.Load(filePath);

This is the easiest solution I have found, it is completely free and independent of the user's computer settings like it would be when using default WebBrowser control.

Found shared references to a collection org.hibernate.HibernateException

I have experienced a great example of reproducing such a problem. Maybe my experience will help someone one day.

Short version

Check that your @Embedded Id of container has no possible collisions.

Long version

When Hibernate instantiates collection wrapper, it searches for already instantiated collection by CollectionKey in internal Map.

For Entity with @Embedded id, CollectionKey wraps EmbeddedComponentType and uses @Embedded Id properties for equality checks and hashCode calculation.

So if you have two entities with equal @Embedded Ids, Hibernate will instantiate and put new collection by the first key and will find same collection for the second key. So two entities with same @Embedded Id will be populated with same collection.

Example

Suppose you have Account entity which has lazy set of loans. And Account has @Embedded Id consists of several parts(columns).

@Entity
@Table(schema = "SOME", name = "ACCOUNT")
public class Account {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "account")
    private Set<Loan> loans;

    @Embedded
    private AccountId accountId;

    ...
}

@Embeddable
public class AccountId {
    @Column(name = "X")
    private Long x;
    
    @Column(name = "BRANCH")
    private String branchId;
    
    @Column(name = "Z")
    private String z;

    ...
}

Then suppose that Account has additional property mapped by @Embedded Id but has relation to other entity Branch.

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BRANCH")
@MapsId("accountId.branchId")
@NotFound(action = NotFoundAction.IGNORE)//Look at this!
private Branch branch;

It could happen that you have no FK for Account to Brunch relation id DB so Account.BRANCH column can have any value not presented in Branch table.

According to @NotFound(action = NotFoundAction.IGNORE) if value is not present in related table, Hibernate will load null value for the property.

If X and Y columns of two Accounts are same(which is fine), but BRANCH is different and not presented in Branch table, hibernate will load null for both and Embedded Ids will be equal.

So two CollectionKey objects will be equal and will have same hashCode for different Accounts.

result = {CollectionKey@34809} "CollectionKey[Account.loans#Account@43deab74]"
 role = "Account.loans"
 key = {Account@26451} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

result = {CollectionKey@35653} "CollectionKey[Account.loans#Account@33470aa]"
 role = "Account.loans"
 key = {Account@35225} 
 keyType = {EmbeddedComponentType@21355} 
 factory = {SessionFactoryImpl@21356} 
 hashCode = 1187125168
 entityMode = {EntityMode@17415} "pojo"

Because of this, Hibernate will load same PesistentSet for two entities.

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

DO NOT put ALTER TABLE/MODIFY COLS or any other such table mod operations inside a TRANSACTION. Transactions are for being able to roll back a QUERY failure not for ALTERations...it will error out every time in a transaction.

Just run a SELECT * query on the table and check if the column is there...

Creating an IFRAME using JavaScript

It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.

<div id="placeholder"></div>

<script id="iframeTemplate" type="text/html">
    <iframe src="...">
        <!-- replace this line with alternate content -->
    </iframe>
</script>

<script type="text/javascript">
var element,
    html,
    template;

element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;

element.innerHTML = html;
</script>

Using an authorization header with Fetch in React Native

It turns out, I was using the fetch method incorrectly.

fetch expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.

I was wrapping the intended object within a second object, which did not get me any desired result.

Here's how it looks on a high level:

fetch('API_ENDPOINT', OBJECT)  
  .then(function(res) {
    return res.json();
   })
  .then(function(resJson) {
    return resJson;
   })

I structured my object as such:

var obj = {  
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Origin': '',
    'Host': 'api.producthunt.com'
  },
  body: JSON.stringify({
    'client_id': '(API KEY)',
    'client_secret': '(API SECRET)',
    'grant_type': 'client_credentials'
  })

C/C++ check if one bit is set in, i.e. int variable

Check if bit N (starting from 0) is set:

temp & (1 << N)

There is no builtin function for this.

How to sort List of objects by some property

In java you need to use the static Collections.sort method. Here is an example for a list of CompanyRole objects, sorted first by begin and then by end. You can easily adapt for your own object.

private static void order(List<TextComponent> roles) {

    Collections.sort(roles, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            int x1 = ((CompanyRole) o1).getBegin();
            int x2 = ((CompanyRole) o2).getBegin();

            if (x1 != x2) {
                return x1 - x2;
            } else {
                int y1 = ((CompanyRole) o1).getEnd();
                int y2 = ((CompanyRole) o2).getEnd();
                return y2 - y1;
            }
        }
    });
}

How to check if a character in a string is a digit or letter

You could use:

    if (Character.isLetter(character.charAt(0))){
    ....

Checking whether a variable is an integer or not

if type(input('enter = '))==int:
     print 'Entered number is an Integer'
else:
     print 'Entered number isn't an Integer'

This'll work to check out whether number is an integer or not

How to convert a file into a dictionary?

Simple Option

Most methods for storing a dictionary use JSON, Pickle, or line reading. Providing you're not editing the dictionary outside of Python, this simple method should suffice for even complex dictionaries. Although Pickle will be better for larger dictionaries.

x = {1:'a', 2:'b', 3:'c'}
f = 'file.txt'
print(x, file=open(f,'w'))    # file.txt >>> {1:'a', 2:'b', 3:'c'}
y = eval(open(f,'r').read())
print(x==y)                   # >>> True

How to determine when a Git branch was created?

This did it for me: (10 years later)

git log [--remotes] --no-walk --decorate

Since there is no stored information on branch creation times, what this does is display the first commit of each branch (--no-walk), which includes the date of the commit. Use --remotes for the remote branches, or omit it for local branches.

Since I do at least one commit in a branch before creating another one, this permitted me trace back a few months of branch creations (and feature dev-start) for documentation purposes.

source: AnoE on stackexchange

How do getters and setters work?

class Clock {  
        String time;  

        void setTime (String t) {  
           time = t;  
        }  

        String getTime() {  
           return time;  
        }  
}  


class ClockTestDrive {  
   public static void main (String [] args) {  
   Clock c = new Clock;  

   c.setTime("12345")  
   String tod = c.getTime();  
   System.out.println(time: " + tod);  
 }
}  

When you run the program, program starts in mains,

  1. object c is created
  2. function setTime() is called by the object c
  3. the variable time is set to the value passed by
  4. function getTime() is called by object c
  5. the time is returned
  6. It will passe to tod and tod get printed out

How do you uninstall the package manager "pip", if installed from source?

That way you haven't installed pip, you installed just the easy_install i.e. setuptools.

First you should remove all the packages you installed with easy_install using (see uninstall):

easy_install -m PackageName

This includes pip if you installed it using easy_install pip.

After this you remove the setuptools following the instructions from here:

If setuptools package is found in your global site-packages directory, you may safely remove the following file/directory:

setuptools-*.egg

If setuptools is installed in some other location such as the user site directory (eg: ~/.local, ~/Library/Python or %APPDATA%), then you may safely remove the following files:

pkg_resources.py
easy_install.py
setuptools/
setuptools-*.egg-info/

Remove trailing spaces automatically or with a shortcut

Have a look at the EditorConfig plugin.

By using the plugin you can have settings specific for various projects. Visual Studio Code also has IntelliSense built-in for .editorconfig files.

Relative imports in Python 3

To obviate this problem, I devised a solution with the repackage package, which has worked for me for some time. It adds the upper directory to the lib path:

import repackage
repackage.up()
from mypackage.mymodule import myfunction

Repackage can make relative imports that work in a wide range of cases, using an intelligent strategy (inspecting the call stack).

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

This explains the whole thing:

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

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

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

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

Add values to app.config and retrieve them

Are you missing the reference to System.Configuration.dll? ConfigurationManager class lies there.

EDIT: The System.Configuration namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default...

How can I compile a Java program in Eclipse without running it?

Go to the project explorer block ... right click on project name select "Build Path"-----------> "Configuration Build Path"

then the pop up window will get open.

in this pop up window you will find 4 tabs. 1)source 2) project 3)Library 4)order and export

Click on 1) Source

select the project (under which that file is present which you want to compile)

and then click on ok....

Go to the workspace location of the project open a bin folder and search that class file ...

you will get that java file compiled...

just to cross verify check the changed timing.

hope this will help.

Thanks.

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Create AMI -> Boot AMI on large instance.

More info http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/creating-an-image.html

You can do this all from the admin console too at aws.amazon.com

delete image from folder PHP

You can delete files in PHP using the unlink() function.

unlink('path/to/file.jpg');

How do I split an int into its digits?

You can count how many digits you want to print first

#include <iostream>
#include <cmath>
using namespace std;

int main(){
int number, result, counter=0, zeros;

do{
    cout << "Introduce un numero entero: ";
  cin >> number;

  }while (number < 0);

  // We count how many digits we are going print
  for(int i = number; i > 0; i = i/10)
        counter++;

   while(number > 0){

       zeros = pow(10, counter - 1);

       result = number / zeros;
       number = number % zeros;
       counter--;

       //Muestra resultados
       cout << " " << result;
   }
   cout<<endl;

}

How to do relative imports in Python?

main.py
setup.py
app/ ->
    __init__.py
    package_a/ ->
       __init__.py
       module_a.py
    package_b/ ->
       __init__.py
       module_b.py
  1. You run python main.py.
  2. main.py does: import app.package_a.module_a
  3. module_a.py does import app.package_b.module_b

Alternatively 2 or 3 could use: from app.package_a import module_a

That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.

So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.

TypeError: method() takes 1 positional argument but 2 were given

As mentioned in other answers - when you use an instance method you need to pass self as the first argument - this is the source of the error.

With addition to that,it is important to understand that only instance methods take self as the first argument in order to refer to the instance.

In case the method is Static you don't pass self, but a cls argument instead (or class_).

Please see an example below.

class City:

   country = "USA" # This is a class level attribute which will be shared across all instances  (and not created PER instance)

   def __init__(self, name, location, population):
       self.name       = name
       self.location   = location
       self.population = population
 
   # This is an instance method which takes self as the first argument to refer to the instance 
   def print_population(self, some_nice_sentence_prefix):
       print(some_nice_sentence_prefix +" In " +self.name + " lives " +self.population + " people!")

   # This is a static (class) method which is marked with the @classmethod attribute
   # All class methods must take a class argument as first param. The convention is to name is "cls" but class_ is also ok
   @classmethod
   def change_country(cls, new_country):
       cls.country = new_country

Some tests just to make things more clear:

# Populate objects
city1 = City("New York",    "East", "18,804,000")
city2 = City("Los Angeles", "West", "10,118,800")

#1) Use the instance method: No need to pass "self" - it is passed as the city1 instance
city1.print_population("Did You Know?") # Prints: Did You Know? In New York lives 18,804,000 people!

#2.A) Use the static method in the object
city2.change_country("Canada")

#2.B) Will be reflected in all objects
print("city1.country=",city1.country) # Prints Canada
print("city2.country=",city2.country) # Prints Canada

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

Html.Raw() in ASP.NET MVC Razor view

You shouldn't be calling .ToString().

As the error message clearly states, you're writing a conditional in which one half is an IHtmlString and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.


There is never a reason to call Html.Raw(...).ToString().
Html.Raw returns an HtmlString instance that wraps the original string.
The Razor page output knows not to escape HtmlString instances.

However, calling HtmlString.ToString() just returns the original string value again; it doesn't accomplish anything.

How to Fill an array from user input C#?

Try:

array[i] = Convert.ToDouble(Console.Readline());

You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.

Trying to merge 2 dataframes but get ValueError

It happens when common column in both table are of different data type.

Example: In table1, you have date as string whereas in table2 you have date as datetime. so before merging,we need to change date to common data type.

How does Subquery in select statement work in oracle

In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.

How to add image in a TextView text?

This is partly based on this earlier answer above by @A Boschman. In that solution, I found that the input size of the image greatly affected the ability of makeImageSpan() to properly center-align the image. Additionally, I found that the solution affected text spacing by creating unnecessary line spacing.

I found BaseImageSpan (from Facebook's Fresco library) to do the job particularly well:

 /**
 * Create an ImageSpan for the given icon drawable. This also sets the image size. Works best
 * with a square icon because of the sizing
 *
 * @param context       The Android Context.
 * @param drawableResId A drawable resource Id.
 * @param size          The desired size (i.e. width and height) of the image icon in pixels.
 *                      Use the lineHeight of the TextView to make the image inline with the
 *                      surrounding text.
 * @return An ImageSpan, aligned with the bottom of the text.
 */
private static BetterImageSpan makeImageSpan(Context context, int drawableResId, int size) {
    final Drawable drawable = context.getResources().getDrawable(drawableResId);
    drawable.mutate();
    drawable.setBounds(0, 0, size, size);
    return new BetterImageSpan(drawable, BetterImageSpan.ALIGN_CENTER);
}

Then supply your betterImageSpan instance to spannable.setSpan() as usual

wildcard * in CSS for classes

What you need is called attribute selector. An example, using your html structure, is the following:

div[class^="tocolor-"], div[class*=" tocolor-"] {
    color:red 
}

In the place of div you can add any element or remove it altogether, and in the place of class you can add any attribute of the specified element.

[class^="tocolor-"] — starts with "tocolor-".
[class*=" tocolor-"] — contains the substring "tocolor-" occurring directly after a space character.

Demo: http://jsfiddle.net/K3693/1/

More information on CSS attribute selectors, you can find here and here. And from MDN Docs MDN Docs

Get keys from HashMap in Java

To get Key and its value

e.g

private Map<String, Integer> team1 = new HashMap<String, Integer>();
  team1.put("United", 5);
  team1.put("Barcelona", 6);
    for (String key:team1.keySet()){
                     System.out.println("Key:" + key +" Value:" + team1.get(key)+" Count:"+Collections.frequency(team1, key));// Get Key and value and count
                }

Will print: Key: United Value:5 Key: Barcelona Value:6

TypeError: Converting circular structure to JSON in nodejs

It's because you don't an async response For example:

app.get(`${api}/users`, async (req, res) => {
    const users = await User.find()
    res.send(users);
   })

Uninstall old versions of Ruby gems

# remove all old versions of the gem
gem cleanup rjb

# choose which ones you want to remove
gem uninstall rjb

# remove version 1.1.9 only
gem uninstall rjb --version 1.1.9

# remove all versions less than 1.3.4
gem uninstall rjb --version '<1.3.4'

Difference between SRC and HREF

after going through the HTML 5.1 ducumentation (1 November 2016):


part 4 (The elements of HTML)

chapter 2 (Document metadata)

section 4 (The link element) states that:

The destination of the link(s) is given by the href attribute, which must be present and must contain a valid non-empty URL potentially surrounded by spaces. If the href attribute is absent, then the element does not define a link.

does not contain the src attribute ...

witch is logical because it is a link .


chapter 12 (Scripting)

section 1 (The script element) states that:

Classic scripts may either be embedded inline or may be imported from an external file using the src attribute, which if specified gives the URL of the external script resource to use. If src is specified, it must be a valid non-empty URL potentially surrounded by spaces. The contents of inline script elements, or the external script resource, must conform with the requirements of the JavaScript specification’s Script production for classic scripts.

it doesn't even mention the href attribute ...

this indicates that while using script tags always use the src attribute !!!


chapter 7 (Embedded content)

section 5 (The img element)

The image given by the src and srcset attributes, and any previous sibling source element's srcset attributes if the parent is a picture element, is the embedded content.

also doesn't mention the href attribute ...

this indicates that when using img tags the src attribute should be used aswell ...


Reference link to the W3C Recommendation

Vim clear last search highlighting

Remapped to in my .vimrc.local file, quick and dirty but very functional:

" Clear last search highlighting
map <Space> :noh<cr>

Concatenate two NumPy arrays vertically

A not well known feature of numpy is to use r_. This is a simple way to build up arrays quickly:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.r_[a[None,:],b[None,:]]
print(c)
#[[1 2 3]
# [4 5 6]]

The purpose of a[None,:] is to add an axis to array a.

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

How to include (source) R script in other scripts

I solved my problem using entire address where my code is: Before:

if(!exists("foo", mode="function")) source("utils.r")

After:

if(!exists("foo", mode="function")) source("C:/tests/utils.r")

How might I force a floating DIV to match the height of another floating DIV?

Wrap them in a containing div with the background color applied to it, and have a clearing div after the 'columns'.

<div style="background-color: yellow;">
  <div style="float: left;width: 65%;">column a</div>
  <div style="float: right;width: 35%;">column b</div>
  <div style="clear: both;"></div>
</div>

Updated to address some comments and my own thoughts:

This method works because its essentially a simplification of your problem, in this somewhat 'oldskool' method I put two columns in followed by an empty clearing element, the job of the clearing element is to tell the parent (with the background) this is where floating behaviour ends, this allows the parent to essentially render 0 pixels of height at the position of the clear, which will be whatever the highest priorly floating element is.

The reason for this is to ensure the parent element is as tall as the tallest column, the background is then set on the parent to give the appearance that both columns have the same height.

It should be noted that this technique is 'oldskool' because the better choice is to trigger this height calculation behaviour with something like clearfix or by simply having overflow: hidden on the parent element.

Whilst this works in this limited scenario, if you wish for each column to look visually different, or have a gap between them, then setting a background on the parent element won't work, there is however a trick to get this effect.

The trick is to add bottom padding to all columns, to the max amount of size you expect that could be the difference between the shortest and tallest column, if you can't work this out then pick a large figure, you then need to add a negative bottom margin of the same number.

You'll need overflow hidden on the parent object, but the result will be that each column will request to render this additional height suggested by the margin, but not actually request layout of that size (because the negative margin counters the calculation).

This will render the parent at the size of the tallest column, whilst allowing all the columns to render at their height + the size of bottom padding used, if this height is larger than the parent then the rest will simply clip off.

<div style="overflow: hidden;">
  <div style="background: blue;float: left;width: 65%;padding-bottom: 500px;margin-bottom: -500px;">column a<br />column a</div>
  <div style="background: red;float: right;width: 35%;padding-bottom: 500px;margin-bottom: -500px;">column b</div>
</div>

You can see an example of this technique on the bowers and wilkins website (see the four horizontal spotlight images the bottom of the page).

How to send HTTP request in java?

Here's a complete Java 7 program:

class GETHTTPResource {
  public static void main(String[] args) throws Exception {
    try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("http://tools.ietf.org/rfc/rfc768.txt").openStream())) {
      System.out.println(s.useDelimiter("\\A").next());
    }
  }
}

The new try-with-resources will auto-close the Scanner, which will auto-close the InputStream.

How to shutdown my Jenkins safely?

You can kill Jenkins safely. It will catch SIGTERM and SIGINT and perform an orderly shutdown. However, if Jenkins was in the middle of building something, it will abort the builds and they will show up gray in the status display.

If you want to avoid this, you must put Jenkins into shutdown mode to prevent it from starting new builds and wait until currently running builds are done before killing Jenkins.

You can also use the Jenkins command line interface and tell Jenkins to safe-shutdown, which does the same. You can find more info on Jenkins cli at http://YOURJENKINS/cli

Visual Studio window which shows list of methods

In Visual Studio 2019, there is the "Go To Member" action located in Edit - Go To that is mapped by default to ALT+\. I think this was added in Visual Studio 2017.

Go To Member command

This is what pops up which provides the desired functionality and a couple of options:

Go to member popup

How to simulate browsing from various locations?

This is a bit of self promotion, but I built a tool to do just this that you might find useful, called GeoPeeker.

It remotely accesses a site from servers spread around the world, renders the page with webkit and sends back an image. It will also report the IP address and DNS information of the site as it appears from that location.

There are no ads, and it's very stream-lined to serve this one purpose. It's still in development, and feedback is welcome. Here's hoping somebody besides myself finds it useful!

How to access custom attributes from event object in React?

<div className='btn' onClick={(e) =>
     console.log(e.currentTarget.attributes['tag'].value)}
     tag='bold'>
    <i className='fa fa-bold' />
</div>

so e.currentTarget.attributes['tag'].value works for me

How is the java memory pool divided?

With Java8, non heap region no more contains PermGen but Metaspace, which is a major change in Java8, supposed to get rid of out of memory errors with java as metaspace size can be increased depending on the space required by jvm for class data.

Is it a bad practice to use an if-statement without curly braces?

The "rule" I follow is this:

If the "if" statement is testing in order to do something (I.E. call functions, configure variables etc.), use braces.

if($test)
{
    doSomething();
}

This is because I feel you need to make it clear what functions are being called and where the flow of the program is going, under what conditions. Having the programmer understand exactly what functions are called and what variables are set in this condition is important to helping them understand exactly what your program is doing.

If the "if" statement is testing in order to stop doing something (I.E. flow control within a loop or function), use a single line.

if($test) continue;
if($test) break;
if($test) return;

In this case, what's important to the programmer is discovering quickly what the exceptional cases are where you don't want the code to run, and that is all coverred in $test, not in the execution block.

Mockito How to mock only the call of a method of the superclass

Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.

 public Childservice extends BaseService {
    public void save(){
        //some code
        superSave();
    }

    void superSave(){
        super.save();
    }
}

Loop Through All Subfolders Using VBA

And to complement Rich's recursive answer, a non-recursive method.

Public Sub NonRecursiveMethod()
    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("your folder path variable") 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
            '...insert any file processing code here...
        Next oFile
    Loop

End Sub

You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1) with Set oFolder = queue(queue.Count) and replace queue.Remove(1) with queue.Remove(queue.Count), and probably rename the variable...)

How do I use System.getProperty("line.separator").toString()?

Try this:

rows = tabDelimitedTable.split("[\\r\\n]+");

This should work regardless of what line delimiters are in the input, and will ignore blank lines.

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

How do I find all of the symlinks in a directory tree?

One command, no pipes

find . -type l -ls

Explanation: find from the current directory . onwards all references of -type link and list -ls those in detail. Plain and simple...

Expanding upon this answer, here are a couple more symbolic link related find commands:

Find symbolic links to a specific target

find . -lname link_target

Note that link_target is a pattern that may contain wildcard characters.

Find broken symbolic links

find -L . -type l -ls

The -L option instructs find to follow symbolic links, unless when broken.

Find & replace broken symbolic links

find -L . -type l -delete -exec ln -s new_target {} \;

More find examples

More find examples can be found here: https://hamwaves.com/find/

Keyboard shortcut to clear cell output in Jupyter notebook

Add following at start of cell and run it:

from IPython.display import clear_output
clear_output(wait=True)

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

For yet another concrete use case, use double brackets when you want to select a data frame created by the split() function. If you don't know, split() groups a list/data frame into subsets based on a key field. It's useful if when you want to operate on multiple groups, plot them, etc.

> class(data)
[1] "data.frame"

> dsplit<-split(data, data$id)
> class(dsplit)
[1] "list"

> class(dsplit['ID-1'])
[1] "list"

> class(dsplit[['ID-1']])
[1] "data.frame"

Text overflow ellipsis on two lines

My solution reuses the one of amcdnl, but my fallback consist of using a height for the text container:

.my-caption h4 {
    display: -webkit-box;
    margin: 0 auto;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;

    height: 40px;/* Fallback for non-webkit */
}

How can I get the MAC and the IP address of a connected client in PHP?

too late to answer but here is my approach since no one mentioned this here:
why note a client side solution ?
a javascript implementation to store the mac in a cookie (you can encrypt it before that)
then each request must include that cookie name, else it will be rejected.
to make this even more fun you can make a server side verification
from the mac address you get the manifacturer (there are plenty of free APIs for this)
then compare it with the user_agent value to see if there was some sort of manipulation:
a mac address of HP + a user agent of Safari = reject request.

CURL and HTTPS, "Cannot resolve host"

You may have to enable the HTTPS part:

curl_setopt($c, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST,  2);

And if you need to verify (authenticate yourself) you may need this too:

curl_setopt($c, CURLOPT_USERPWD, 'username:password');

Make TextBox uneditable

Using the TextBox.ReadOnly property

TextBox.ReadOnly = true;

For a Non-Grey background you can change the TextBox.BackColor property to SystemColors.Window Color

textBox.BackColor = System.Drawing.SystemColors.Window;

When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.

How to check if array element exists or not in javascript?

(typeof files[1] === undefined)?
            this.props.upload({file: files}):
            this.props.postMultipleUpload({file: files widgetIndex: 0, id})

Check if the second item in the array is undefined using the typeof and checking for undefined

Adding placeholder text to textbox

I came up with a method that worked for me, but only because I was willing to use the textbox name as my placeholder. See below.

public TextBox employee = new TextBox();

private void InitializeHomeComponent()
{
    //
    //employee
    //
    this.employee.Name = "Caller Name";
    this.employee.Text = "Caller Name";
    this.employee.BackColor = System.Drawing.SystemColors.InactiveBorder;
    this.employee.Location = new System.Drawing.Point(5, 160);
    this.employee.Size = new System.Drawing.Size(190, 30);
    this.employee.TabStop = false;
    this.Controls.Add(employee);
    // I loop through all of my textboxes giving them the same function
    foreach (Control C in this.Controls)
    {
        if (C.GetType() == typeof(System.Windows.Forms.TextBox))
        {
            C.GotFocus += g_GotFocus;
            C.LostFocus += g_LostFocus;
        }
     }
 }

    private void g_GotFocus(object sender, EventArgs e)
    {
        var tbox = sender as TextBox;
        tbox.Text = "";
    }

    private void g_LostFocus(object sender, EventArgs e)
    {
        var tbox = sender as TextBox;
        if (tbox.Text == "")
        {
            tbox.Text = tbox.Name;
        }
    }

How do I limit the number of decimals printed for a double?

Use a DecimalFormatter:

double number = 0.9999999999999;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(number));

Will give you "0.99". You can add or subtract 0 on the right side to get more or less decimals.

Or use '#' on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to become (0.3).

Run Excel Macro from Outside Excel Using VBScript From Command Line

I generally store my macros in xlam add-ins separately from my workbooks so I wanted to open a workbook and then run a macro stored separately.

Since this required a VBS Script, I wanted to make it "portable" so I could use it by passing arguments. Here is the final script, which takes 3 arguments.

  • Full Path to Workbook
  • Macro Name
  • [OPTIONAL] Path to separate workbook with Macro

I tested it like so:

"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlam" "Hello"

"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlsx" "Hello" "%AppData%\Microsoft\Excel\XLSTART\Book1.xlam"

runmacro.vbs:

Set args = Wscript.Arguments

ws = WScript.Arguments.Item(0)
macro = WScript.Arguments.Item(1)
If wscript.arguments.count > 2 Then
 macrowb= WScript.Arguments.Item(2)
End If

LaunchMacro

Sub LaunchMacro() 
  Dim xl
  Dim xlBook  

  Set xl = CreateObject("Excel.application")
  Set xlBook = xl.Workbooks.Open(ws, 0, True)
  If wscript.arguments.count > 2 Then
   Set macrowb= xl.Workbooks.Open(macrowb, 0, True)
  End If
  'xl.Application.Visible = True ' Show Excel Window
  xl.Application.run macro
  'xl.DisplayAlerts = False  ' suppress prompts and alert messages while a macro is running
  'xlBook.saved = True ' suppresses the Save Changes prompt when you close a workbook
  'xl.activewindow.close
  xl.Quit

End Sub 

MVC Razor Radio Button

MVC5 Razor Views

Below example will also associate labels with radio buttons (radio button will be selected upon clicking on the relevant label)

// replace "Yes", "No" --> with, true, false if needed
@Html.RadioButtonFor(m => m.Compatible, "Yes", new { id = "compatible" })
@Html.Label("compatible", "Compatible")

@Html.RadioButtonFor(m => m.Compatible, "No", new { id = "notcompatible" })
@Html.Label("notcompatible", "Not Compatible")

How do I define the name of image built with docker-compose

For docker-compose version 2 file format, you can build and tag an image for one service and then use that same built image for another service.

For my case, I want to set up an elasticsearch cluster with 2 nodes, they both need to use the same image, but configured to run differently. I also want to build my own custom elasticsearch image from my own Dockerfile. So this is what I did (docker-compose.yml):

version: '2'

services:
  es-master:
    build: ./elasticsearch
    image: porter/elasticsearch
    ports:
      - "9200:9200"
    container_name: es_master

  es-node:
    image: porter/elasticsearch
    depends_on:
      - es-master
    ports:
      - "9200"
    command: elasticsearch --discovery.zen.ping.unicast.hosts=es_master

You can see that in the first service definition es-master, I use the build option to build an image from the Dockerfile in ./elasticsearch. I tag the image with the name porter/elasticsearch with the image option.
Then, I reference this built image in the es-node service definition with the image option, and also use a depends_on to make sure the other container es-master is built and run first.

How to convert a byte array to Stream

In your case:

MemoryStream ms = new MemoryStream(buffer);

Generic deep diff between two objects

const diff = require("deep-object-diff").diff;
let differences = diff(obj2, obj1);

There is an npm module with over 500k weekly downloads: https://www.npmjs.com/package/deep-object-diff

I like the object like representation of the differences - especially it is easy to see the structure, when it is formated.

const diff = require("deep-object-diff").diff;

const lhs = {
  foo: {
    bar: {
      a: ['a', 'b'],
      b: 2,
      c: ['x', 'y'],
      e: 100 // deleted
    }
  },
  buzz: 'world'
};

const rhs = {
  foo: {
    bar: {
      a: ['a'], // index 1 ('b')  deleted
      b: 2, // unchanged
      c: ['x', 'y', 'z'], // 'z' added
      d: 'Hello, world!' // added
    }
  },
  buzz: 'fizz' // updated
};

console.log(diff(lhs, rhs)); // =>
/*
{
  foo: {
    bar: {
      a: {
        '1': undefined
      },
      c: {
        '2': 'z'
      },
      d: 'Hello, world!',
      e: undefined
    }
  },
  buzz: 'fizz'
}
*/

How to access session variables from any class in ASP.NET?

(Updated for completeness)
You can access session variables from any page or control using Session["loginId"] and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].

But please read on for my original answer...


I always use a wrapper class around the ASP.NET session to simplify access to session variables:

public class MySession
{
    // private constructor
    private MySession()
    {
      Property1 = "default value";
    }

    // Gets the current session.
    public static MySession Current
    {
      get
      {
        MySession session =
          (MySession)HttpContext.Current.Session["__MySession__"];
        if (session == null)
        {
          session = new MySession();
          HttpContext.Current.Session["__MySession__"] = session;
        }
        return session;
      }
    }

    // **** add your session properties here, e.g like this:
    public string Property1 { get; set; }
    public DateTime MyDate { get; set; }
    public int LoginId { get; set; }
}

This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:

int loginId = MySession.Current.LoginId;

string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;

DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;

This approach has several advantages:

  • it saves you from a lot of type-casting
  • you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]
  • you can document your session items by adding XML doc comments on the properties of MySession
  • you can initialize your session variables with default values (e.g. assuring they are not null)

How to NodeJS require inside TypeScript file?

The best solution is to get a copy of Node's type definitions. This will solve all kinds of dependency issues, not only require(). This was previously done using packages like typings, but as Mike Chamberlain mentioned, Typings are deprecated. The modern way is doing it like this:

npm install --save-dev @types/node

Not only will it fix the compiler error, it will also add the definitions of the Node API to your IDE.

Does MySQL ignore null values on unique constraints?

A simple answer would be : No, it doesn't

Explanation : According to the definition of unique constraints (SQL-92)

A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns

This statement can have two interpretations as :

  • No two rows can have same values i.e. NULL and NULL is not allowed
  • No two non-null rows can have values i.e NULL and NULL is fine, but StackOverflow and StackOverflow is not allowed

Since MySQL follows second interpretation, multiple NULL values are allowed in UNIQUE constraint column. Second, if you would try to understand the concept of NULL in SQL, you will find that two NULL values can be compared at all since NULL in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL values in UNIQUE constraint column, you are contracting the meaning of NULL in SQL. I would summarise my answer by saying :

MySQL supports UNIQUE constraint but not on the cost of ignoring NULL values

Youtube iframe wmode issue

Adding ?wmode=opaque to the URL seems to solve this problem for me, although I have not tested it in IE yet.

For those of you having troubles with the previously proposed solution, note that an inital ampersand will only work if you are already supplying other arguments to the URL. The first argument must have an initial question mark: http://www.example.com?first=foo&second=bar

Maintain the aspect ratio of a div with CSS

As stated in here on w3schools.com and somewhat reiterated in this accepted answer, padding values as percentages (emphasis mine):

Specifies the padding in percent of the width of the containing element

Ergo, a correct example of a responsive DIV that keeps a 16:9 aspect ratio is as follows:

CSS

.parent {
    position: relative;
    width: 100%;
}
.child {
    position: relative;
    padding-bottom: calc(100% * 9 / 16);
}
.child > div {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

HTML

<div class="parent">
    <div class="child">
        <div>Aspect is kept when resizing</div>
    </div>
</div>

Demo on JSFiddle

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

You have to set classpath for mysql-connector.jar

In eclipse, use the build path

If you are developing any web app, you have to put mysql-connector to the lib folder of WEB-INF Directory of your web-app

PHP Session data not being saved

Use phpinfo() and check the session.* settings.

Maybe the information is stored in cookies and your browser does not accept cookies, something like that.

Check that first and come back with the results.

You can also do a print_r($_SESSION); to have a dump of this variable and see the content....

Regarding your phpinfo(), is the session.save_path a valid one? Does your web server have write access to this directory?

Hope this helps.

Case-insensitive search

ES6+:

let string="Stackoverflow is the BEST";
let searchstring="best";


let found = string.toLowerCase()
                  .includes(searchstring.toLowerCase());

includes() returns true if searchString appears at one or more positions or false otherwise.

Bootstrap: Use .pull-right without having to hardcode a negative margin-top

just put #login-box before <h2>Welcome</h2> will be ok.

<div class='container'>
    <div class='hero-unit'>
        <div id='login-box' class='pull-right control-group'>
            <div class='clearfix'>
                <input type='text' placeholder='Username' />
            </div>
            <div class='clearfix'>
                <input type='password' placeholder='Password' />
            </div>
            <button type='button' class='btn btn-primary'>Log in</button>
        </div>
        <h2>Welcome</h2>

        <p>Please log in</p>

    </div>
</div>

here is jsfiddle http://jsfiddle.net/SyjjW/4/

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Upgrade to PostgreSQL 9.5 or greater. If (not) exists was introduced in version 9.5.

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

This may be relevant to a certain subset of people with this issue...perhaps in a different flavor.

I was forcing an https redirect on RELEASE.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
  filters.Add(new HandleErrorAttribute());
  #if !DEBUG
  filters.Add(new RequireHttpsAttribute());
  #endif    
}

And there wasn't https enabled on my iis express. Working correctly on DEBUG

How do you run a Python script as a service in Windows?

nssm in python 3+

(I converted my .py file to .exe with pyinstaller)

nssm: as said before

  • run nssm install {ServiceName}
  • On NSSM´s console:

    path: path\to\your\program.exe

    Startup directory: path\to\your\ #same as the path but without your program.exe

    Arguments: empty

If you don't want to convert your project to .exe

  • create a .bat file with python {{your python.py file name}}
  • and set the path to the .bat file

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

My Solution was to 'Uri.parse' the File Path as String, instead of using Uri.fromFile().

String storage = Environment.getExternalStorageDirectory().toString() + "/test.txt";
File file = new File(storage);
Uri uri;
if (Build.VERSION.SDK_INT < 24) {
    uri = Uri.fromFile(file);
} else {
    uri = Uri.parse(file.getPath()); // My work-around for new SDKs, worked for me in Android 10 using Solid Explorer Text Editor as the external editor.
}
Intent viewFile = new Intent(Intent.ACTION_VIEW);
viewFile.setDataAndType(uri, "text/plain");
startActivity(viewFile);

Seems that fromFile() uses A file pointer, which I suppose could be insecure when memory addresses are exposed to all apps. But A file path String never hurt anybody, so it works without throwing FileUriExposedException.

Tested on API levels 9 to 29! Successfully opens the text file for editing in another app. Does not require FileProvider, nor the Android Support Library at all.

Difference between Static and final?

Static and final have some big differences:

Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:

public class Test{    
   public final int first = 10;
   public static int second = 20;

   public Test(){
     second = second + 1
     first = first + 1;
   }
}

The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case the problem was that i created an @Input variable with the reserved name formControl.

How can I clear the SQL Server query cache?

Note that neither DBCC DROPCLEANBUFFERS; nor DBCC FREEPROCCACHE; is supported in SQL Azure / SQL Data Warehouse.

However, if you need to reset the plan cache in SQL Azure, you can alter one of the tables in the query (for instance, just add then remove a column), this will have the side-effect of removing the plan from the cache.

I personally do this as a way of testing query performance without having to deal with cached plans.

More details about SQL Azure Procedure Cache here

c++ bool question

Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values

Java HashMap: How to get a key and value by index?

If you don't care about the actual key, a concise way to iterate over all the Map's values would be to use its values() method

Map<String, List<String>> myMap;

for ( List<String> stringList : myMap.values() ) {
    for ( String myString : stringList ) {
        // process the string here
    }
}

The values() method is part of the Map interface and returns a Collection view of the values in the map.