Programs & Examples On #Colorbar

Questions that include the use and customization of colorbars in figures

matplotlib: colorbars and its text labels

To add to tacaswell's answer, the colorbar() function has an optional cax input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')

cax.set_xlabel('data label')  # cax == cb.ax

Set Colorbar Range in matplotlib

Use the CLIM function (equivalent to CAXIS function in MATLAB):

plt.pcolor(X, Y, v, cmap=cm)
plt.clim(-4,4)  # identical to caxis([-4,4]) in MATLAB
plt.show()

Matplotlib 2 Subplots, 1 Colorbar

Shared colormap and colorbar

This is for the more complex case where the values are not just between 0 and 1; the cmap needs to be shared instead of just using the last one.

import numpy as np
from matplotlib.colors import Normalize
import matplotlib.pyplot as plt
import matplotlib.cm as cm
fig, axes = plt.subplots(nrows=2, ncols=2)
cmap=cm.get_cmap('viridis')
normalizer=Normalize(0,4)
im=cm.ScalarMappable(norm=normalizer)
for i,ax in enumerate(axes.flat):
    ax.imshow(i+np.random.random((10,10)),cmap=cmap,norm=normalizer)
    ax.set_title(str(i))
fig.colorbar(im, ax=axes.ravel().tolist())
plt.show()

matplotlib colorbar in each subplot

Try to use the func below to add colorbar:

def add_colorbar(mappable):
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import matplotlib.pyplot as plt
    last_axes = plt.gca()
    ax = mappable.axes
    fig = ax.figure
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    cbar = fig.colorbar(mappable, cax=cax)
    plt.sca(last_axes)
    return cbar

Then you codes need to be modified as:

fig , ( (ax1,ax2) , (ax3,ax4)) = plt.subplots(2, 2,sharex = True,sharey=True)
z1_plot = ax1.scatter(x,y,c = z1,vmin=0.0,vmax=0.4)
add_colorbar(z1_plot)

CSS - display: none; not working

Try add this to your css

#tfl {
display: none !important;
}

Why is  appearing in my HTML?

"I don't know why this is happening"

Well I have just run into a possible cause:-) Your HTML page is being assembled from separate files. Perhaps you have files which only contain the body or banner portion of your final page. Those files contain a BOM (0xFEFF) marker. Then as part of the merge process you are running HTML tidy or xmllint over the final merged HTML file.

That will cause it!

UITableView example for Swift

//    UITableViewCell set Identify "Cell"
//    UITableView Name is  tableReport

UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet weak var tableReport: UITableView!  

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 5;
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            cell.textLabel?.text = "Report Name"
            return cell;
        }
}

Data access object (DAO) in Java

Don't get confused with too many explanations. DAO: From the name itself it means Accessing Data using Object. DAO is separated from other Business Logic.

Running PHP script from the command line

UPDATE:

After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?

Look for lines that start with LoadModule php... There probably are configuration files/directories named mods or something like that, start from there.

You could also check output from php -r 'phpinfo();' | grep php and compare lines to phpinfo(); from web server.

To run php interactively:

(so you can paste/write code in the console)

php -a

To make it parse file and output to console:

php -f file.php

Parse file and output to another file:

php -f file.php > results.html

Do you need something else?

To run only small part, one line or like, you can use:

php -r '$x = "Hello World"; echo "$x\n";'

If you are running linux then do man php at console.

if you need/want to run php through fpm, use cli fcgi

SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"

where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.

Java's L number (long) specification

These are literals and are described in section 3.10 of the Java language spec.

Adding a default value in dropdownlist after binding with database

design

<asp:DropDownList ID="ddlArea" DataSourceID="ldsArea" runat="server" ondatabound="ddlArea_DataBound" />

codebehind

protected void ddlArea_DataBound(object sender, EventArgs e)
{
    ddlArea.Items.Insert(0, new ListItem("--Select--", "0"));
}

Parsing GET request parameters in a URL that contains another URL

$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);

$my_url outputs:

http://localhost/test.php?id=http%3A%2F%2Fgoogle.com%2F%3Fvar%3D234%26key%3D234

So now you can get this value using $_GET['id'] or $_REQUEST['id'] (decoded).

echo urldecode($_GET["id"]);

Output

http://google.com/?var=234&key=234

To get every GET parameter:

foreach ($_GET as $key=>$value) {
  echo "$key = " . urldecode($value) . "<br />\n";
  }

$key is GET key and $value is GET value for $key.

Or you can use alternative solution to get array of GET params

$get_parameters = array();
if (isset($_SERVER['QUERY_STRING'])) {
  $pairs = explode('&', $_SERVER['QUERY_STRING']);
  foreach($pairs as $pair) {
    $part = explode('=', $pair);
    $get_parameters[$part[0]] = sizeof($part)>1 ? urldecode($part[1]) : "";
    }
  }

$get_parameters is same as url decoded $_GET.

Auto-center map with multiple markers in Google Maps API v3

This work for me in Angular 9:

  import {GoogleMap, GoogleMapsModule} from "@angular/google-maps";
  @ViewChild('Map') Map: GoogleMap; /* Element Map */

  locations = [
   { lat: 7.423568, lng: 80.462287 },
   { lat: 7.532321, lng: 81.021187 },
   { lat: 6.117010, lng: 80.126269 }
  ];

  constructor() {
   var bounds = new google.maps.LatLngBounds();
    setTimeout(() => {
     for (let u in this.locations) {
      var marker = new google.maps.Marker({
       position: new google.maps.LatLng(this.locations[u].lat, 
       this.locations[u].lng),
      });
      bounds.extend(marker.getPosition());
     }

     this.Map.fitBounds(bounds)
    }, 200)
  }

And it automatically centers the map according to the indicated positions.

Result:

enter image description here

Generate a random number in the range 1 - 10

The correct version of hythlodayr's answer.

-- ERROR:  operator does not exist: double precision % integer
-- LINE 1: select (trunc(random() * 10) % 10) + 1

The output from trunc has to be converted to INTEGER. But it can be done without trunc. So it turns out to be simple.

select (random() * 9)::INTEGER + 1

Generates an INTEGER output in range [1, 10] i.e. both 1 & 10 inclusive.

For any number (floats), see user80168's answer. i.e just don't convert it to INTEGER.

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

I've added the <%% literal tag delimiter as an answer to this because of its obscurity. This will tell erb not to interpret the <% part of the tag which is necessary for js apps like displaying chart.js tooltips etc.

Update (Fixed broken link)

Everything about ERB can now be found here: https://puppet.com/docs/puppet/5.3/lang_template_erb.html#tags

How do you do a deep copy of an object in .NET?

I have a simpler idea. Use LINQ with a new selection.

public class Fruit
{
  public string Name {get; set;}
  public int SeedCount {get; set;}
}

void SomeMethod()
{
  List<Fruit> originalFruits = new List<Fruit>();
  originalFruits.Add(new Fruit {Name="Apple", SeedCount=10});
  originalFruits.Add(new Fruit {Name="Banana", SeedCount=0});

  //Deep Copy
  List<Fruit> deepCopiedFruits = from f in originalFruits
              select new Fruit {Name=f.Name, SeedCount=f.SeedCount};
}

Extracting double-digit months and days from a Python date

Look at the types of those properties:

In [1]: import datetime

In [2]: d = datetime.date.today()

In [3]: type(d.month)
Out[3]: <type 'int'>

In [4]: type(d.day)
Out[4]: <type 'int'>

Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.

If you want leading zeroes, you'll have to format them one way or another. For that you have several options:

In [5]: '{:02d}'.format(d.month)
Out[5]: '03'

In [6]: '%02d' % d.month
Out[6]: '03'

In [7]: d.strftime('%m')
Out[7]: '03'

In [8]: f'{d.month:02d}'
Out[8]: '03'

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

All you need to do is to put arp into diferrent group.

Default:

-rwxr-xr-x 1 root root 48K 2008-11-11 18:11 /usr/sbin/arp*

With command:

sudo chown root:www-data /usr/sbin/arp

you will get:

-rwxr-xr-x 1 root www-data 48K 2008-11-11 18:11 /usr/sbin/arp*

And because apache is a daemon running under the user www-data, it's now able to execute this command.

So if you now use a PHP script, e.g.:

<?php
$mac = system('arp -an');
echo $mac;
?>

you will get the output of linux arp -an command.

What data type to use for hashed password field and what length?

It really depends on the hashing algorithm you're using. The length of the password has little to do with the length of the hash, if I remember correctly. Look up the specs on the hashing algorithm you are using, run a few tests, and truncate just above that.

How to correctly iterate through getElementsByClassName

 <!--something like this--> 
<html>
<body>



<!-- i've used for loop...this pointer takes current element to apply a 
 particular change on it ...other elements take change by else condition 
-->  


<div class="classname" onclick="myFunction(this);">first</div>  
<div class="classname" onclick="myFunction(this);">second</div>


<script>
function myFunction(p) {
 var x = document.getElementsByClassName("classname");
 var i;
 for (i = 0; i < x.length; i++) {
    if(x[i] == p)
    {
x[i].style.background="blue";
    }
    else{
x[i].style.background="red";
    }
}
}


</script>
<!--this script will only work for a class with onclick event but if u want 
to use all class of same name then u can use querySelectorAll() ...-->




var variable_name=document.querySelectorAll('.classname');
for(var i=0;i<variable_name.length;i++){
variable_name[i].(--your option--);
}



 <!--if u like to divide it on some logic apply it inside this for loop 
 using your nodelist-->

</body>
</html>

Understanding slice notation

I got a little frustrated in not finding an online source, or Python documentation that describes precisely what slicing does.

I took Aaron Hall's suggestion, read the relevant parts of the CPython source code, and wrote some Python code that performs slicing similarly to how it's done in CPython. I've tested my code in Python 3 on millions of random tests on integer lists.

You may find the references in my code to the relevant functions in CPython helpful.

# Return the result of slicing list x
# See the part of list_subscript() in listobject.c that pertains
# to when the indexing item is a PySliceObject
def slicer(x, start=None, stop=None, step=None):
    # Handle slicing index values of None, and a step value of 0.
    # See PySlice_Unpack() in sliceobject.c, which
    # extracts start, stop, step from a PySliceObject.
    maxint = 10000000       # A hack to simulate PY_SSIZE_T_MAX
    if step == None:
        step = 1
    elif step == 0:
        raise ValueError('slice step cannot be zero')

    if start == None:
        start = maxint if step < 0 else 0
    if stop == None:
        stop = -maxint if step < 0 else maxint

    # Handle negative slice indexes and bad slice indexes.
    # Compute number of elements in the slice as slice_length.
    # See PySlice_AdjustIndices() in sliceobject.c
    length = len(x)
    slice_length = 0

    if start < 0:
        start += length
        if start < 0:
            start = -1 if step < 0 else 0
    elif start >= length:
        start = length - 1 if step < 0 else length

    if stop < 0:
        stop += length
        if stop < 0:
            stop = -1 if step < 0 else 0
    elif stop > length:
        stop = length - 1 if step < 0 else length

    if step < 0:
        if stop < start:
            slice_length = (start - stop - 1) // (-step) + 1
    else:
        if start < stop:
            slice_length = (stop - start - 1) // step + 1

    # Cases of step = 1 and step != 1 are treated separately
    if slice_length <= 0:
        return []
    elif step == 1:
        # See list_slice() in listobject.c
        result = []
        for i in range(stop - start):
            result.append(x[i+start])
        return result
    else:
        result = []
        cur = start
        for i in range(slice_length):
            result.append(x[cur])
            cur += step
        return result

PHP cURL error code 60

First, we need download this certificate root certificate bundle:

https://curl.haxx.se/ca/cacert.pem

Move this file to somewhere such as to PHP folder in Wamp/Xampp folder.

Then edit your "php.ini" :

curl.cainfo ="C:/path/to/your/cacert.pem"

and

openssl.cafile="C:/path/to/your/cacert.pem"

IMPORTANT:

Be sure that you open the "php.ini" file directly by your Window Explorer. (in my case: “C:\DevPrograms\wamp64\bin\php\php5.6.25\php.ini”).

Don't use the shortcut to "php.ini" in the Wamp/Xampp icon's menu in the System Tray. This shortcut didn't work in some cases I faced.

After saving "php.ini" you don't need to "Restart All Services" in Wamp icon or close/re-open CMD.

Try with " var_dump(openssl_get_cert_locations()); " and look at line : ["ini_cafile"]=> string(40) "C:/path/to/your/cacert.pem"

Done.

Difference between a User and a Login in SQL Server

A "Login" grants the principal entry into the SERVER.

A "User" grants a login entry into a single DATABASE.

One "Login" can be associated with many users (one per database).

Each of the above objects can have permissions granted to it at its own level. See the following articles for an explanation of each

What is the difference between a cer, pvk, and pfx file?

I actually came across something like this not too long ago... check it out over on msdn (see the first answer)

in summary:

.cer - certificate stored in the X.509 standard format. This certificate contains information about the certificate's owner... along with public and private keys.

.pvk - files are used to store private keys for code signing. You can also create a certificate based on .pvk private key file.

.pfx - stands for personal exchange format. It is used to exchange public and private objects in a single file. A pfx file can be created from .cer file. Can also be used to create a Software Publisher Certificate.

I summarized the info from the page based on the suggestion from the comments.

How can I delete a query string parameter in JavaScript?

If you have a polyfill for URLSearchParams or simply don't have to support Internet Explorer, that's what I would use like suggested in other answers here. If you don't want to depend on URLSearchParams, that's how I would do it:

function removeParameterFromUrl(url, parameter) {
  const replacer = (m, p1, p2) => (p1 === '?' && p2 === '&' ? '?' : p2 || '')
  return url.replace(new RegExp(`([?&])${parameter}=[^&#]+([&#])?`), replacer)
}

It will replace a parameter preceded by ? (p1) and followed by & (p2) with ? to make sure the list of parameters still starts with a question mark, otherwise, it will replace it with the next separator (p2): could be &, or #, or undefined which falls back to an empty string.

Python Save to file

file = open('Failed.py', 'w')
file.write('whatever')
file.close()

Here is a more pythonic version, which automatically closes the file, even if there was an exception in the wrapped block:

with open('Failed.py', 'w') as file:
    file.write('whatever')

How to convert char to int?

I'm surprised nobody has mentioned the static method built right into System.Char...

int val = (int)Char.GetNumericValue('8');
// val == 8

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

sudo tar -cvjSf folder.tar.bz2 folder

Or from the same folder try

sudo tar -cvjSf folder.tar.bz2 *

Cheers!

How do I create a transparent Activity on Android?

I wanted to add to this a little bit as I am a new Android developer as well. The accepted answer is great, but I did run into some trouble. I wasn't sure how to add in the color to the colors.xml file. Here is how it should be done:

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <color name="class_zero_background">#7f040000</color>
     <color name="transparent">#00000000</color>
</resources>

In my original colors.xml file I had the tag "drawable":

<drawable name="class_zero_background">#7f040000</drawable>

And so I did that for the color as well, but I didn't understand that the "@color/" reference meant look for the tag "color" in the XML. I thought that I should mention this as well to help anyone else out.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

Setting project's SDK in IntelliJ (File > Project Structure > Project:Project SDK) worked for me

How to dynamically change a web page's title?

Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.

Javamail Could not convert socket to TLS GMail

After a full day of search, I disabled Avast for 10 minutes and Windows Firewall (important) and everything started working!

This was my error:

Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  

Here is how to fix the issue in Avast 19.8.2393 by adding an exclusion to SMTP port 587 (or whichever port your application uses):

  1. Open Avast

  2. Click on 'Settings'

  3. Click on 'Troubleshooting' and then 'Open old settings'

enter image description here

  1. Click again on 'Troubleshooting', scroll down to 'Redirect settings' and delete the port that your app uses.

enter image description here

In my case, I just removed 587 from SMTP ports.

Now I am able to use Avast and also have my Windows Firewall switched on (no need to add additional exclusion for the Firewall).

Here are my application.properties e-mail properties:

###### I am using a Google App Password which I generated in my Gmail Security settings ######
spring.mail.host = smtp.gmail.com
spring.mail.port = 587
spring.mail.protocol = smtp
spring.mail.username = gmail account
spring.mail.password = password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

Tomcat Servlet: Error 404 - The requested resource is not available

You definitely need to map your servlet onto some URL. If you use Java EE 6 (that means at least Servlet API 3.0) then you can annotate your servlet like

@WebServlet(name="helloServlet", urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
     //rest of the class

Then you can just go to the localhost:8080/yourApp/hello and the value should be displayed. In case you can't use Servlet 3.0 API than you need to register this servlet into web.xml file like

<servlet>
    <servlet-name>helloServlet</servlet-name>
    <servlet-class>crunch.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>helloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

How can you find the height of text on an HTML canvas?

I solved this problem straitforward - using pixel manipulation.

Here is graphical answer:

Here is code:

    function textHeight (text, font) {

    var fontDraw = document.createElement("canvas");

    var height = 100;
    var width = 100;

    // here we expect that font size will be less canvas geometry
    fontDraw.setAttribute("height", height);
    fontDraw.setAttribute("width", width);

    var ctx = fontDraw.getContext('2d');
    // black is default
    ctx.fillRect(0, 0, width, height);
    ctx.textBaseline = 'top';
    ctx.fillStyle = 'white';
    ctx.font = font;
    ctx.fillText(text/*'Eg'*/, 0, 0);

    var pixels = ctx.getImageData(0, 0, width, height).data;

    // row numbers where we first find letter end where it ends 
    var start = -1;
    var end = -1;

    for (var row = 0; row < height; row++) {
        for (var column = 0; column < width; column++) {

            var index = (row * width + column) * 4;

            // if pixel is not white (background color)
            if (pixels[index] == 0) {
                // we havent met white (font color) pixel
                // on the row and the letters was detected
                if (column == width - 1 && start != -1) {
                    end = row;
                    row = height;
                    break;
                }
                continue;
            }
            else {
                // we find top of letter
                if (start == -1) {
                    start = row;
                }
                // ..letters body
                break;
            }

        }

    }
   /*
    document.body.appendChild(fontDraw);
    fontDraw.style.pixelLeft = 400;
    fontDraw.style.pixelTop = 400;
    fontDraw.style.position = "absolute";
   */

    return end - start;

}

make script execution to unlimited

You'll have to set it to zero. Zero means the script can run forever. Add the following at the start of your script:

ini_set('max_execution_time', 0);

Refer to the PHP documentation of max_execution_time

Note that:

set_time_limit(0);

will have the same effect.

Assigning more than one class for one event

Have you tried this:

 function doSomething() {
     if ($(this).hasClass('clickedTag')){
         // code here
     } else {
         // and here
     }
 }

 $('.tag1, .tag2').click(doSomething);

jQuery: If this HREF contains

Try this:

$("a").each(function() {
    if ($('[href$="?"]', this).length()) {
        alert("Contains questionmark");
    }
});

nvm keeps "forgetting" node in new terminal session

Try nvm alias default. For example:

$ nvm alias default 0.12.7

This sets the default node version in your shell. Then verify that the change persists by closing the shell window, opening a new one, then: node --version

How to Configure SSL for Amazon S3 bucket

Custom domain SSL certs were just added today for $600/cert/month. Sign up for your invite below: http://aws.amazon.com/cloudfront/custom-ssl-domains/

Update: SNI customer provided certs are now available for no additional charge. Much cheaper than $600/mo, and with XP nearly killed off, it should work well for most use cases.

@skalee AWS has a mechanism for achieving what the poster asks for, "implement SSL for an Amazon s3 bucket", it's called CloudFront. I'm reading "implement" as "use my SSL certs," not "just put an S on the HTTP URL which I'm sure the OP could have surmised.

Since CloudFront costs exactly the same as S3 ($0.12/GB), but has a ton of additional features around SSL AND allows you to add your own SNI cert at no additional cost, it's the obvious fix for "implementing SSL" on your domain.

Calling onclick on a radiobutton list using javascript

The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.

The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.

This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.

Accessing session from TWIG template

A simple trick is to define the $_SESSION array as a global variable. For that, edit the core.php file in the extension folder by adding this function :

public function getGlobals() {
    return array(
        'session'   => $_SESSION,
    ) ;
}

Then, you'll be able to acces any session variable as :

{{ session.username }}

if you want to access to

$_SESSION['username']

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

class Globals {
   static String ouch = "I'm global.."
}

println Globals.ouch

Convert objective-c typedef to its string equivalent

I made a sort of mix of all solutions found on this page to create mine, it's a kind of object oriented enum extension or something.

In fact if you need more than just constants (i.e. integers), you probably need a model object (We're all talking about MVC, right?)

Just ask yourself the question before using this, am I right, don't you, in fact, need a real model object, initialized from a webservice, a plist, an SQLite database or CoreData ?

Anyway here comes the code (MPI is for "My Project Initials", everybody use this or their name, it seems) :

MyWonderfulType.h :

typedef NS_ENUM(NSUInteger, MPIMyWonderfulType) {
    MPIMyWonderfulTypeOne = 1,
    MPIMyWonderfulTypeTwo = 2,
    MPIMyWonderfulTypeGreen = 3,
    MPIMyWonderfulTypeYellow = 4,
    MPIMyWonderfulTypePumpkin = 5
};

#import <Foundation/Foundation.h>

@interface MyWonderfulType : NSObject

+ (NSString *)displayNameForWonderfulType:(MPIMyWonderfulType)wonderfulType;
+ (NSString *)urlForWonderfulType:(MPIMyWonderfulType)wonderfulType;

@end

And MyWonderfulType.m :

#import "MyWonderfulType.h"

@implementation MyWonderfulType

+ (NSDictionary *)myWonderfulTypeTitles
{
    return @{
             @(MPIMyWonderfulTypeOne) : @"One",
             @(MPIMyWonderfulTypeTwo) : @"Two",
             @(MPIMyWonderfulTypeGreen) : @"Green",
             @(MPIMyWonderfulTypeYellow) : @"Yellow",
             @(MPIMyWonderfulTypePumpkin) : @"Pumpkin"
             };
}

+ (NSDictionary *)myWonderfulTypeURLs
{
    return @{
             @(MPIMyWonderfulTypeOne) : @"http://www.theone.com",
             @(MPIMyWonderfulTypeTwo) : @"http://www.thetwo.com",
             @(MPIMyWonderfulTypeGreen) : @"http://www.thegreen.com",
             @(MPIMyWonderfulTypeYellow) : @"http://www.theyellow.com",
             @(MPIMyWonderfulTypePumpkin) : @"http://www.thepumpkin.com"
             };
}

+ (NSString *)displayNameForWonderfulType:(MPIMyWonderfulType)wonderfulType {
    return [MPIMyWonderfulType myWonderfulTypeTitles][@(wonderfulType)];
}

+ (NSString *)urlForWonderfulType:(MPIMyWonderfulType)wonderfulType {
    return [MPIMyWonderfulType myWonderfulTypeURLs][@(wonderfulType)];
}


@end

How to replace text in a column of a Pandas dataframe?

Replace all commas with underscore in the column names

data.columns= data.columns.str.replace(' ','_',regex=True)

android get all contacts

Get contacts info , photo contacts , photo uri and convert to Class model

1). Sample for Class model :

    public class ContactModel {
        public String id;
        public String name;
        public String mobileNumber;
        public Bitmap photo;
        public Uri photoURI;
    }

2). get Contacts and convert to Model

     public List<ContactModel> getContacts(Context ctx) {
        List<ContactModel> list = new ArrayList<>();
        ContentResolver contentResolver = ctx.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(),
                            ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));

                    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
                    Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

                    Bitmap photo = null;
                    if (inputStream != null) {
                        photo = BitmapFactory.decodeStream(inputStream);
                    }
                    while (cursorInfo.moveToNext()) {
                        ContactModel info = new ContactModel();
                        info.id = id;
                        info.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        info.mobileNumber = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        info.photo = photo;
                        info.photoURI= pURI;
                        list.add(info);
                    }

                    cursorInfo.close();
                }
            }
            cursor.close();
        }
        return list;
    }

HTML/Javascript: how to access JSON data loaded in a script tag with src set

It would appear this is not possible, or at least not supported.

From the HTML5 specification:

When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used.

How to redirect output of an already running process

I collected some information on the internet and prepared the script that requires no external tool: See my response here. Hope it's helpful.

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

How do I determine k when using k-means clustering?

If you use MATLAB, any version since 2013b that is, you can make use of the function evalclusters to find out what should the optimal k be for a given dataset.

This function lets you choose from among 3 clustering algorithms - kmeans, linkage and gmdistribution.

It also lets you choose from among 4 clustering evaluation criteria - CalinskiHarabasz, DaviesBouldin, gap and silhouette.

What are the differences between Visual Studio Code and Visual Studio?

Out of the box, Visual Studio can compile, run and debug programs.

Out of the box, Visual Studio Code can do practically nothing but open and edit text files. It can be extended to compile, run, and debug, but you will need to install other software. It's a PITA.

If you're looking for a Notepad replacement, Visual Studio Code is your man.

If you want to develop and debug code without fiddling for days with settings and installing stuff, then Visual Studio is your man.

How can I get the SQL of a PreparedStatement?

I'm using Oralce 11g and couldn't manage to get the final SQL from the PreparedStatement. After reading @Pascal MARTIN answer I understand why.

I just abandonned the idea of using PreparedStatement and used a simple text formatter which fitted my needs. Here's my example:

//I jump to the point after connexion has been made ...
java.sql.Statement stmt = cnx.createStatement();
String sqlTemplate = "SELECT * FROM Users WHERE Id IN ({0})";
String sqlInParam = "21,34,3434,32"; //some random ids
String sqlFinalSql = java.text.MesssageFormat(sqlTemplate,sqlInParam);
System.out.println("SQL : " + sqlFinalSql);
rsRes = stmt.executeQuery(sqlFinalSql);

You figure out the sqlInParam can be built dynamically in a (for,while) loop I just made it plain simple to get to the point of using the MessageFormat class to serve as a string template formater for the SQL query.

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

i have tried this one and it worked for me. hope it works for others too.

  1. Open build.gradle module file
  2. downgrade you sdkversion from 25 to 24 or 23
  3. add 'multiDexEnabled true'
  4. comment this line : compile 'com.android.support:appcompat-v7:25.1.0' (if it's in 'dependencies')
  5. Sync your project and ready to go.

Here i have attached screenshot to explain things. Go through this steps

happy to help.

thanks.

Is nested function a good approach when required by only one function?

I found this question because I wanted to pose a question why there is a performance impact if one uses nested functions. I ran tests for the following functions using Python 3.2.5 on a Windows Notebook with a Quad Core 2.5 GHz Intel i5-2530M processor

def square0(x):
    return x*x

def square1(x):
    def dummy(y):
        return y*y
    return x*x

def square2(x):
    def dummy1(y):
        return y*y
    def dummy2(y):
        return y*y
    return x*x

def square5(x):
    def dummy1(y):
        return y*y
    def dummy2(y):
        return y*y
    def dummy3(y):
        return y*y
    def dummy4(y):
        return y*y
    def dummy5(y):
        return y*y
    return x*x

I measured the following 20 times, also for square1, square2, and square5:

s=0
for i in range(10**6):
    s+=square0(i)

and got the following results

>>> 
m = mean, s = standard deviation, m0 = mean of first testcase
[m-3s,m+3s] is a 0.997 confidence interval if normal distributed

square? m     s       m/m0  [m-3s ,m+3s ]
square0 0.387 0.01515 1.000 [0.342,0.433]
square1 0.460 0.01422 1.188 [0.417,0.503]
square2 0.552 0.01803 1.425 [0.498,0.606]
square5 0.766 0.01654 1.979 [0.717,0.816]
>>> 

square0 has no nested function, square1 has one nested function, square2 has two nested functions and square5 has five nested functions. The nested functions are only declared but not called.

So if you have defined 5 nested funtions in a function that you don't call then the execution time of the function is twice of the function without a nested function. I think should be cautious when using nested functions.

The Python file for the whole test that generates this output can be found at ideone.

Submitting a multidimensional array via POST with php

I made a function which handles arrays as well as single GET or POST values

function subVal($varName, $default=NULL,$isArray=FALSE ){ // $isArray toggles between (multi)array or single mode

    $retVal = "";
    $retArray = array();

    if($isArray) {
        if(isset($_POST[$varName])) {
            foreach ( $_POST[$varName] as $var ) {  // multidimensional POST array elements
                $retArray[]=$var;
            }
        }
        $retVal=$retArray;
    }

    elseif (isset($_POST[$varName]) )  {  // simple POST array element
        $retVal = $_POST[$varName];
    }

    else {
        if (isset($_GET[$varName]) ) {
            $retVal = $_GET[$varName];    // simple GET array element
        }
        else {
            $retVal = $default;
        }
    }

    return $retVal;

}

Examples:

$curr_topdiameter = subVal("topdiameter","",TRUE)[3];
$user_name = subVal("user_name","");

Initialise a list to a specific length in Python

In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n to pre-allocate the length you want.

Slides available as PPT or via Google

The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.

Can I run a 64-bit VMware image on a 32-bit machine?

Yes, you can. I have a 64-bit Debian running in VMware on Windows XP 32-Bit. As long as you set the Guest to use two processors, it will work just fine.

c# write text on bitmap

Bitmap bmp = new Bitmap("filename.bmp");

RectangleF rectf = new RectangleF(70, 90, 90, 50);

Graphics g = Graphics.FromImage(bmp);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);

g.Flush();

image.Image=bmp;

Error in <my code> : object of type 'closure' is not subsettable

You don't define the vector, url, before trying to subset it. url is also a function in the base package, so url[i] is attempting to subset that function... which doesn't make sense.

You probably defined url in your prior R session, but forgot to copy that code to your script.

How to escape a JSON string to have it in a URL?

Answer given by Delan is perfect. Just adding to it - incase someone wants to name the parameters or pass multiple JSON strings separately - the below code could help!

JQuery

var valuesToPass = new Array(encodeURIComponent(VALUE_1), encodeURIComponent(VALUE_2), encodeURIComponent(VALUE_3), encodeURIComponent(VALUE_4));

data = {elements:JSON.stringify(valuesToPass)}

PHP

json_decode(urldecode($_POST('elements')));

Hope this helps!

How to install requests module in Python 3.4, instead of 2.7

i was facing same issue in beautiful soup , I solved this issue by this command , your issue will also get rectified . You are unable to install requests in python 3.4 because your python libraries are not updated . use this command apt-get install python3-requests Just run it will ask you to add 222 MB space in your hard disk , just press Y and wait for completing process, after ending up whole process . check your problem will be resolved.

Google Play app description formatting

Include emojis; copy and paste them to the description:

http://getemoji.com

How to install JSON.NET using NuGet?

I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..

enter image description here

getting file size in javascript

If you could access the file system of a user with javascript, image the bad that could happen.

However, you can use File System Object but this will work only in IE:

http://bytes.com/topic/javascript/answers/460516-check-file-size-javascript

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

Jquery Change Height based on Browser Size/Resize

Building on Chad's answer, you also want to add that function to the onload event to ensure it is resized when the page loads as well.

jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);

function resizeFrame() 
{
    var h = $(window).height();
    var w = $(window).width();
    $("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
}

Multiple select statements in Single query

SELECT t1.credit, 
       t2.debit 
FROM   (SELECT Sum(c.total_amount) AS credit 
        FROM   credit c 
        WHERE  c.status = "a") AS t1, 
       (SELECT Sum(d.total_amount) AS debit 
        FROM   debit d 
        WHERE  d.status = "a") AS t2 

Send form data with jquery ajax json

You can use serialize() like this:

$.ajax({
  cache: false,
  url: 'test.php',
  data: $('form').serialize(),
  datatype: 'json',
  success: function(data) {

  }
});

Retrieve filename from file descriptor in C

As Tyler points out, there's no way to do what you require "directly and reliably", since a given FD may correspond to 0 filenames (in various cases) or > 1 (multiple "hard links" is how the latter situation is generally described). If you do still need the functionality with all the limitations (on speed AND on the possibility of getting 0, 2, ... results rather than 1), here's how you can do it: first, fstat the FD -- this tells you, in the resulting struct stat, what device the file lives on, how many hard links it has, whether it's a special file, etc. This may already answer your question -- e.g. if 0 hard links you will KNOW there is in fact no corresponding filename on disk.

If the stats give you hope, then you have to "walk the tree" of directories on the relevant device until you find all the hard links (or just the first one, if you don't need more than one and any one will do). For that purpose, you use readdir (and opendir &c of course) recursively opening subdirectories until you find in a struct dirent thus received the same inode number you had in the original struct stat (at which time if you want the whole path, rather than just the name, you'll need to walk the chain of directories backwards to reconstruct it).

If this general approach is acceptable, but you need more detailed C code, let us know, it won't be hard to write (though I'd rather not write it if it's useless, i.e. you cannot withstand the inevitably slow performance or the possibility of getting != 1 result for the purposes of your application;-).

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

Well that is Because of

you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception. and the one way is to encrypt that data Directly into the String.

look this. Try and u will be able to resolve this

public static String decrypt(String encryptedData) throws Exception {

    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    String decordedValue = new BASE64Decoder().decodeBuffer(encryptedData).toString().trim();
    System.out.println("This is Data to be Decrypted" + decordedValue);
    return decordedValue;
}

hope that will help.

MAX(DATE) - SQL ORACLE

Try:

SELECT MEMBSHIP_ID
  FROM user_payment
 WHERE user_id=1 
ORDER BY paym_date = (select MAX(paym_date) from user_payment and user_id=1);

Or:

SELECT MEMBSHIP_ID
FROM (
  SELECT MEMBSHIP_ID, row_number() over (order by paym_date desc) rn
      FROM user_payment
     WHERE user_id=1 )
WHERE rn = 1

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

Google API authentication: Not valid origin for the client

Credentials do not work if API is not enabled. In my case the next steps were needed:

  1. Go to https://console.developers.google.com/apis/library
  2. Enter 'People'
  3. From the result choose 'Google People API'
  4. Click 'Enable'

Print an ArrayList with a for-each loop

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

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

Can we define min-margin and max-margin, max-padding and min-padding in css?

@vigilante_stark's answer worked for me. It can be used to set a minimum "approximately" fixed margin in pixels. But in a responsive layout, when the width of the page is increasing margin can be increased by a percentage according to the given percentage as well. I used it as follows

example-class{
  margin: 0 calc(20px + 5%) 0 0;
}

Send Outlook Email Via Python?

Other than win32, if your company had set up you web outlook, you can also try PYTHON REST API, which is officially made by Microsoft. (https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations)

How to change text color of cmd with windows batch script every 1 second

echo off & cls
title   never buy these they're so easy to make... hmu for source code             

    -%pinging:IP%-
color 0D

echo =================================================================
echo i flex on my unhittable ovh, you flex on an easy to hit trash ovh
echo =================================================================
set /p IP=Enter IP:
:top
title :: this skid's boutta get slammed FeelsGoodMan ::    -%pinging:IP%-
PING -n 1 %IP% | FIND "TTL="
IF ERRORLEVEL (echo stop flexing on ovh's i down them with ease, mine on the other hand is unhittable.):
set /a num=(%Random%%%9)+1
color %num%IP   ping -t 2 0 10 127.0.0.1 >nul
GoTo top

This is an ip pinging that has custom timed out messages for if something such as a website or server is down, also, can use for if booting people offline, I can make a tool that opens files and individual pingers dependant on your input, and a built in geo-location tool.

C++ create string of text and variables

See also boost::format:

#include <boost/format.hpp>

std::string var = (boost::format("somtext %s sometext %s") % somevar % somevar).str();

Why is lock(this) {...} bad?

Because if people can get at your object instance (ie: your this) pointer, then they can also try to lock that same object. Now they might not be aware that you're locking on this internally, so this may cause problems (possibly a deadlock)

In addition to this, it's also bad practice, because it's locking "too much"

For example, you might have a member variable of List<int>, and the only thing you actually need to lock is that member variable. If you lock the entire object in your functions, then other things which call those functions will be blocked waiting for the lock. If those functions don't need to access the member list, you'll be causing other code to wait and slow down your application for no reason at all.

Hide Twitter Bootstrap nav collapse on click

I posted a solution that works with Aurelia here: https://stackoverflow.com/a/41465905/6466378

The problem is you can not just add data-toggle="collapse" and data-target="#navbar" to your a elements. And jQuery does not work wenn in an Aurelia or Angular environment.

The best solution for me was to create a custom attribute that listens to the corresponding media query and adds in the data-toggle="collapse"attribute if desired:

<a href="#" ... collapse-toggle-if-less768 data-target="#navbar"> ...

The custom attribute with Aurelia looks like this:

_x000D_
_x000D_
import {autoinject} from 'aurelia-framework';_x000D_
_x000D_
@autoinject_x000D_
export class CollapseToggleIfLess768CustomAttribute {_x000D_
  element: Element;_x000D_
_x000D_
  constructor(element: Element) {_x000D_
    this.element = element;_x000D_
    var mql = window.matchMedia("(min-width: 768px)");_x000D_
    mql.addListener((mediaQueryList: MediaQueryList) => this.handleMediaChange(mediaQueryList));_x000D_
    this.handleMediaChange(mql);_x000D_
  }_x000D_
_x000D_
  handleMediaChange(mediaQueryList: MediaQueryList) {_x000D_
    if (mediaQueryList.matches) {_x000D_
      var dataToggle = this.element.attributes.getNamedItem("data-toggle");_x000D_
      if (dataToggle) {_x000D_
        this.element.attributes.removeNamedItem("data-toggle");_x000D_
      }_x000D_
    } else {_x000D_
      var dataToggle = this.element.attributes.getNamedItem("data-toggle");_x000D_
      if (!dataToggle) {_x000D_
        var dataToggle = document.createAttribute("data-toggle");_x000D_
        dataToggle.value = "collapse";_x000D_
        this.element.attributes.setNamedItem(dataToggle);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Difference between arguments and parameters in Java

In java, there are two types of parameters, implicit parameters and explicit parameters. Explicit parameters are the arguments passed into a method. The implicit parameter of a method is the instance that the method is called from. Arguments are simply one of the two types of parameters.

Prevent RequireJS from Caching Required Scripts

I took this snippet from AskApache and put it into a seperate .conf file of my local Apache webserver (in my case /etc/apache2/others/preventcaching.conf):

<FilesMatch "\.(html|htm|js|css)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</FilesMatch>

For development this works fine with no need to change the code. As for the production, I might use @dvtoever's approach.

Changing text color of menu item in navigation drawer

You can also define a custom theme that is derived from your base theme:

<android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/nav_view"
        app:headerLayout="@layout/nav_view_header"
        app:menu="@layout/nav_view_menu"
        app:theme="@style/MyTheme.NavMenu" />

and then in your styles.xml file:

  <style name="MyTheme.NavMenu" parent="MyTheme.Base">
    <item name="android:textColorPrimary">@color/yourcolor</item>
  </style>

you can also apply more attributes to the custom theme.

JPA OneToMany not deleting child

You can try this:

@OneToOne(orphanRemoval=true) or @OneToMany(orphanRemoval=true).

Get value of Span Text

_x000D_
_x000D_
var span_Text = document.getElementById("span_Id").innerText;_x000D_
_x000D_
console.log(span_Text)
_x000D_
<span id="span_Id">I am the Text </span>
_x000D_
_x000D_
_x000D_

Babel 6 regeneratorRuntime is not defined

I had this problem in Chrome. Similar to RienNeVaPlu?s’s answer, this solved it for me:

npm install --save-dev regenerator-runtime

Then in my code:

import 'regenerator-runtime/runtime';

Happy to avoid the extra 200 kB from babel-polyfill.

changing default x range in histogram matplotlib

import matplotlib.pyplot as plt


...


plt.xlim(xmin=6.5, xmax = 12.5)

Get the closest number out of an array

I don't know if I'm supposed to answer an old question, but as this post appears first on Google searches, I hoped that you would forgive me adding my solution & my 2c here.

Being lazy, I couldn't believe that the solution for this question would be a LOOP, so I searched a bit more and came back with filter function:

var myArray = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
var myValue = 80;

function BiggerThan(inArray) {
  return inArray > myValue;
}

var arrBiggerElements = myArray.filter(BiggerThan);
var nextElement = Math.min.apply(null, arrBiggerElements);
alert(nextElement);

That's all !

Custom events in jQuery?

Here is how I author custom events:

var event = jQuery.Event('customEventName');
$(element).trigger(event);

Granted, you could simply do

$(element).trigger('eventname');

But the way I wrote allows you to detect whether the user has prevented default or not by doing

var prevented = event.isDefaultPrevented();

This allows you to listen to your end-user's request to stop processing a particular event, such as if you click a button element in a form but do not want to the form to post if there is an error.


I then usually listen to events like so

$(element).off('eventname.namespace').on('eventname.namespace', function () {
    ...
});

Once again, you could just do

$(element).on('eventname', function () {
    ...
});

But I've always found this somewhat unsafe, especially if you're working in a team.

There is nothing wrong with the following:

$(element).on('eventname', function () {});

However, assume that I need to unbind this event for whatever reason (imagine a disabled button). I would then have to do

$(element).off('eventname', function () {});

This will remove all eventname events from $(element). You cannot know whether someone in the future will also bind an event to that element, and you'd be inadvertently unbinding that event as well

The safe way to avoid this is to namespace your events by doing

$(element).on('eventname.namespace', function () {});

Lastly, you may have noticed that the first line was

$(element).off('eventname.namespace').on('eventname.namespace', ...)

I personally always unbind an event before binding it just to make sure that the same event handler never gets called multiple times (imagine this was the submit button on a payment form and the event had been bound 5 times)

Change the Blank Cells to "NA"

I recently ran into similar issues, and this is what worked for me.

If the variable is numeric, then a simple df$Var[df$Var == ""] <- NA should suffice. But if the variable is a factor, then you need to convert it to the character first, then replace "" cells with the value you want, and convert it back to factor. So case in point, your Sex variable, I assume it would be a factor and if you want to replace the empty cell, I would do the following:

df$Var <- as.character(df$Var)
df$Var[df$Var==""] <- NA
df$Var <- as.factor(df$Var)

Get all dates between two dates in SQL Server

DECLARE @FirstDate DATE = '2018-01-01'
DECLARE @LastDate Date = '2018-12-31'
DECLARE @tbl TABLE(ID INT IDENTITY(1,1) PRIMARY KEY,CurrDate date)
INSERT @tbl VALUES( @FirstDate)
WHILE @FirstDate < @LastDate
BEGIN
SET @FirstDate = DATEADD( day,1, @FirstDate)
INSERT @tbl VALUES( @FirstDate)
END
INSERT @tbl VALUES( @LastDate) 

SELECT * FROM @tbl

Simple proof that GUID is not unique

If the number of UUID being generated follows Moore's law, the impression of never running out of GUID in the foreseeable future is false.

With 2 ^ 128 UUIDs, it will only take 18 months * Log2(2^128) ~= 192 years, before we run out of all UUIDs.

And I believe (with no statistical proof what-so-ever) in the past few years since mass adoption of UUID, the speed we are generating UUID is increasing way faster than Moore's law dictates. In other words, we probably have less than 192 years until we have to deal with UUID crisis, that's a lot sooner than end of universe.

But since we definitely won't be running them out by the end of 2012, we'll leave it to other species to worry about the problem.

Is there an effective tool to convert C# code to Java code?

We have an application that we need to maintain in both C# and Java. Since we actively maintain this product, a one-time port wasn't an option. We investigated Net2Java and the Mainsoft tools, but neither met our requirements (Net2Java for lack of robustness and Mainsoft for cost and lack of source code conversion). We created our own tool called CS2J that runs as part of our nightly build script and does a very effective port of our C# code to Java. Right now it is precisely good enough to translate our application, but would have a long way to go before being considered a comprehensive tool. We've licensed the technology to a few parties with similar needs and we're toying with the idea of releasing it publicly, but our core business just keeps us too busy these days.

How to convert a string to an integer in JavaScript?

Here is the easiest solution

let myNumber = "123" | 0;

More easy solution

let myNumber = +"123";

How do I set a variable to the output of a command in Bash?

This is another way and is good to use with some text editors that are unable to correctly highlight every intricate code you create:

read -r -d '' str < <(cat somefile.txt)
echo "${#str}"
echo "$str"

How do I make the first letter of a string uppercase in JavaScript?

Using prototypes

String.prototype.capitalize = function () {
    return this.charAt(0) + this.slice(1).toLowerCase();
  }

or Using functions

function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

How to change users in TortoiseSVN

Replace the line in htpasswd file:

Go to: http://www.htaccesstools.com/htpasswd-generator-windows/

(If the link is expired, search another generator from google.com.)

Enter your username and password. The site will generate an encrypted line. Copy that line and replace it with the previous line in the file "repo/htpasswd".

You might also need to Clear the 'Authentication data' from TortoiseSVN ? Settings ? Saved Data.

How do I simulate a hover with a touch in touch enabled browsers?

Try this:

<script>
document.addEventListener("touchstart", function(){}, true);
</script>

And in your CSS:

element:hover, element:active {
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-user-select: none;
-webkit-touch-callout: none /*only to disable context menu on long press*/
}

With this code you don't need an extra .hover class!

How to parse freeform street/postal address out of text, and into components

There are many street address parsers. They come in two basic flavors - ones that have databases of place names and street names, and ones that don't.

A regular expression street address parser can get up to about a 95% success rate without much trouble. Then you start hitting the unusual cases. The Perl one in CPAN, "Geo::StreetAddress::US", is about that good. There are Python and Javascript ports of that, all open source. I have an improved version in Python which moves the success rate up slightly by handling more cases. To get the last 3% right, though, you need databases to help with disambiguation.

A database with 3-digit ZIP codes and US state names and abbreviations is a big help. When a parser sees a consistent postal code and state name, it can start to lock on to the format. This works very well for the US and UK.

Proper street address parsing starts from the end and works backwards. That's how the USPS systems do it. Addresses are least ambiguous at the end, where country names, city names, and postal codes are relatively easy to recognize. Street names can usually be isolated. Locations on streets are the most complex to parse; there you encounter things such as "Fifth Floor" and "Staples Pavillion". That's when a database is a big help.

How to remove duplicates from Python list and keep order?

A list can be sorted and deduplicated using built-in functions:

myList = sorted(set(myList))
  • set is a built-in function for Python >= 2.3
  • sorted is a built-in function for Python >= 2.4

YYYY-MM-DD format date in shell script

You can set date as environment variable and later u can use it

setenv DATE `date "+%Y-%m-%d"`
echo "----------- ${DATE} -------------"

or

DATE =`date "+%Y-%m-%d"`
echo "----------- ${DATE} -------------"

How to add images to README.md on GitHub?

It's much simpler than that.

Just upload your image to the repository root, and link to the filename without any path, like so:

![Screenshot](screenshot.png)

Load vs. Stress testing

-> Testing the app with maximum number of user and input is defined as load testing. While testing the app with more than maximum number of user and input is defined as stress testing.

->In Load testing we measure the system performance based on a volume of users. While in Stress testing we measure the breakpoint of a system.

->Load Testing is testing the application for a given load requirements which may include any of the following criteria:

 .Total number of users.

 .Response Time

 .Through Put

Some parameters to check State of servers/application.

-> While stress testing is testing the application for unexpected load. It includes

 .Vusers

 .Think-Time

Example:

If an app is build for 500 users, then for load testing we check up to 500 users and for stress testing we check greater than 500.

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

In Swift 4.2 and Xcode 10.1:

If you want to get the friends list from Facebook, you need to submit your app for review in Facebook. See some of the Login Permissions:

Login Permissions

Here are the two steps:

1) First your app status is must be in Live

2) Get required permissions form Facebook.

1) Enable our app status live:

  1. Go to the apps page and select your app

    https://developers.facebook.com/apps/

  2. Select status in the top right in Dashboard.

    Enter image description here

  3. Submit privacy policy URL

    Enter image description here

  4. Select category

    Enter image description here

  5. Now our app is in Live status.

    Enter image description here

One step is completed.

2) Submit our app for review:

  1. First send required requests.

    Example: user_friends, user_videos, user_posts, etc.

    Enter image description here

  2. Second, go to the Current Request page

    Enter image description here

    Example: user_events

  3. Submit all details

    Enter image description here

  4. Like this submit for all requests (user_friends , user_events, user_videos, user_posts, etc.).

  5. Finally submit your app for review.

    If your review is accepted from Facebook's side, you are now eligible to read contacts, etc.

How to change the server port from 3000?

You can change it in the webpack.dev.js file in config folder.

Fastest way to update 120 Million records

set rowcount 1000000
Update table set int_field = -1 where int_field<>-1

see how fast that takes, adjust and repeat as necessary

How to obtain image size using standard Python class (without using external library)?

Here's a way to get dimensions of a png file without needing a third-party module. From http://coreygoldberg.blogspot.com/2013/01/python-verify-png-file-and-get-image.html

import struct

def get_image_info(data):
    if is_png(data):
        w, h = struct.unpack('>LL', data[16:24])
        width = int(w)
        height = int(h)
    else:
        raise Exception('not a png image')
    return width, height

def is_png(data):
    return (data[:8] == '\211PNG\r\n\032\n'and (data[12:16] == 'IHDR'))

if __name__ == '__main__':
    with open('foo.png', 'rb') as f:
        data = f.read()

    print is_png(data)
    print get_image_info(data)

When you run this, it will return:

True
(x, y)

And another example that includes handling of JPEGs as well: http://markasread.net/post/17551554979/get-image-size-info-using-pure-python-code

SVN upgrade working copy

On MacOS:

  1. Get the latest compiled SVN client binaries from here.
  2. Install.
  3. Add binaries to path (the last installation screen explains how).
  4. Open terminal and run the following command on your project directory:

    svn upgrade

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

While not elegant, works for me in certain situations.

Controller

if (RedirectToPage)
    return PartialView("JavascriptRedirect", new JavascriptRedirectModel("http://www.google.com"));
else
   ... return regular ajax partialview

Model

    public JavascriptRedirectModel(string location)
    {
        Location = location;
    }

    public string Location { get; set; }

/Views/Shared/JavascriptRedirect.cshtml

@model Models.Shared.JavascriptRedirectModel

<script type="text/javascript">
    window.location = '@Model.Location';
</script>

Setting default value for TypeScript object passed as argument

Actually, there appears to now be a simple way. The following code works in TypeScript 1.5:

function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
  const name = first + ' ' + last;
  console.log(name);
}

sayName({ first: 'Bob' });

The trick is to first put in brackets what keys you want to pick from the argument object, with key=value for any defaults. Follow that with the : and a type declaration.

This is a little different than what you were trying to do, because instead of having an intact params object, you have instead have dereferenced variables.

If you want to make it optional to pass anything to the function, add a ? for all keys in the type, and add a default of ={} after the type declaration:

function sayName({first='Bob',last='Smith'}: {first?: string; last?: string}={}){
    var name = first + " " + last;
    alert(name);
}

sayName();

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

Try putting the following in the environment variables for the scheme under run(debug)

OS_ACTIVITY_MODE = disable

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

Session state can only be used when enableSessionState is set to true either in a configuration

Session State may be broken if you have the following in Web.Config:

<httpModules>
  <clear/>
</httpModules>

If this is the case, you may want to comment out such section, and you won't need any other changes to fix this issue.

Iterating Through a Dictionary in Swift

Arrays are ordered collections but dictionaries and sets are unordered collections. Thus you can't predict the order of iteration in a dictionary or a set.

Read this article to know more about Collection Types: Swift Programming Language

The module was expected to contain an assembly manifest

In my case, I was using InstallUtil.exe which was causing an error. To install the .Net Core service in window best way to use sc command.

More information here Exe installation throwing error The module was expected to contain an assembly manifest .Net Core

Open fancybox from function

...
<div class="img_file" style="background-image: url('/upload/test/14120330.jpg')" data-img="/upload/test/14120330.jpg"></div>
<div class="img_file" style="background-image: url('/upload/test/14120330.jpg')" data-img="/upload/test/14120330.jpg"></div>
...
if($(".img_file[data-img]").length) {
                var imgs_slider_img = [];
                $(".img_file[data-img]").each(function(i) {
                    imgs_slider_img.push({
                        href:$(this).attr('data-img')
                    });
                    $(this).attr('data-index-img', i);
                }).on("click", function(e) {
                    e.preventDefault();
                    $.fancybox.open(imgs_slider_img, {
                         index: $(this).attr('data-index-img'),
                         padding: 0,
                         margin: 0,
                         prevEffect: 'elastic',
                         nextEffect: 'elastic',
                         maxWidth: '90%',
                         maxHeight: '90%',
                         autoWidth: true,
                         autoHeight: true
                    });
                });
            }
...

Can I use if (pointer) instead of if (pointer != NULL)?

Question is answered, but I would like to add my points.

I will always prefer if(pointer) instead of if(pointer != NULL) and if(!pointer) instead of if(pointer == NULL):

  • It is simple, small
  • Less chances to write a buggy code, suppose if I misspelled equality check operator == with =
    if(pointer == NULL) can be misspelled if(pointer = NULL) So I will avoid it, best is just if(pointer).
    (I also suggested some Yoda condition in one answer, but that is diffrent matter)

  • Similarly for while (node != NULL && node->data == key), I will simply write while (node && node->data == key) that is more obvious to me (shows that using short-circuit).

  • (may be stupid reason) Because NULL is a macro, if suppose some one redefine by mistake with other value.

In jQuery, what's the best way of formatting a number to 2 decimal places?

If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.

<script type="text/javascript">

    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );

    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });

</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

How to prompt for user input and read command-line arguments

If it's a 3.x version then just simply use:

variantname = input()

For example, you want to input 8:

x = input()
8

x will equal 8 but it's going to be a string except if you define it otherwise.

So you can use the convert command, like:

a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07

How to uncheck checked radio button

try this

_x000D_
_x000D_
var radio_button=false;_x000D_
$('.radio-button').on("click", function(event){_x000D_
  var this_input=$(this);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.attr('checked1','11')_x000D_
  } else {_x000D_
    this_input.attr('checked1','22')_x000D_
  }_x000D_
  $('.radio-button').prop('checked', false);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.prop('checked', false);_x000D_
    this_input.attr('checked1','22')_x000D_
  } else {_x000D_
    this_input.prop('checked', true);_x000D_
    this_input.attr('checked1','11')_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
_x000D_
_x000D_

Header and footer in CodeIgniter

Yes.

Create a file called template.php in your views folder.

The contents of template.php:

$this->load->view('templates/header');
$this->load->view($v);
$this->load->view('templates/footer');

Then from your controller you can do something like:

$d['v'] = 'body';
$this->load->view('template', $d);

This is actually a very simplistic version of how I personally load all of my views. If you take this idea to the extreme, you can make some interesting modular layouts:

Consider if you create a view called init.php that contains the single line:

$this->load->view('html');

Now create the view html.php with contents:

<!DOCTYPE html>
<html lang="en">
    <? $this->load->view('head'); ?>
    <? $this->load->view('body'); ?>
</html>

Now create a view head.php with contents:

<head>
<title><?= $title;?></title>
<base href="<?= site_url();?>">
<link rel="shortcut icon" href='favicon.ico'>
<script type='text/javascript'>//Put global scripts here...</script>
<!-- ETC ETC... DO A BUNCH OF OTHER <HEAD> STUFF... -->
</head>

And a body.php view with contents:

<body>
    <div id="mainWrap">
        <? $this->load->view('header'); ?>
        <? //FINALLY LOAD THE VIEW!!! ?>
        <? $this->load->view($v); ?>
        <? $this->load->view('footer'); ?>
    </div>
</body>

And create header.php and footer.php views as appropriate.

Now when you call the init from the controller all the heavy lifting is done and your views will be wrapped inside <html> and <body> tags, your headers and footers will be loaded in.

$d['v'] = 'fooview'
$this->load->view('init', $d);

A formula to copy the values from a formula to another column

Copy the cell. Paste special as link. Will update with original. No formula though.

How do I combine the first character of a cell with another cell in Excel?

Personally I like the & function for this

Assuming that you are using cells A1 and A2 for John Smith

=left(a1,1) & b1

If you want to add text between, for example a period

=left(a1,1) & "." & b1

How to use timer in C?

Here's a solution I used (it needs #include <time.h>):

int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();

do {
  /*
   * Do something to busy the CPU just here while you drink a coffee
   * Be sure this code will not take more than `trigger` ms
   */

  clock_t difference = clock() - before;
  msec = difference * 1000 / CLOCKS_PER_SEC;
  iterations++;
} while ( msec < trigger );

printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
  msec/1000, msec%1000, iterations);

How do I read a file line by line in VB Script?

If anyone like me is searching to read only a specific line, example only line 18 here is the code:

filename = "C:\log.log"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

For i = 1 to 17
    f.ReadLine
Next

strLine = f.ReadLine
Wscript.Echo strLine

f.Close

location.host vs location.hostname and cross-browser compatibility?

MDN: https://developer.mozilla.org/en/DOM/window.location

It seems that you will get the same result for both, but hostname contains clear host name without brackets or port number.

How to use Chrome's network debugger with redirects

I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:

  1. Open the js console
  2. window.addEventListener("beforeunload", function() { debugger; }, false)

This will pause chrome before loading the new page by hitting a breakpoint.

Replace image src location using CSS

You could do this but it is hacky

.application-title {
   background:url("/path/to/image.png");
   /* set these dims according to your image size */
   width:500px;
   height:500px;
}

.application-title img {
   display:none;
}

Here is a working example:

http://jsfiddle.net/5tbxkzzc/

How to filter rows in pandas by regex

Using str slice

foo[foo.b.str[0]=='f']
Out[18]: 
   a    b
1  2  foo
2  3  fat

fatal error: iostream.h no such file or directory

That header doesn't exist in standard C++. It was part of some pre-1990s compilers, but it is certainly not part of C++.

Use #include <iostream> instead. And all the library classes are in the std:: namespace, for ex­am­ple std::cout.

Also, throw away any book or notes that mention the thing you said.

Detach (move) subdirectory into separate Git repository

I had exactly this problem but all the standard solutions based on git filter-branch were extremely slow. If you have a small repository then this may not be a problem, it was for me. I wrote another git filtering program based on libgit2 which as a first step creates branches for each filtering of the primary repository and then pushes these to clean repositories as the next step. On my repository (500Mb 100000 commits) the standard git filter-branch methods took days. My program takes minutes to do the same filtering.

It has the fabulous name of git_filter and lives here:

https://github.com/slobobaby/git_filter

on GitHub.

I hope it is useful to someone.

How to exclude records with certain values in sql select

SELECT SC.StoreId 
FROM StoreClients SC
WHERE SC.StoreId NOT IN (SELECT StoreId FROM StoreClients WHERE ClientId = 5)

In this way neither JOIN nor GROUP BY is necessary.

How To Launch Git Bash from DOS Command Line?

I used the info above to help create a more permanent solution. The following will create the alias sh that you can use to open Git Bash:

echo @start "" "%PROGRAMFILES%\Git\bin\sh.exe" --login > %systemroot%\sh.bat

WooCommerce - get category for product page

$product->get_categories() is deprecated since version 3.0! Use wc_get_product_category_list instead.

https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html

Extend a java class from one file in another java file

Just put the two files in the same directory. Here's an example:

Person.java

public class Person {
  public String name;

  public Person(String name) {
    this.name = name;
  }

  public String toString() {
    return name;
  }
}

Student.java

public class Student extends Person {
  public String somethingnew;

  public Student(String name) {
    super(name);
    somethingnew = "surprise!";
  }

  public String toString() {
    return super.toString() + "\t" + somethingnew;
  }

  public static void main(String[] args) {
    Person you = new Person("foo");
    Student me = new Student("boo");

    System.out.println("Your name is " + you);
    System.out.println("My name is " + me);
  }
}

Running Student (since it has the main function) yields us the desired outcome:

Your name is foo
My name is boo  surprise!

How can I set the PATH variable for javac so I can manually compile my .java works?

  1. Type cmd in program start
  2. Copy and Paste following on dos prompt

set PATH="%PATH%;C:\Program Files\Java\jdk1.6.0_18\bin"

How to do case insensitive string comparison?

Since no answer clearly provided a simple code snippet for using RegExp, here's my attempt:

function compareInsensitive(str1, str2){ 
  return typeof str1 === 'string' && 
    typeof str2 === 'string' && 
    new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2);
}

It has several advantages:

  1. Verifies parameter type (any non-string parameter, like undefined for example, would crash an expression like str1.toUpperCase()).
  2. Does not suffer from possible internationalization issues.
  3. Escapes the RegExp string.

client denied by server configuration

this worked for me..

<Location />
 Allow from all
 Order Deny,Allow
</Location>

I have included this code in my /etc/apache2/apache2.conf

How to stop a PowerShell script on the first error?

Redirecting stderr to stdout seems to also do the trick without any other commands/scriptblock wrappers although I can't find an explanation why it works that way..

# test.ps1

$ErrorActionPreference = "Stop"

aws s3 ls s3://xxx
echo "==> pass"

aws s3 ls s3://xxx 2>&1
echo "shouldn't be here"

This will output the following as expected (the command aws s3 ... returns $LASTEXITCODE = 255)

PS> .\test.ps1

An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied
==> pass

log4j vs logback

Your decision should be based on

  • your actual need for these "more features"; and
  • your expected cost of implementing the change.

You should resist the urge to change APIs just because it's "newer, shinier, better." I follow a policy of "if it's not broken, don't kick it."

If your application requires a very sophisticated logging framework, you may want to consider why.

jQuery show/hide not working

Use this

<script>
$(document).ready(function(){
    $( '.expand' ).click(function() {
        $( '.img_display_content' ).show();
    });
});
</script>

Event assigning always after Document Object Model loaded

How to pass parameters to ThreadStart method in Thread?

You could also delegate like so...

ThreadStart ts = delegate
{
      bool moreWork = DoWork("param1", "param2", "param3");
      if (moreWork) 
      {
          DoMoreWork("param1", "param2");
      }
};
new Thread(ts).Start();

How can I add a table of contents to a Jupyter / JupyterLab notebook?

As Ian already pointed out, there is a table-of-contents extension by minrk for the IPython Notebook. I had some trouble to make it work and made this IPython Notebook which semi-automatically generates the files for minrk's table of contents extension in Windows. It does not use the 'curl'-commands or links, but writes the *.js and *.css files directly into your IPython Notebook-profile-directory.

There is a section in the notebook called 'What you need to do' - follow it and have a nice floating table of contents : )

Here is an html version which already shows it: http://htmlpreview.github.io/?https://github.com/ahambi/140824-TOC/blob/master/A%20floating%20table%20of%20contents.htm

why should I make a copy of a data frame in pandas

This expands on Paul's answer. In Pandas, indexing a DataFrame returns a reference to the initial DataFrame. Thus, changing the subset will change the initial DataFrame. Thus, you'd want to use the copy if you want to make sure the initial DataFrame shouldn't change. Consider the following code:

df = DataFrame({'x': [1,2]})
df_sub = df[0:1]
df_sub.x = -1
print(df)

You'll get:

x
0 -1
1  2

In contrast, the following leaves df unchanged:

df_sub_copy = df[0:1].copy()
df_sub_copy.x = -1

How to sort in-place using the merge sort algorithm?

The critical step is getting the merge itself to be in-place. It's not as difficult as those sources make out, but you lose something when you try.

Looking at one step of the merge:

[...list-sorted...|x...list-A...|y...list-B...]

We know that the sorted sequence is less than everything else, that x is less than everything else in A, and that y is less than everything else in B. In the case where x is less than or equal to y, you just move your pointer to the start of A on one. In the case where y is less than x, you've got to shuffle y past the whole of A to sorted. That last step is what makes this expensive (except in degenerate cases).

It's generally cheaper (especially when the arrays only actually contain single words per element, e.g., a pointer to a string or structure) to trade off some space for time and have a separate temporary array that you sort back and forth between.

How to remove/ignore :hover css style on touch devices

I'm dealing with a similar problem currently.

There are two main options that occur to me immediately: (1) user-string checking, or (2) maintaining separate mobile pages using a different URL and having users choose what's better for them.

  1. If you're able to use an internet duct-tape language such as PHP or Ruby, you can check the user string of the device requesting a page, and simply serve the same content but with a <link rel="mobile.css" /> instead of the normal style.

User strings have identifying information about browser, renderer, operating system, etc. It would be up to you to decide what devices are "touch" versus non-touch. You may be able to find this information available somewhere and map it into your system.

A. If you're allowed to ignore old browsers, you just have to add a single rule to the normal, non-mobile css, namely: EDIT: Erk. After doing some experimentation, I discovered the below rule also disables the ability to follow links in webkit-browsers in addition to just causing aesthetic effects to be disabled - see http://jsfiddle.net/3nkcdeao/
As such, you'll have to be a bit more selective as to how you modify rules for the mobile case than what I show here, but it may be a helpful starting point:

* { 
    pointer-events: none !important; /* only use !important if you have to */
}

As a sidenote, disabling pointer-events on a parent and then explicitly enabling them on a child currently causes any hover-effects on the parent to become active again if a child-element enters :hover.
See http://jsfiddle.net/38Lookhp/5/

B. If you're supporting legacy web-renderers, you'll have to do a bit more work along the lines of removing any rules which set special styles during :hover. To save everyone time, you might just want to build an automated copying + seding command which you run on your standard style sheets to create the mobile versions. That would allow you to just write/update the standard code and scrub away any style-rules which use :hover for the mobile version of your pages.

  1. (I) Alternatively, simply make your users aware that you have an m.website.com for mobile devices in addition to your website.com. Though subdomaining is the most common way, you could also have some other predictable modification of a given URL to allow mobile users to access the modified pages. At that stage, you would want to be sure they don't have to modify the URL every time they navigate to another part of the site.

Again here, you may be able to just add an extra rule or two to the stylesheets or be forced to do something slightly more complicated using sed or a similar utility. It would probably be easiest to apply :not to your styling rules like div:not(.disruptive):hover {... wherein you would add class="disruptive" to elements doing annoying things for mobile users using js or the server language, instead of munging the CSS.

  1. (II) You can actually combine the first two and (if you suspect a user has wandered to the wrong version of a page) you can suggest that they switch into/out of the mobile-type display, or simply have a link somewhere which allows users to flop back and forth. As already-stated, @media queries might also be something to look use in determining what's being used to visit.

  2. (III) If you're up for a jQuery solution once you know what devices are "touch" and which aren't, you might find CSS hover not being ignored on touch-screen devices helpful.

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I did not want to install visual studio and development environment, so I have installed AspNetMVC4Setup.exe in Windows server 2016 machine and it solved the problem. The installer was downloaded from Microsoft website.

File properties of the installer

How to see query history in SQL Server Management Studio

A slightly out-of-the-box method would be to script up a solution in AutoHotKey. I use this, and it's not perfect, but works and is free. Essentially, this script assigns a hotkey to CTRL+SHIFT+R which will copy the selected SQL in SSMS (CTRL+C), save off a datestamp SQL file, and then execute the highlighted query (F5). If you aren't used to AHK scripts, the leading semicolon is a comment.

;CTRL+SHIFT+R to run a query that is first saved off
^+r::
;Copy
Send, ^c
; Set variables
EnvGet, HomeDir, USERPROFILE
FormatTime, DateString,,yyyyMMdd
FormatTime, TimeString,,hhmmss
; Make a spot to save the clipboard
FileCreateDir %HomeDir%\Documents\sqlhist\%DateString%
FileAppend, %Clipboard%, %HomeDir%\Documents\sqlhist\%DateString%\%TimeString%.sql
; execute the query
Send, {f5}
Return

The biggest limitations are that this script won't work if you click "Execute" rather than use the keyboard shortcut, and this script won't save off the whole file - just the selected text. But, you could always modify the script to execute the query, and then select all (CTRL+A) before the copy/save.

Using a modern editor with "find in files" features will let you search your SQL history. You could even get fancy and scrape your files into a SQLite3 database to query your queries.

Creating a UICollectionView programmatically

colection view exam

    #import "CollectionViewController.h"
#import "BuyViewController.h"
#import "CollectionViewCell.h"

@interface CollectionViewController ()
{
    NSArray *mobiles;
    NSArray  *costumes;
    NSArray *shoes;
    NSInteger selectpath;
    NSArray *mobilerate;
    NSArray *costumerate;
    NSArray *shoerate;
}
@end

@implementation CollectionViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = self.receivename;
    mobiles = [[NSArray alloc]initWithObjects:@"7.jpg",@"6.jpg",@"5.jpg", nil];
    costumes = [[NSArray alloc]initWithObjects:@"shirt.jpg",@"costume2.jpg",@"costume1.jpg", nil];
    shoes = [[NSArray alloc]initWithObjects:@"shoe.jpg",@"shoe1.jpg",@"shoe2.jpg", nil];
    mobilerate = [[NSArray alloc]initWithObjects:@"10000",@"11000",@"13000",nil];
    costumerate = [[NSArray alloc]initWithObjects:@"699",@"999",@"899", nil];
    shoerate = [[NSArray alloc]initWithObjects:@"599",@"499",@"300", nil];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 3;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];

    UIImageView *collectionImg = (UIImageView *)[cell viewWithTag:100];

    if ([self.receivename isEqualToString:@"Mobiles"])
    {
        collectionImg.image = [UIImage imageNamed:[mobiles objectAtIndex:indexPath.row]];
    }
    else if ([self.receivename isEqualToString:@"Costumes"])
    {
        collectionImg.image = [UIImage imageNamed:[costumes objectAtIndex:indexPath.row]];
    }
    else
    {
        collectionImg.image = [UIImage imageNamed:[shoes objectAtIndex:indexPath.row]];
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{
    selectpath = indexPath.row;
    [self performSegueWithIdentifier:@"buynow" sender:self];
}

    // In a storyboard-based application, you will often want to do a little
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"buynow"])
    {
        BuyViewController *obj = segue.destinationViewController;
        if ([self.receivename isEqualToString:@"Mobiles"])
        {
            obj.reciveimg = [mobiles objectAtIndex:selectpath];
            obj.labelrecive = [mobilerate objectAtIndex:selectpath];

        }
        else if ([self.receivename isEqualToString:@"Costumes"])
        {
            obj.reciveimg = [costumes objectAtIndex:selectpath];
            obj.labelrecive = [costumerate objectAtIndex:selectpath];
        }
        else
        {
            obj.reciveimg = [shoes objectAtIndex:selectpath];
            obj.labelrecive = [shoerate objectAtIndex:selectpath];
        }
        //     Get the new view controller using [segue destinationViewController].
        //     Pass the selected object to the new view controller.
    }
}

@end

.h file

@interface CollectionViewController :
UIViewController<UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong,nonatomic) NSString *receiveimg;
@property (strong,nonatomic) NSString *receivecostume;
@property (strong,nonatomic)NSString *receivename;

@end

Fixed page header overlaps in-page anchors

I use this approach:

/* add class="jumptarget" to all targets. */

.jumptarget::before {
  content:"";
  display:block;
  height:50px; /* fixed header height*/
  margin:-50px 0 0; /* negative fixed header height */
}

It adds an invisible element before each target. It works IE8+.

Here are more solutions: http://nicolasgallagher.com/jump-links-and-viewport-positioning/

How do I delete files programmatically on Android?

I tested this code on Nougat emulator and it worked:

In manifest add:

<application...

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

Create empty xml folder in res folder and past in the provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-path name="external_files" path="."/>
  </paths>

Then put the next snippet into your code (for instance fragment):

File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(), 
  getActivity().getApplicationContext().getPackageName() +
    ".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);

Array as session variable

Yes, PHP supports arrays as session variables. See this page for an example.

As for your second question: once you set the session variable, it will remain the same until you either change it or unset it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.

How to select the first, second, or third element with a given class name?

Perhaps using the "~" selector of CSS?

.myclass {
    background: red;
}

.myclass~.myclass {
    background: yellow;
}

.myclass~.myclass~.myclass {
    background: green;
}

See my example on jsfiddle

Http Post With Body

You can use HttpClient and HttpPost to build and send the request.

HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));

request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);

How to do a simple file search in cmd

Problem with DIR is that it will return wrong answers. If you are looking for DOC in a folder by using DIR *.DOC it will also give you the DOCX. Searching for *.HTM will also give the HTML and so on...

Playing m3u8 Files with HTML Video Tag

You can use video js library for easily play HLS video's. It allows to directly play videos

<!-- CSS  -->
 <link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">


<!-- HTML -->
<video id='hls-example'  class="video-js vjs-default-skin" width="400" height="300" controls>
<source type="application/x-mpegURL" src="http://www.streambox.fr/playlists/test_001/stream.m3u8">
</video>


<!-- JS code -->
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/ie8-version/videojs-ie8.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.14.1/videojs-contrib-hls.js"></script>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>

<script>
var player = videojs('hls-example');
player.play();
</script>

GitHub Video Js

How do I get the coordinates of a mouse click on a canvas element?

I'm not sure what's the point of all these answers that loop through parent elements and do all kinds of weird stuff.

The HTMLElement.getBoundingClientRect method is designed to to handle actual screen position of any element. This includes scrolling, so stuff like scrollTop is not needed:

(from MDN) The amount of scrolling that has been done of the viewport area (or any other scrollable element) is taken into account when computing the bounding rectangle

Normal image

The very simplest approach was already posted here. This is correct as long as no wild CSS rules are involved.

Handling stretched canvas/image

When image pixel width isn't matched by it's CSS width, you'll need to apply some ratio on pixel values:

/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/
HTMLCanvasElement.prototype.relativeCoords = function(event) {
  var x,y;
  //This is the current screen rectangle of canvas
  var rect = this.getBoundingClientRect();
  var top = rect.top;
  var bottom = rect.bottom;
  var left = rect.left;
  var right = rect.right;
  //Recalculate mouse offsets to relative offsets
  x = event.clientX - left;
  y = event.clientY - top;
  //Also recalculate offsets of canvas is stretched
  var width = right - left;
  //I use this to reduce number of calculations for images that have normal size 
  if(this.width!=width) {
    var height = bottom - top;
    //changes coordinates by ratio
    x = x*(this.width/width);
    y = y*(this.height/height);
  } 
  //Return as an array
  return [x,y];
}

As long as the canvas has no border, it works for stretched images (jsFiddle).

Handling CSS borders

If the canvas has thick border, the things get little complicated. You'll literally need to subtract the border from the bounding rectangle. This can be done using .getComputedStyle. This answer describes the process.

The function then grows up a little:

/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/
HTMLCanvasElement.prototype.relativeCoords = function(event) {
  var x,y;
  //This is the current screen rectangle of canvas
  var rect = this.getBoundingClientRect();
  var top = rect.top;
  var bottom = rect.bottom;
  var left = rect.left;
  var right = rect.right;
  //Subtract border size
  // Get computed style
  var styling=getComputedStyle(this,null);
  // Turn the border widths in integers
  var topBorder=parseInt(styling.getPropertyValue('border-top-width'),10);
  var rightBorder=parseInt(styling.getPropertyValue('border-right-width'),10);
  var bottomBorder=parseInt(styling.getPropertyValue('border-bottom-width'),10);
  var leftBorder=parseInt(styling.getPropertyValue('border-left-width'),10);
  //Subtract border from rectangle
  left+=leftBorder;
  right-=rightBorder;
  top+=topBorder;
  bottom-=bottomBorder;
  //Proceed as usual
  ...
}

I can't think of anything that would confuse this final function. See yourself at JsFiddle.

Notes

If you don't like modifying the native prototypes, just change the function and call it with (canvas, event) (and replace any this with canvas).

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

LINQ-to-SQL is a remarkable piece of technology that is very simple to use, and by and large generates very good queries to the back end. LINQ-to-EF was slated to supplant it, but historically has been extremely clunky to use and generated far inferior SQL. I don't know the current state of affairs, but Microsoft promised to migrate all the goodness of L2S into L2EF, so maybe it's all better now.

Personally, I have a passionate dislike of ORM tools (see my diatribe here for the details), and so I see no reason to favour L2EF, since L2S gives me all I ever expect to need from a data access layer. In fact, I even think that L2S features such as hand-crafted mappings and inheritance modeling add completely unnecessary complexity. But that's just me. ;-)

how to show progress bar(circle) in an activity having a listview before loading the listview with data

Are you extending ListActivity?

If so, put a circular progress dialog with the following line in your xml

<ProgressBar
android:id="@android:id/empty"
...other stuff...
/>

Now, the progress indicator will show up till you have all your listview information, and set the Adapter. At which point, it will go back to the listview, and the progress bar will go away.

What does git push -u mean?

"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull or git push without arguments. A little bit down, this article explains and demonstrates this concept.

How to remove spaces from a string using JavaScript?

_x000D_
_x000D_
var a = b = " /var/www/site/Brand new   document.docx ";_x000D_
_x000D_
console.log( a.split(' ').join('') );_x000D_
console.log( b.replace( /\s/g, '') ); 
_x000D_
_x000D_
_x000D_

Two ways of doing this!

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

How to check if string contains Latin characters only?

I'm surprised that the answers here got so many upvotes when none of them really answer the question. Here's how to make sure that ONLY LATIN characters are in a given string.

const hasOnlyLetters = !!value.match(/^[a-z]*$/i);

The !! takes transforms something that's not boolean into a boolean value. (It's exactly the same as applying a ! twice, and in fact you can use as many ! as you'd like to toggle the truthiness multiple times.)

As for the RegEx, here's the breakdown.

  • /.../i The delimiter is a / and the i means to assess the statement in a case-insensitive fashion.
  • ^...$ The ^ means to look at the very beginning of a string. The $ means to look at the end of the string, and when used together, it means to consider the entire string. You can add more to the RegEx outside of these boundaries for things like appending/prepending a required suffix or prefix.
  • [a-z]*This part says to look for all lowercase letters. (The case-insensitive modifier means that we don't need to look at uppercase letters, too.) The * at the end says that we should match whats in the brackets any number of times. That way "abc" will match instead of just "a" or "b", and so forth.

How do I pass a command line argument while starting up GDB in Linux?

Try

gdb --args InsertionSortWithErrors arg1toinsort arg2toinsort

how to stop a for loop

There are several ways to do it:

The simple Way: a sentinel variable

n = L[0][0]
m = len(A)
found = False
for i in range(m):
   if found:
      break
   for j in range(m):
     if L[i][j] != n: 
       found = True
       break

Pros: easy to understand Cons: additional conditional statement for every loop

The hacky Way: raising an exception

n = L[0][0]
m = len(A)

try:
  for x in range(3):
    for z in range(3):
     if L[i][j] != n: 
       raise StopIteration
except StopIteration:
   pass

Pros: very straightforward Cons: you use Exception outside of their semantic

The clean Way: make a function

def is_different_value(l, elem, size):
  for x in range(size):
    for z in range(size):
     if l[i][j] != elem: 
       return True
  return False

if is_different_value(L, L[0][0], len(A)):
  print "Doh"

pros: much cleaner and still efficient cons: yet feels like C

The pythonic way: use iteration as it should be

def is_different_value(iterable):
  first = iterable[0][0]
  for l in iterable:
    for elem in l:
       if elem != first: 
          return True
  return False

if is_different_value(L):
  print "Doh"

pros: still clean and efficient cons: you reinvdent the wheel

The guru way: use any():

def is_different_value(iterable):
  first = iterable[0][0]
  return  any(any((cell != first for cell in col)) for elem in iterable)):

if is_different_value(L):
  print "Doh"

pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you

How to get logged-in user's name in Access vba?

In a Form, Create a text box, with in text box properties select data tab

Default value =CurrentUser()

Current source "select table field name"

It will display current user log on name in text box / label as well as saves the user name in the table field

How to close existing connections to a DB

This should disconnect everyone else, and leave you as the only user:

alter database YourDb set single_user with rollback immediate

Note: Don't forget

alter database YourDb set MULTI_USER

after you're done!

Get domain name

Why are you using WMI? Can't you use the standard .NET functionality?

System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

How to verify a method is called two times with mockito verify()

Using the appropriate VerificationMode:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

Visual Studio can't 'see' my included header files

Try adding the header file to your project's files. (right click on project -> add existing file).

How to execute the start script with Nodemon

I have a TypeScript file called "server.ts", The following npm scripts configures Nodemon and npm to start my app and monitor for any changes on TypeScript files:

"start": "nodemon -e ts  --exec \"npm run myapp\"",
"myapp": "tsc -p . && node server.js",

I already have Nodemon on dependencies. When I run npm start, it will ask Nodemon to monitor its files using the -e switch and then it calls the myapp npm script which is a simple combination of transpiling the typescript files and then starting the resulting server.js. When I change the TypeScript file, because of -e switch the same cycle happens and new .js files will be generated and executed.

C++ Matrix Class

For a matrix class, you want to stay away from overloading the [] operator.
See C++ FAQ 13.10

Also, search the web for some freeware Matrix classes. Worst case, they can give you guidance. Best case, less software that you have to write and debug.

How to catch a specific SqlException error?

If you are looking for a better way to handle SQLException, there are a couple things you could do. First, Spring.NET does something similar to what you are looking for (I think). Here is a link to what they are doing:

http://springframework.net/docs/1.2.0/reference/html/dao.html

Also, instead of looking at the message, you could check the error code (sqlEx.Number). That would seem to be a better way of identifying which error occurred. The only problem is that the error number returned might be different for each database provider. If you plan to switch providers, you will be back to handling it the way you are or creating an abstraction layer that translates this information for you.

Here is an example of a guy who used the error code and a config file to translate and localize user-friendly error messages:

https://web.archive.org/web/20130731181042/http://weblogs.asp.net/guys/archive/2005/05/20/408142.aspx

Saving images in Python at a very high quality

Okay, I found spencerlyon2's answer working. However, in case anybody would find himself/herself not knowing what to do with that one line, I had to do it this way:

beingsaved = plt.figure()

# Some scatter plots
plt.scatter(X_1_x, X_1_y)
plt.scatter(X_2_x, X_2_y)

beingsaved.savefig('destination_path.eps', format='eps', dpi=1000)

How much faster is C++ than C#?

The garbage collection is the main reason Java# CANNOT be used for real-time systems.

  1. When will the GC happen?

  2. How long will it take?

This is non-deterministic.

How to Read from a Text File, Character by Character in C++

Re: textFile.getch(), did you make that up, or do you have a reference that says it should work? If it's the latter, get rid of it. If it's the former, don't do that. Get a good reference.

char ch;
textFile.unsetf(ios_base::skipws);
textFile >> ch;

Converting XML to JSON using Python?

There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to do with the results.

That being said, Python's standard library has several modules for parsing XML (including DOM, SAX, and ElementTree). As of Python 2.6, support for converting Python data structures to and from JSON is included in the json module.

So the infrastructure is there.

How to count the number of occurrences of a character in an Oracle varchar value?

here is a solution that will function for both characters and substrings:

select (length('a') - nvl(length(replace('a','b')),0)) / length('b')
  from dual

where a is the string in which you search the occurrence of b

have a nice day!

Pandas: Appending a row to a dataframe and specify its index label

I shall refer to the same sample of data as posted in the question:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))

Running this code will give you

The original data frame is:

          A         B         C         D
0  0.494824 -0.328480  0.818117  0.100290
1  0.239037  0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856  0.359811 -0.345560
3 -0.070814 -0.394711  0.081697 -1.178845
4 -1.638063  1.498027 -0.609325  0.882594
5 -0.510217  0.500475  1.039466  0.187076
6  1.116529  0.912380  0.869323  0.119459
7 -1.046507  0.507299 -0.373432 -1.024795

Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append returns a view of the dataframe and does not modify its contents. Following is the code:

row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))

Following would be the new output:

The new data frame is:

           A          B          C          D
0   0.494824  -0.328480   0.818117   0.100290
1   0.239037   0.954912  -0.186825  -0.651935
2  -1.818285  -0.158856   0.359811  -0.345560
3  -0.070814  -0.394711   0.081697  -1.178845
4  -1.638063   1.498027  -0.609325   0.882594
5  -0.510217   0.500475   1.039466   0.187076
6   1.116529   0.912380   0.869323   0.119459
7  -1.046507   0.507299  -0.373432  -1.024795
3  10.000000  20.000000  30.000000  40.000000

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

The following works perfectly:-

if(isset($_POST['signup'])){
$username=mysqli_real_escape_string($connect,$_POST['username']);
$email=mysqli_real_escape_string($connect,$_POST['email']);
$pass1=mysqli_real_escape_string($connect,$_POST['pass1']);
$pass2=mysqli_real_escape_string($connect,$_POST['pass2']);

Now, the $connect is my variable containing my connection to the database. You only left out the connection variable. Include it and it shall work perfectly.

Hide div element when screen size is smaller than a specific size

The easiest approach I know of is using onresize() func:

   window.onresize = function(event) {
        ...
    }

Here is a fiddle for it

Checking password match while typing

if we use bootstrap our text will be green or red depending on the result

HTML

<div class="col-12 col-md-6 col-lg-4 mb-3">
            <label class="form-group d-block mb-0">
        <span class="text-secondary d-block font-weight-semibold mb-1">New Password</span>
<input type="password" id="txtNewPassword" class="form-control">     
        </label>
        </div>
        <div class="col-12 col-md-6 col-lg-4 mb-3">
            <label class="form-group d-block mb-0">
        <span class="text-secondary d-block font-weight-semibold mb-1">Confirm Password
        </span>
        <input class="form-control" type="password" id="txtConfirmPassword" onkeyup="checkPasswordMatch();">   
            </label>
        </div>
        <div class="registrationFormAlert" id="divCheckPasswordMatch"></div>

CSS

.text-success {
    color: #28a745;
}
.text-danger {
    color: #dc3545;
}

JS

function checkPasswordMatch() {
        var password = $("#txtNewPassword").val();
        var confirmPassword = $("#txtConfirmPassword").val();

        if (password != confirmPassword)
            $("#divCheckPasswordMatch").html("Passwords do not match!").addClass('text-danger').removeClass('text-success');

        else
            $("#divCheckPasswordMatch").html("Passwords match.").addClass('text-success').removeClass('text-danger');
    }

How do I deal with special characters like \^$.?*|+()[{ in my regex?

I think the easiest way to match the characters like

\^$.?*|+()[

are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")

This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

indexOf and lastIndexOf in PHP?

<?php
// sample array
$fruits3 = [
    "iron",
    1,
    "ascorbic",
    "potassium",
    "ascorbic",
    2,
    "2",
    "1",
];

// Let's say we are looking for the item "ascorbic", in the above array

//a PHP function matching indexOf() from JS
echo(array_search("ascorbic", $fruits3, true)); //returns "2"

// a PHP function matching lastIndexOf() from JS world
function lastIndexOf($needle, $arr)
{
    return array_search($needle, array_reverse($arr, true), true);
}

echo(lastIndexOf("ascorbic", $fruits3)); //returns "4"

// so these (above) are the two ways to run a function similar to indexOf and lastIndexOf()

Clone an image in cv2 python

Using python 3 and opencv-python version 4.4.0, the following code should work:

img_src = cv2.imread('image.png')
img_clone = img_src.copy()

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

Careful as target might not work with all browsers, it works well with Chrome, but I reckon Firefox (or IE/Edge, can't remember) is a bit different and uses srcElement. I usually do something like

var t = ev.srcElement || ev.target;

thus leading to

$(document).ready(function() {
    $("a").click(function(ev) {
        // get target depending on what API's in use
        var t = ev.srcElement || ev.target;

        alert(t.id+" and "+$(t).attr('class'));
    });
});

Thx for the nice answers!

CSS position absolute full width problem

I don't know if this what you want but try to remove overflow: hidden from #wrap

How to check if a registry value exists using C#?

Of course, "Fagner Antunes Dornelles" is correct in its answer. But it seems to me that it is worth checking the registry branch itself in addition, or be sure of the part that is exactly there.

For example ("dirty hack"), i need to establish trust in the RMS infrastructure, otherwise when i open Word or Excel documents, i will be prompted for "Active Directory Rights Management Services". Here's how i can add remote trust to me servers in the enterprise infrastructure.

foreach (var strServer in listServer)
{
    try
    {
        RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
        if (regCurrentUser == null)
            throw new ApplicationException("Not found registry SubKey ...");
        if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
            throw new ApplicationException("Not found value in SubKey ...");
    }
    catch (ApplicationException appEx)
    {
        Console.WriteLine(appEx);
        try
        {
            RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
            RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
            newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
        }
        catch(Exception ex)
        {
            Console.WriteLine($"{ex} Pipec kakoito ...");
        }
    }
}

How do I connect C# with Postgres?

If you want an recent copy of npgsql, then go here

http://www.npgsql.org/

This can be installed via package manager console as

PM> Install-Package Npgsql

CSS horizontal centering of a fixed div?

The answers here are outdated. Now you can easily use a CSS3 transform without hardcoding a margin. This works on all elements, including elements with no width or dynamic width.

Horizontal center:

left: 50%;
transform: translateX(-50%);

Vertical center:

top: 50%;
transform: translateY(-50%);

Both horizontal and vertical:

left: 50%;
top: 50%;
transform: translate(-50%, -50%);

Compatibility is not an issue: http://caniuse.com/#feat=transforms2d

Ping site and return result in PHP

Another option (if you need/want to ping instead of send an HTTP request) is the Ping class for PHP. I wrote it for just this purpose, and it lets you use one of three supported methods to ping a server (some servers/environments only support one of the three methods).

Example usage:

require_once('Ping/Ping.php');
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
  print 'Latency is ' . $latency . ' ms';
}
else {
  print 'Host could not be reached.';
}

Refused to load the script because it violates the following Content Security Policy directive

The probable reason why you get this error is likely because you've added the /build folder to your .gitignore file or generally haven't checked it into Git.

So when you Git push Heroku master, the build folder you're referencing don't get pushed to Heroku. And that's why it shows this error.

That's the reason it works properly locally, but not when you deployed to Heroku.

Create Test Class in IntelliJ

Use @Test annotation on one of the test methods or annotate your test class with @RunWith(JMockit.class) if using jmock. Intellij should identify that as test class & enable navigation. Also make sure junit plugin is enabled.

How to run two jQuery animations simultaneously?

While it's true that consecutive calls to animate will give the appearance they are running at the same time, the underlying truth is they're distinct animations running very close to parallel.

To insure the animations are indeed running at the same time use:

$(function() {
    $('#first').animate({..., queue: 'my-animation'});
    $('#second').animate({..., queue: 'my-animation'}).dequeue('my-animation');
});

Further animations can be added to the 'my-animation' queue and all can be initiated provided the last animation dequeue's them.

Cheers, Anthony

How to make a copy of an object in C#

You can use MemberwiseClone

obj myobj2 = (obj)myobj.MemberwiseClone();

The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj are of value types.

If you own the source code, you can also implement ICloneable

Convert iterator to pointer?

here it is, obtaining a reference to the coresponding pointer of an iterator use :

example:

string my_str= "hello world";

string::iterator it(my_str.begin());

char* pointer_inside_buffer=&(*it); //<--

[notice operator * returns a reference so doing & on a reference will give you the address].

How do I use NSTimer?

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timerCalled) userInfo:nil repeats:NO];

-(void)timerCalled
{
     NSLog(@"Timer Called");
     // Your Code
}

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

Run JavaScript code on window close or page refresh?

Trying this in React, if the function does not gets executed try wrapping it in an IIFE like this:


  window.onbeforeunload = (function () {
    alert('GrrrR!!!')
    return null;
  })()

how to attach url link to an image?

"How to attach url link to an image?"

You do it like this:

<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>

See it in action.

What does -> mean in Python function definitions?

These are function annotations covered in PEP 3107. Specifically, the -> marks the return function annotation.

Examples:

>>> def kinetic_energy(m:'in KG', v:'in M/S')->'Joules': 
...    return 1/2*m*v**2
... 
>>> kinetic_energy.__annotations__
{'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}

Annotations are dictionaries, so you can do this:

>>> '{:,} {}'.format(kinetic_energy(20,3000),
      kinetic_energy.__annotations__['return'])
'90,000,000.0 Joules'

You can also have a python data structure rather than just a string:

>>> rd={'type':float,'units':'Joules','docstring':'Given mass and velocity returns kinetic energy in Joules'}
>>> def f()->rd:
...    pass
>>> f.__annotations__['return']['type']
<class 'float'>
>>> f.__annotations__['return']['units']
'Joules'
>>> f.__annotations__['return']['docstring']
'Given mass and velocity returns kinetic energy in Joules'

Or, you can use function attributes to validate called values:

def validate(func, locals):
    for var, test in func.__annotations__.items():
        value = locals[var]
        try: 
            pr=test.__name__+': '+test.__docstring__
        except AttributeError:
            pr=test.__name__   
        msg = '{}=={}; Test: {}'.format(var, value, pr)
        assert test(value), msg

def between(lo, hi):
    def _between(x):
            return lo <= x <= hi
    _between.__docstring__='must be between {} and {}'.format(lo,hi)       
    return _between

def f(x: between(3,10), y:lambda _y: isinstance(_y,int)):
    validate(f, locals())
    print(x,y)

Prints

>>> f(2,2) 
AssertionError: x==2; Test: _between: must be between 3 and 10
>>> f(3,2.1)
AssertionError: y==2.1; Test: <lambda>