Programs & Examples On #C++filt

Command-line utility to demangle C++ and Java symbols

Clear Application's Data Programmatically

If you want a less verbose hack:

void deleteDirectory(String path) {
  Runtime.getRuntime().exec(String.format("rm -rf %s", path));
}

How to disable XDebug

Find your php.ini and look for XDebug.

Set xdebug autostart to false

xdebug.remote_autostart=0  
xdebug.remote_enable=0

Disable your profiler

xdebug.profiler_enable=0

Note that there can be a performance loss even with xdebug disabled but loaded. To disable loading of the extension itself, you need to comment it in your php.ini. Find an entry looking like this:

zend_extension = "/path/to/php_xdebug.dll"

and put a ; to comment it, e.g. ;zend_extension = ….

Check out this post XDebug, how to disable remote debugging for single .php file?

How to remove specific object from ArrayList in Java?

In general an object can be removed in two ways from an ArrayList (or generally any List), by index (remove(int)) and by object (remove(Object)).

In this particular scenario: Add an equals(Object) method to your ArrayTest class. That will allow ArrayList.remove(Object) to identify the correct object.

There can be only one auto column

My MySQL says "Incorrect table definition; there can be only one auto column and it must be defined as a key" So when I added primary key as below it started working:

CREATE TABLE book (
   id INT AUTO_INCREMENT NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL,
   primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

How to find if a given key exists in a C++ std::map

Use map::find

if ( m.find("f") == m.end() ) {
  // not found
} else {
  // found
}

What is .htaccess file?

Htaccess is a configuration file of apache which is used to make changes in the configuration on a directory basis. Htaccess file is used to do changes in functions and features of the apache server. Htaccess is used to rewrite the URL. It is used to make site address protected. Also to restrict IP addresses so on particular IP address site will not be opened

Installing PG gem on OS X - failure to build native extension

I tried everything for hours but the following finally fixed it (I'm on OS X 10.9.4):

  1. Install Xcode command line tools (Apple Developer site)
  2. brew uninstall postgresql
  3. brew install postgresql
  4. ARCHFLAGS="-arch x86_64" gem install pg

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

if you use Bootstrap 2.2.1 then maybe is this what you are looking for.

Sample file index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <link href="Content/bootstrap.min.css" rel="stylesheet" />_x000D_
    <link href="Content/Site.css" rel="stylesheet" />_x000D_
</head>_x000D_
<body>_x000D_
    <menu>_x000D_
        <div class="navbar navbar-default navbar-fixed-top">_x000D_
            <div class="container">_x000D_
                <div class="navbar-header">_x000D_
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                    </button>_x000D_
                    <a class="navbar-brand" href="/">Application name</a>_x000D_
                </div>_x000D_
                <div class="navbar-collapse collapse">_x000D_
                    <ul class="nav navbar-nav">_x000D_
                        <li><a href="/">Home</a></li>_x000D_
                        <li><a href="/Home/About">About</a></li>_x000D_
                        <li><a href="/Home/Contact">Contact</a></li>_x000D_
                    </ul>_x000D_
                    <ul class="nav navbar-nav navbar-right">_x000D_
                        <li><a href="/Account/Register" id="registerLink">Register</a></li>_x000D_
                        <li><a href="/Account/Login" id="loginLink">Log in</a></li>_x000D_
                    </ul>_x000D_
_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </menu>_x000D_
_x000D_
    <nav>_x000D_
        <div class="col-md-2">_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
        </div>_x000D_
_x000D_
    </nav>_x000D_
    <content>_x000D_
       <div class="col-md-10">_x000D_
_x000D_
               <h2>About.</h2>_x000D_
               <h3>Your application description page.</h3>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <hr />_x000D_
       </div>_x000D_
    </content>_x000D_
_x000D_
    <footer>_x000D_
        <div class="navbar navbar-default navbar-fixed-bottom">_x000D_
            <div class="container" style="font-size: .8em">_x000D_
                <p class="navbar-text">_x000D_
                    &copy; Some info_x000D_
                </p>_x000D_
            </div>_x000D_
        </div>_x000D_
    </footer>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_ File Content/Site.css
_x000D_
_x000D_
body {_x000D_
    padding-bottom: 70px;_x000D_
    padding-top: 70px;_x000D_
}
_x000D_
_x000D_
_x000D_

How to create a .gitignore file

Here a nice tip under Windows:

  • Right click in Windows Explorer, New > Text Document
  • Name it .gitignore. (with a trailing dot - that is the tip)
  • You end up with a .gitignore file :)

Tested under Windows 7 and 8.

This tip assumes that your Windows Explorer displays the file extensions.

Windows Explorer .gitignore

Using getline() with file input in C++

ifstream inFile;
string name, temp;
int age;

inFile.open("file.txt");

getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

Change background color for selected ListBox item

I had to set both HighlightBrushKey and ControlBrushKey to get it to be correctly styled. Otherwise, whilst it has focus this will correctly use the transparent HighlightBrusKey. Bt, if the control loses focus (whilst it is still highlighted) then it uses the ControlBrushKey.

<Style.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</Style.Resources>

When Using .Net 4.5 and above, use InactiveSelectionHighlightBrushKey instead of ControlBrushKey:

<Style.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
    <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
</Style.Resources>

Hope this helps someone out.

<embed> vs. <object>

Probably the best cross browser solution for pdf display on web pages is to use the Mozilla PDF.js project code, it can be run as a node.js service and used as follows

<iframe style="width:100%;height:500px" src="http://www.mysite.co.uk/libs/pdfjs/web/viewer.html?file="http://www.mysite.co.uk/mypdf.pdf"></iframe>

A tutorial on how to use pdf.js can be found at this ejectamenta blog article

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

This is works for me on Ubuntu 18.04 with Postman v7.1.1 which is released on 20 May, 2019.

Download the latest version of Postman.

Most probably your downloaded file should be in Downloads folder.

# Postman-linux-x64-7.1.1.tar.gz is my downloaded file

cd /home/YOUR_USERNAME/Downloads/
tar -xzf Postman-linux-x64-7.1.1.tar.gz Postman/
sudo mv Postman /usr/share/postman
sudo ln -s /usr/share/postman/Postman /usr/bin/postman

If you get an error like this,

/usr/share/postman/Postman: error while loading shared libraries: libgconf-2.so.4: cannot open shared object file: No such file or directory

please install libgconf-2-4.

sudo apt install libgconf-2-4

Just type postman in your terminal and hit enter to run latest version of Postman. Now we have to create an Unity desktop file for your launcher. For create postman.desktop file run the below command.

sudo nano ~/.local/share/applications/postman.desktop

Then paste below lines into the postman.desktop file.

[Desktop Entry]
Encoding=UTF-8
Name=Postman
Exec=postman
Icon=/usr/share/postman/app/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;

Now you can see the "Postman" icon in your Unity launcher. If you miss any point please go through this video or comment below.

Postman 7.1.1

What's the difference between primitive and reference types?

As many have stated more or less correctly what reference and primitive types are, one might be interested that we have some more relevant types in Java. Here is the complete lists of types in java (as far as I am aware of (JDK 11)).

Primitive Type

Describes a value (and not a type).

11

Reference Type

Describes a concrete type which instances extend Object (interface, class, enum, array). Furthermore TypeParameter is actually a reference type!

Integer

Note: The difference between primitive and reference type makes it necessary to rely on boxing to convert primitives in Object instances and vise versa.

Note2: A type parameter describes a type having an optional lower or upper bound and can be referenced by name within its context (in contrast to the wild card type). A type parameter typically can be applied to parameterized types (classes/interfaces) and methods. The parameter type defines a type identifier.

Wildcard Type

Expresses an unknown type (like any in TypeScript) that can have a lower or upper bound by using super or extend.

? extends List<String>
? super ArrayList<String>

Void Type

Nothingness. No value/instance possible.

void method();

Null Type

The only representation is 'null'. It is used especially during type interference computations. Null is a special case logically belonging to any type (can be assigned to any variable of any type) but is actual not considered an instance of any type (e.g. (null instanceof Object) == false).

null

Union Type

A union type is a type that is actual a set of alternative types. Sadly in Java it only exists for the multi catch statement.

catch(IllegalStateException | IOException e) {}

Interference Type

A type that is compatibile to multiple types. Since in Java a class has at most one super class (Object has none), interference types allow only the first type to be a class and every other type must be an interface type.

void method(List<? extends List<?> & Comparable> comparableList) {}

Unknown Type

The type is unknown. That is the case for certain Lambda definitions (not enclosed in brackets, single parameter).

list.forEach(element -> System.out.println(element.toString)); //element is of unknown type

Var Type

Unknown type introduced by a variable declaration spotting the 'var' keyword.

var variable = list.get(0);

Call method when home button pressed

I also struggled with HOME button for awhile. I wanted to stop/skip a background service (which polls location) when user clicks HOME button.

here is what I implemented as "hack-like" solution;

keep the state of the app on SharedPreferences using boolean value

on each activity

onResume() -> set appactive=true

onPause() -> set appactive=false

and the background service checks the appstate in each loop, skips the action

IF appactive=false

it works well for me, at least not draining the battery anymore, hope this helps....

When does socket.recv(recv_size) return?

I think you conclusions are correct but not accurate.

As the docs indicates, socket.recv is majorly focused on the network buffers.

When socket is blocking, socket.recv will return as long as the network buffers have bytes. If bytes in the network buffers are more than socket.recv can handle, it will return the maximum number of bytes it can handle. If bytes in the network buffers are less than socket.recv can handle, it will return all the bytes in the network buffers.

How to dynamically allocate memory space for a string and get that string from user?

Read one character at a time (using getc(stdin)) and grow the string (realloc) as you go.

Here's a function I wrote some time ago. Note it's intended only for text input.

char *getln()
{
    char *line = NULL, *tmp = NULL;
    size_t size = 0, index = 0;
    int ch = EOF;

    while (ch) {
        ch = getc(stdin);

        /* Check if we need to stop. */
        if (ch == EOF || ch == '\n')
            ch = 0;

        /* Check if we need to expand. */
        if (size <= index) {
            size += CHUNK;
            tmp = realloc(line, size);
            if (!tmp) {
                free(line);
                line = NULL;
                break;
            }
            line = tmp;
        }

        /* Actually store the thing. */
        line[index++] = ch;
    }

    return line;
}

How to show text in combobox when no item selected?

Unfortunately none of the above worked for me, so instead I added a label on top of the comboxbox that says "Please select". I used the following code to show and hide it:

  1. When I initialise my combobox, if there is no selected value I bring it to the front and set the text:

    PleaseSelectValueLabel.BringToFront();
    PleaseSelectValueLabel.Text = Constants.AssessmentValuePrompt;
    
  2. If there is a value selected I send it to the back:

    PleaseSelectValueLabel.SendToBack();
    
  3. I then use the following events to move the label to the front or back depending on whether the user has selected a value:

    private void PleaseSelectValueLabel_Click(object sender, EventArgs e)
    {
        PleaseSelectValueLabel.SendToBack();
        AssessmentValue.Focus();
    }
    
    private void AssessmentValue_Click(object sender, EventArgs e)
    {
        PleaseSelectValueLabel.SendToBack();
    }
    
    //if the user hasnt selected an item, make the please select label visible again
    private void AssessmentValue_Leave(object sender, EventArgs e)
    {
        if (AssessmentValue.SelectedIndex < 0)
        {
            PleaseSelectValueLabel.BringToFront();
        }
    }
    

Using Laravel Homestead: 'no input file specified'

This error only happens to me when I perform a new installation without creating the directories correctly, eg "correct": C:\Users\userxyz\Code\public.

Try removing the "public" directory, the error 'no input file specified' is displayed

Homestead.yaml

folders:
    - map: ~/Code
      to: /home/vagrant/Code
      #type: "nfs"

sites:
    - map: homestead.test
      to: /home/vagrant/Code/public

Can Twitter Bootstrap alerts fade in as well as out?

I don't agree with the way that Bootstrap uses fade in (as seen in their documentation - http://v4-alpha.getbootstrap.com/components/alerts/), and my suggestion is to avoid the class names fade and in, and to avoid that pattern in general (which is currently seen in the top-rated answer to this question).

(1) The semantics are wrong - transitions are temporary, but the class names live on. So why should we name our classes fade and fade in? It should be faded and faded-in, so that when developers read the markup, it's clear that those elements were faded or faded-in. The Bootstrap team has already done away with hide for hidden, why is fade any different?

(2) Using 2 classes fade and in for a single transition pollutes the class space. And, it's not clear that fade and in are associated with one another. The in class looks like a completely independent class, like alert and alert-success.

The best solution is to use faded when the element has been faded out, and to replace that class with faded-in when the element has been faded in.

Alert Faded

So to answer the question. I think the alert markup, style, and logic should be written in the following manner. Note: Feel free to replace the jQuery logic, if you're using vanilla javascript.

HTML

<div id="saveAlert" class="alert alert-success">
  <a class="close" href="#">×</a>
  <p><strong>Well done!</strong> You successfully read this alert message.</p>
</div>

CSS

.faded {
  opacity: 0;
  transition: opacity 1s;
}

JQuery

$('#saveAlert .close').on('click', function () {

  $("#saveAlert")
    .addClass('faded');

});

unsigned APK can not be installed

I did not know that even with the "Allow Installation of non-Marked application", I still needed to sign the application.

I self-signed my application, following this link self-sign and release application, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.

Dark color scheme for Eclipse

For Linux users, assuming you run a compositing window manager (Compiz), you can just turn the window negative. I use Eclipse like this all the time, the normal (whitie) looks is blowing my eyes off.

Git fatal: protocol 'https' is not supported

Problem

git clone https://github.com/rojarfast1991/TestGit.git fatal: protocol 'https' is not supported

Solution:

Steps:

(1):- Open the new terminal and clone the git repository

git clone https://github.com/rojarfast1991/TestGit.git

(2) Automatic git login prompt will open and it will be asked you to enter a user credential.

UserName : - xxxxxxx

PassWord : - xxxxxxx

Finally, cloning will start...

git clone https://github.com/rojarfast1991/TestGit.git
Cloning into 'TestGit'...
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (4/4), done.

Pandas join issue: columns overlap but no suffix specified

Mainly join is used exclusively to join based on the index,not on the attribute names,so change the attributes names in two different dataframes,then try to join,they will be joined,else this error is raised

How to refresh token with Google API client?

This here works very good, maybe it could help anybody:

index.php

session_start();

require_once __DIR__.'/client.php';

if(!isset($obj->error) && isset($_SESSION['access_token']) && $_SESSION['access_token'] && isset($obj->expires_in)) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Google API Token Test</title>
<meta charset='utf-8' />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
search('Music Mix 2010');
function search(q) {
    $.ajax({
        type: 'GET',
        url: 'action.php?q='+q,
        success: function(data) {
            if(data == 'refresh') location.reload();
            else $('#response').html(JSON.stringify(JSON.parse(data)));
        }
    });
}
</script>
</head>
<body>
<div id="response"></div>
</body>
</html>
<?php
}
else header('Location: '.filter_var('https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/oauth2callback.php', FILTER_SANITIZE_URL));
?>

oauth2callback.php

require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('auth.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setRedirectUri('https://'.filter_var($_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'], FILTER_SANITIZE_URL));
$client->addScope(Google_Service_YouTube::YOUTUBE_FORCE_SSL);

if(isset($_GET['code']) && $_GET['code']) {
    $client->authenticate(filter_var($_GET['code'], FILTER_SANITIZE_STRING));
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $_SESSION['access_token']['refresh_token'];
    setcookie('refresh_token', $_SESSION['refresh_token'], time()+60*60*24*180, '/', filter_var($_SERVER['HTTP_HOST'], FILTER_SANITIZE_URL), true, true);
    header('Location: '.filter_var('https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']), FILTER_SANITIZE_URL));
    exit();
}
else header('Location: '.filter_var($client->createAuthUrl(), FILTER_SANITIZE_URL));
exit();

?>

client.php

// https://developers.google.com/api-client-library/php/start/installation
require_once __DIR__.'/vendor/autoload.php';

$client = new Google_Client();
$client->setAuthConfig('auth.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_YouTube::YOUTUBE_FORCE_SSL);

// Delete Cookie Token
#setcookie('refresh_token', @$_SESSION['refresh_token'], time()-1, '/', filter_var($_SERVER['HTTP_HOST'], FILTER_SANITIZE_URL), true, true);

// Delete Session Token
#unset($_SESSION['refresh_token']);

if(isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
    $client->refreshToken($_SESSION['refresh_token']);
    $_SESSION['access_token'] = $client->getAccessToken();
}
elseif(isset($_COOKIE['refresh_token']) && $_COOKIE['refresh_token']) {
    $client->refreshToken($_COOKIE['refresh_token']);
    $_SESSION['access_token'] = $client->getAccessToken();
}

$url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.urlencode(@$_SESSION['access_token']['access_token']);
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Google API Token Test');
$json = curl_exec($curl_handle);
curl_close($curl_handle);

$obj = json_decode($json);

?>

action.php

session_start();

require_once __DIR__.'/client.php';

if(isset($obj->error)) {
    echo 'refresh';
    exit();
}
elseif(isset($_SESSION['access_token']) && $_SESSION['access_token'] && isset($obj->expires_in) && isset($_GET['q']) && !empty($_GET['q'])) {
    $client->setAccessToken($_SESSION['access_token']);
    $service = new Google_Service_YouTube($client);
    $response = $service->search->listSearch('snippet', array('q' => filter_input(INPUT_GET, 'q', FILTER_SANITIZE_SPECIAL_CHARS), 'maxResults' => '1', 'type' => 'video'));
    echo json_encode($response['modelData']);
    exit();
}
?>

Where do I get servlet-api.jar from?

Grab it from here

Just choose required version and click 'Binary'. e.g direct link to version 2.5

HttpClient won't import in Android Studio

HttpClient was deprecated in API Level 22 and removed in API Level 23. You can still use it in API Level 23 and onwards if you must, however it is best to move to supported methods to handle HTTP. So, if you're compiling with 23, add this in your build.gradle:

android {
    useLibrary 'org.apache.http.legacy'
}

PyTorch: How to get the shape of a Tensor as a list of int

For PyTorch v1.0 and possibly above:

>>> import torch
>>> var = torch.tensor([[1,0], [0,1]])

# Using .size function, returns a torch.Size object.
>>> var.size()
torch.Size([2, 2])
>>> type(var.size())
<class 'torch.Size'>

# Similarly, using .shape
>>> var.shape
torch.Size([2, 2])
>>> type(var.shape)
<class 'torch.Size'>

You can cast any torch.Size object to a native Python list:

>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>

In PyTorch v0.3 and 0.4:

Simply list(var.size()), e.g.:

>>> import torch
>>> from torch.autograd import Variable
>>> from torch import IntTensor
>>> var = Variable(IntTensor([[1,0],[0,1]]))

>>> var
Variable containing:
 1  0
 0  1
[torch.IntTensor of size 2x2]

>>> var.size()
torch.Size([2, 2])

>>> list(var.size())
[2, 2]

Replace given value in vector

Why the fuss?

replace(haystack, haystack %in% needles, replacements)

Demo:

haystack <- c("q", "w", "e", "r", "t", "y")
needles <- c("q", "w")
replacements <- c("a", "z")

replace(haystack, haystack %in% needles, replacements)
#> [1] "a" "z" "e" "r" "t" "y"

jQuery - setting the selected value of a select control via its text description

Select by description for jQuery v1.6+

_x000D_
_x000D_
var text1 = 'Two';_x000D_
$("select option").filter(function() {_x000D_
  //may want to use $.trim in here_x000D_
  return $(this).text() == text1;_x000D_
}).prop('selected', true);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
  <option value="0">One</option>_x000D_
  <option value="1">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

jQuery versions below 1.6 and greater than or equal to 1.4

_x000D_
_x000D_
var text1 = 'Two';_x000D_
$("select option").filter(function() {_x000D_
  //may want to use $.trim in here_x000D_
  return $(this).text() == text1;_x000D_
}).attr('selected', true);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
  <option value="0">One</option>_x000D_
  <option value="1">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It will not work in jQuery 1.9+.


Previous versions

val() should handle both cases.

_x000D_
_x000D_
$('select').val('1'); // selects "Two"_x000D_
$('select').val('Two'); // also selects "Two"
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
  <option value="0">One</option>_x000D_
  <option value="1">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

View the change history of a file using Git versioning

To show what revision and author last modified each line of a file:

git blame filename

or if you want to use the powerful blame GUI:

git gui blame filename

Finding common rows (intersection) in two Pandas dataframes

In SQL, this problem could be solved by several methods:

select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)

or join and then unpivot (possible in SQL server)

select
    df1.user_id,
    c.rating
from df1
    inner join df2 on df2.user_i = df1.user_id
    outer apply (
        select df1.rating union all
        select df2.rating
    ) as c

Second one could be written in pandas with something like:

>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
   user_id  rating
0        3      20
0        3      30

Passing multiple parameters with $.ajax url

Why are you combining GET and POST? Use one or the other.

$.ajax({
    type: 'post',
    data: {
        timestamp: timestamp,
        uid: uid
        ...
    }
});

php:

$uid =$_POST['uid'];

Or, just format your request properly (you're missing the ampersands for the get parameters).

url:"getdata.php?timestamp="+timestamp+"&uid="+id+"&uname="+name,

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

This will work:

The problem may happen when you're trying to read a list with a single element as a JsonArray rather than a JsonNode or vice versa.

Since you can't know for sure if the returned list contains a single element (so the json looks like this {...}) or multiple elements (and the json looks like this [{...},{...}]) - you'll have to check in runtime the type of the element.

It should look like this:

(Note: in this code sample I'm using com.fasterxml.jackson)

String jsonStr = response.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);

// Start by checking if this is a list -> the order is important here:                      
if (rootNode instanceof ArrayNode) {
    // Read the json as a list:
    myObjClass[] objects = mapper.readValue(rootNode.toString(), myObjClass[].class);
    ...
} else if (rootNode instanceof JsonNode) {
    // Read the json as a single object:
    myObjClass object = mapper.readValue(rootNode.toString(), myObjClass.class);
    ...
} else {
    ...
}

how to rotate a bitmap 90 degrees

I would simplify comm1x's Kotlin extension function even more:

fun Bitmap.rotate(degrees: Float) =
    Bitmap.createBitmap(this, 0, 0, width, height, Matrix().apply { postRotate(degrees) }, true)

Two statements next to curly brace in an equation

Or this:

f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}

Bootstrap Modal immediately disappearing

In my case, a click on a button causes a (not wanted) reload of the page.

Here is my fix:

<button class="btn btn-success" onclick="javascript: return false;" 
data-target="#modalID" data-toggle="modal">deaktivieren</button>

How to convert timestamp to datetime in MySQL?

To answer Janus Troelsen comment

Use UNIX_TIMESTAMP instead of TIMESTAMP

SELECT from_unixtime( UNIX_TIMESTAMP(  "2011-12-01 22:01:23.048" ) )

The TIMESTAMP function returns a Date or a DateTime and not a timestamp, while UNIX_TIMESTAMP returns a unix timestamp

How to break out or exit a method in Java?

Use the return keyword to exit from a method.

public void someMethod() {
    //... a bunch of code ...
    if (someCondition()) {
        return;
    }
    //... otherwise do the following...
}

Pls note: We may use break statements which are used to break/exit only from a loop, and not the entire program.

To exit from program: System.exit() Method:
System.exit has status code, which tells about the termination, such as:
exit(0) : Indicates successful termination.
exit(1) or exit(-1) or any non-zero value – indicates unsuccessful termination.

Iterate over object attributes in python

For python 3.6

class SomeClass:

    def attr_list(self, should_print=False):

        items = self.__dict__.items()
        if should_print:
            [print(f"attribute: {k}    value: {v}") for k, v in items]

        return items

adb is not recognized as internal or external command on windows

You have two ways:

First go to the particular path of Android SDK:

1) Open your command prompt and traverse to the platform-tools directory through it such as

$ cd Frameworks\Android-Sdk\platform-tools

2) Run your adb commands now such as to know that your adb is working properly :

$ adb devices OR adb logcat OR simply adb

Second way is :

1) Right click on your My Computer.

2) Open Environment variables.

3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).

4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.

5) Restart your computer once.

6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.

Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

The Northwind example cited by Marc Gravell can be rewritten with the City column selected directly by the group statement:

from cust in ctx.Customers
where cust.CustomerID != ""
group cust.City /*here*/ by cust.Country
into grp
select new
{
        Country = grp.Key,
        Count = grp.Distinct().Count()
};

javac: invalid target release: 1.8

If this error occurs when running a Gradle (or Maven) task, you need to modify that build tool configuration to point to your installation of Java JDK 1.8 following this route:

File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle

There you check the Linked Gradle project is the one you are working on and select the Gradle JVM (You missed this when you imported the gradle project into IntelliJ)

enter image description here

Remember when importing a Gradle (or Maven) project to set the target JVM correctly here: enter image description here

Remove all padding and margin table HTML and CSS

Try using tag body to remove all margin and padding like that you want.

<body style="margin: 0;padding: 0">
    <table border="1" width="100%" cellpadding="0" cellspacing="0" bgcolor=green>
        <tr>
            <td >&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td >&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td >&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
    </table>
</body>

How to display a gif fullscreen for a webpage background?

You can set up a background with your GIF file and set the body this way:

body{
background-image:url('http://www.example.com/yourfile.gif');
background-position: center;
background-size: cover;
}

Change background image URL with your GIF. With background-position: center you can put the image to the center and with background-size: cover you set the picture to fit all the screen. You can also set background-size: contain if you want to fit the picture at 100% of the screen but without leaving any part of the picture without showing.

Here's more info about the property:

http://www.w3schools.com/cssref/css3_pr_background-size.asp

Hope it helps :)

Objective-C: Reading a file line by line

This will work for general reading a String from Text. If you would like to read longer text (large size of text), then use the method that other people here were mentioned such as buffered (reserve the size of the text in memory space).

Say you read a Text File.

NSString* filePath = @""//file path...
NSString* fileRoot = [[NSBundle mainBundle] 
               pathForResource:filePath ofType:@"txt"];

You want to get rid of new line.

// read everything from text
NSString* fileContents = 
      [NSString stringWithContentsOfFile:fileRoot 
       encoding:NSUTF8StringEncoding error:nil];

// first, separate by new line
NSArray* allLinedStrings = 
      [fileContents componentsSeparatedByCharactersInSet:
      [NSCharacterSet newlineCharacterSet]];

// then break down even further 
NSString* strsInOneLine = 
      [allLinedStrings objectAtIndex:0];

// choose whatever input identity you have decided. in this case ;
NSArray* singleStrs = 
      [currentPointString componentsSeparatedByCharactersInSet:
      [NSCharacterSet characterSetWithCharactersInString:@";"]];

There you have it.

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

Should Gemfile.lock be included in .gitignore?

The Bundler docs address this question as well:

ORIGINAL: http://gembundler.com/v1.3/rationale.html

EDIT: http://web.archive.org/web/20160309170442/http://bundler.io/v1.3/rationale.html

See the section called "Checking Your Code into Version Control":

After developing your application for a while, check in the application together with the Gemfile and Gemfile.lock snapshot. Now, your repository has a record of the exact versions of all of the gems that you used the last time you know for sure that the application worked. Keep in mind that while your Gemfile lists only three gems (with varying degrees of version strictness), your application depends on dozens of gems, once you take into consideration all of the implicit requirements of the gems you depend on.

This is important: the Gemfile.lock makes your application a single package of both your own code and the third-party code it ran the last time you know for sure that everything worked. Specifying exact versions of the third-party code you depend on in your Gemfile would not provide the same guarantee, because gems usually declare a range of versions for their dependencies.

The next time you run bundle install on the same machine, bundler will see that it already has all of the dependencies you need, and skip the installation process.

Do not check in the .bundle directory, or any of the files inside it. Those files are specific to each particular machine, and are used to persist installation options between runs of the bundle install command.

If you have run bundle pack, the gems (although not the git gems) required by your bundle will be downloaded into vendor/cache. Bundler can run without connecting to the internet (or the RubyGems server) if all the gems you need are present in that folder and checked in to your source control. This is an optional step, and not recommended, due to the increase in size of your source control repository.

Streaming Audio from A URL in Android using MediaPlayer?

Looking my projects:

  1. https://github.com/master255/ImmortalPlayer http/FTP support, One thread to read, send and save to cache data. Most simplest way and most fastest work. Complex logic - best way!
  2. https://github.com/master255/VideoViewCache Simple Videoview with cache. Two threads for play and save data. Bad logic, but if you need then use this.

What's the difference between UTF-8 and UTF-8 without BOM?

The UTF-8 BOM is a sequence of bytes at the start of a text stream (0xEF, 0xBB, 0xBF) that allows the reader to more reliably guess a file as being encoded in UTF-8.

Normally, the BOM is used to signal the endianness of an encoding, but since endianness is irrelevant to UTF-8, the BOM is unnecessary.

According to the Unicode standard, the BOM for UTF-8 files is not recommended:

2.6 Encoding Schemes

... Use of a BOM is neither required nor recommended for UTF-8, but may be encountered in contexts where UTF-8 data is converted from other encoding forms that use a BOM or where the BOM is used as a UTF-8 signature. See the “Byte Order Mark” subsection in Section 16.8, Specials, for more information.

jQuery $(this) keyword

Have a look at this code:

HTML:

<div class="multiple-elements" data-bgcol="red"></div>
<div class="multiple-elements" data-bgcol="blue"></div>

JS:

$('.multiple-elements').each(
    function(index, element) {
        $(this).css('background-color', $(this).data('bgcol')); // Get value of HTML attribute data-bgcol="" and set it as CSS color
    }
);

this refers to the current element that the DOM engine is sort of working on, or referring to.

Another example:

<a href="#" onclick="$(this).css('display', 'none')">Hide me!</a>

Hope you understand now. The this keyword occurs while dealing with object oriented systems, or as we have in this case, element oriented systems :)

How to parse unix timestamp to time.Time

The time.Parse function does not do Unix timestamps. Instead you can use strconv.ParseInt to parse the string to int64 and create the timestamp with time.Unix:

package main

import (
    "fmt"
    "time"
    "strconv"
)

func main() {
    i, err := strconv.ParseInt("1405544146", 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(i, 0)
    fmt.Println(tm)
}

Output:

2014-07-16 20:55:46 +0000 UTC

Playground: http://play.golang.org/p/v_j6UIro7a

Edit:

Changed from strconv.Atoi to strconv.ParseInt to avoid int overflows on 32 bit systems.

'ls' is not recognized as an internal or external command, operable program or batch file

If you want to use Unix shell commands on Windows, you can use Windows Powershell, which includes both Windows and Unix commands as aliases. You can find more info on it in the documentation.

PowerShell supports aliases to refer to commands by alternate names. Aliasing allows users with experience in other shells to use common command names that they already know for similar operations in PowerShell.

The PowerShell equivalents may not produce identical results. However, the results are close enough that users can do work without knowing the PowerShell command name.

Remove non-numeric characters (except periods and commas) from a string

Simplest way to truly remove all non-numeric characters:

echo preg_replace('/\D/', '', $string);

\D represents "any character that is not a decimal digit"

http://php.net/manual/en/regexp.reference.escape.php

How to "fadeOut" & "remove" a div in jQuery?

If you're using it in several different places, you should turn it into a plugin.

jQuery.fn.fadeOutAndRemove = function(speed){
    $(this).fadeOut(speed,function(){
        $(this).remove();
    })
}

And then:

// Somewhere in the program code.
$('div').fadeOutAndRemove('fast');

How should I remove all the leading spaces from a string? - swift

To remove all spaces from the string:

let space_removed_string = (yourstring?.components(separatedBy: " ").joined(separator: ""))!

Android Transparent TextView?

Although this answer is very late but might help other developer so I'm posting it here.

Answers above showing only how to set transparent background of TextView. We can achieve transparent Textview backcgorund in two way:

  1. By setting opacity code such as #88000000 in android:background attribute
  2. By setting android:alpha="0.5" attribute to TextView

Second approach is better because it gives flexibility to set background with different color and then setting setting opacity to widget using android:alpha="0.2"

Example

<TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black"
        android:alpha="0.3"
        android:textColor="@color/white"
        android:textStyle="bold"/>

How to go from Blob to ArrayBuffer

Or you can use the fetch API

fetch(URL.createObjectURL(myBlob)).then(res => res.arrayBuffer())

I don't know what the performance difference is, and this will show up on your network tab in DevTools as well.

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

Does the user you're executing this script under even see that table??

select top 1 * from products

Do you get any output for this??

If yes: does this user have the permission to modify the table, i.e. execute DDL scripts like ALTER TABLE etc.? Typically, regular users don't have this elevated permissions.

How to implement a material design circular progress bar in android

In addition to cozeJ4's answer, here's updated version of that gist

Original one lacked imports and contained some errors. This one is ready to use.

A simple algorithm for polygon intersection

You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.

One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton

Alan Murta has a complete implementation of a polygon clipper GPC.

Edit:

Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.

Mocking HttpClient in unit tests

Building on the other answers, I suggest this code, which does not have any outside dependencies:

[TestClass]
public class MyTestClass
{
    [TestMethod]
    public async Task MyTestMethod()
    {
        var httpClient = new HttpClient(new MockHttpMessageHandler());

        var content = await httpClient.GetStringAsync("http://some.fake.url");

        Assert.AreEqual("Content as string", content);
    }
}

public class MockHttpMessageHandler : HttpMessageHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var responseMessage = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent("Content as string")
        };

        return await Task.FromResult(responseMessage);
    }
}

How to create CSV Excel file C#?

If anyone would like I converted this to an extension method on IEnumerable:

public static class ListExtensions
{
    public static string ExportAsCSV<T>(this IEnumerable<T> listToExport, bool includeHeaderLine, string delimeter)
    {
        StringBuilder sb = new StringBuilder();

        IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();

        if (includeHeaderLine)
        {
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                sb.Append(propertyInfo.Name).Append(",");
            }
            sb.Remove(sb.Length - 1, 1).AppendLine();
        }

        foreach (T obj in listToExport)
        {
            T localObject = obj;

            var line = String.Join(delimeter, propertyInfos.Select(x => SanitizeValuesForCSV(x.GetValue(localObject, null), delimeter)));

            sb.AppendLine(line);
        }

        return sb.ToString();
    }

    private static string SanitizeValuesForCSV(object value, string delimeter)
    {
        string output;

        if (value == null) return "";

        if (value is DateTime)
        {
            output = ((DateTime)value).ToLongDateString();
        }
        else
        {
            output = value.ToString();                
        }

        if (output.Contains(delimeter) || output.Contains("\""))
            output = '"' + output.Replace("\"", "\"\"") + '"';

        output = output.Replace("\n", " ");
        output = output.Replace("\r", "");

        return output;
    }
}

Java: Reading a file into an array

import java.io.File;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;

import java.util.List;

// ...

Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();        
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});

Graphical user interface Tutorial in C

You can also have a look at FLTK (C++ and not plain C though)

FLTK (pronounced "fulltick") is a cross-platform C++ GUI toolkit for UNIX®/Linux® (X11), Microsoft® Windows®, and MacOS® X. FLTK provides modern GUI functionality without the bloat and supports 3D graphics via OpenGL® and its built-in GLUT emulation.

FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.

Here are some quickstart screencasts

[Happy New Year!]

How to animate button in android?

I can't comment on @omega's comment because I don't have enough reputation but the answer to that question should be something like:

shake.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"          <!-- how long the animation lasts -->
    android:fromDegrees="-5"        <!-- how far to swing left -->
    android:pivotX="50%"            <!-- pivot from horizontal center -->
    android:pivotY="50%"            <!-- pivot from vertical center -->
    android:repeatCount="10"        <!-- how many times to swing back and forth -->
    android:repeatMode="reverse"    <!-- to make the animation go the other way -->
    android:toDegrees="5" />        <!-- how far to swing right -->

Class.java

Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
view.startAnimation(shake);

This is just one way of doing what you want, there may be better methods out there.

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

I had the same issue running it in my pipeline.

For me, the issue was that I was using node version v10.0.0 in my docker container.

Updating it to v14.7.0 solved it for me

How to send objects through bundle

This is a very belated answer to my own question, but it keep getting attention, so I feel I must address it. Most of these answers are correct and handle the job perfectly. However, it depends on the needs of the application. This answer will be used to describe two solutions to this problem.

Application

The first is the Application, as it has been the most spoken about answer here. The application is a good object to place entities that need a reference to a Context. A `ServerSocket` undoubtedly would need a context (for file I/o or simple `ListAdapter` updates). I, personally, prefer this route. I like application's, they are useful for context retrieving (because they can be made static and not likely cause a memory leak) and have a simple lifecycle.

Service

The Service` is second. A `Service`is actually the better choice for my problem becuase that is what services are designed to do:
A Service is an application component that can perform long-running operations in
the background and does not provide a user interface.
Services are neat in that they have a more defined lifecycle that is easier to control. Further, if needed, services can run externally of the application (ie. on boot). This can be necessary for some apps or just a neat feature.

This wasn't a full description of either, but I left links to the docs for those who want to investigate more. Overall the Service is the better for the instance I needed - running a ServerSocket to my SPP device.

Parse rfc3339 date strings in Python?

This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()

Detect HTTP or HTTPS then force HTTPS in JavaScript

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

Add this meta tag to your index.html inside head

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

Hope it helped.

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

__cplusplus

In C++0x the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.

C++0x FAQ by BS

Python Tkinter clearing a frame

For clear frame, first need to destroy all widgets inside the frame,. it will clear frame.

import tkinter as tk
from tkinter import *
root = tk.Tk()

frame = Frame(root)
frame.pack(side="top", expand=True, fill="both")

lab = Label(frame, text="hiiii")
lab.grid(row=0, column=0, padx=10, pady=5)

def clearFrame():
    # destroy all widgets from frame
    for widget in frame.winfo_children():
       widget.destroy()
    
    # this will clear frame and frame will be empty
    # if you want to hide the empty panel then
    frame.pack_forget()

frame.but = Button(frame, text="clear frame", command=clearFrame)
frame.but.grid(row=0, column=1, padx=10, pady=5)

# then whenever you add data in frame then you can show that frame
lab2 = Label(frame, text="hiiii")
lab2.grid(row=1, column=0, padx=10, pady=5)
frame.pack()
root.mainloop()

C# Error "The type initializer for ... threw an exception

This problem can occur if a class tries to get value of a non-existent key in web.config.

For example, the class has a static variable ClientID

private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();

but the web.config doesn't contain the 'GoogleCalendarApplicationClientID' key, then the error will be thrown on any static function call or any class instance creation

Is there a way to select sibling nodes?

From 2017:
straightforward answer: element.nextElementSibling for get the right element sibling. also you have element.previousElementSibling for previous one

from here is pretty simple to got all next sibiling

var n = element, ret = [];
while (n = n.nextElementSibling){
  ret.push(n)
}
return ret;

Django Rest Framework -- no module named rest_framework

Install the missing module separately using pip installer

pip3 install djangorestframework-jsonapi

This worked for me.

How do Python's any and all functions work?

You can roughly think of any and all as series of logical or and and operators, respectively.

any

any will return True when at least one of the elements is Truthy. Read about Truth Value Testing.

all

all will return True only when all the elements are Truthy.

Truth table

+-----------------------------------------+---------+---------+
|                                         |   any   |   all   |
+-----------------------------------------+---------+---------+
| All Truthy values                       |  True   |  True   |
+-----------------------------------------+---------+---------+
| All Falsy values                        |  False  |  False  |
+-----------------------------------------+---------+---------+
| One Truthy value (all others are Falsy) |  True   |  False  |
+-----------------------------------------+---------+---------+
| One Falsy value (all others are Truthy) |  True   |  False  |
+-----------------------------------------+---------+---------+
| Empty Iterable                          |  False  |  True   |
+-----------------------------------------+---------+---------+

Note 1: The empty iterable case is explained in the official documentation, like this

any

Return True if any element of the iterable is true. If the iterable is empty, return False

Since none of the elements are true, it returns False in this case.

all

Return True if all elements of the iterable are true (or if the iterable is empty).

Since none of the elements are false, it returns True in this case.


Note 2:

Another important thing to know about any and all is, it will short-circuit the execution, the moment they know the result. The advantage is, entire iterable need not be consumed. For example,

>>> multiples_of_6 = (not (i % 6) for i in range(1, 10))
>>> any(multiples_of_6)
True
>>> list(multiples_of_6)
[False, False, False]

Here, (not (i % 6) for i in range(1, 10)) is a generator expression which returns True if the current number within 1 and 9 is a multiple of 6. any iterates the multiples_of_6 and when it meets 6, it finds a Truthy value, so it immediately returns True, and rest of the multiples_of_6 is not iterated. That is what we see when we print list(multiples_of_6), the result of 7, 8 and 9.

This excellent thing is used very cleverly in this answer.


With this basic understanding, if we look at your code, you do

any(x) and not all(x)

which makes sure that, atleast one of the values is Truthy but not all of them. That is why it is returning [False, False, False]. If you really wanted to check if both the numbers are not the same,

print [x[0] != x[1] for x in zip(*d['Drd2'])]

Substitute a comma with a line break in a cell

To replace commas with newline characters use this formula (assuming that the text to be altered is in cell A1):

=SUBSTITUTE(A1,",",CHAR(10))

You may have to then alter the row height to see all of the values in the cell

I've left a comment about the other part of your question


Edit: here's a screenshot of this working - I had to turn on "Wrap Text" in the "Format Cells" dialog.

enter image description here

check if a file is open in Python

I assume that you're writing to the file, then close it (so the user can open it in Excel), and then, before re-opening it for append/write operations, you want to check that the file isn't still open in Excel?

This is how you could do that:

while True:   # repeat until the try statement succeeds
    try:
        myfile = open("myfile.csv", "r+") # or "a+", whatever you need
        break                             # exit the loop
    except IOError:
        input("Could not open file! Please close Excel. Press Enter to retry.")
        # restart the loop

with myfile:
    do_stuff()

How do I debug jquery AJAX calls?

you can use success function, once see this jquery.ajax settings

 $('#ChangePermission').click(function(){
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
        'user': document.GetElementById("user").value,
        'perm': document.GetElementById("perm").value
        }
       success:function(result)//we got the response
       {
        //you can try to write alert(result) to see what is the response,this result variable will contains what you prints in the php page
       }
    })
})

we can also have error() function

hope this helps you

How to create a new figure in MATLAB?

The other thing to be careful about, is to use the clf (clear figure) command when you are starting a fresh plot. Otherwise you may be plotting on a pre-existing figure (not possible with the figure command by itself, but if you do figure(2) there may already be a figure #2), with more than one axis, or an axis that is placed kinda funny. Use clf to ensure that you're starting from scratch:

figure(N);
clf;
plot(something);
...

MongoDB "root" user

Mongodb user management:

roles list:

read
readWrite
dbAdmin
userAdmin
clusterAdmin
readAnyDatabase
readWriteAnyDatabase
userAdminAnyDatabase
dbAdminAnyDatabase

create user:

db.createUser(user, writeConcern)

db.createUser({ user: "user",
  pwd: "pass",
  roles: [
    { role: "read", db: "database" } 
  ]
})

update user:

db.updateUser("user",{
  roles: [
    { role: "readWrite", db: "database" } 
  ]
})

drop user:

db.removeUser("user")

or

db.dropUser("user")

view users:

db.getUsers();

more information: https://docs.mongodb.com/manual/reference/security/#read

Add line break to 'git commit -m' from the command line

Personally, I find it easiest to modify commit messages after the fact in vi (or whatever your git editor of choice is) rather than on the command line, by doing git commit --amend right after git commit.

Jquery click event not working after append method

The .on() method is used to delegate events to elements, dynamically added or already present in the DOM:

_x000D_
_x000D_
// STATIC-PARENT              on  EVENT    DYNAMIC-CHILD_x000D_
$('#registered_participants').on('click', '.new_participant_form', function() {_x000D_
_x000D_
  var $td = $(this).closest('tr').find('td');_x000D_
  var part_name = $td.eq(1).text();_x000D_
  console.log( part_name );_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
$('#add_new_participant').click(function() {_x000D_
_x000D_
  var first_name = $.trim( $('#f_name_participant').val() );_x000D_
  var last_name  = $.trim( $('#l_name_participant').val() );_x000D_
  var role       = $('#new_participant_role').val();_x000D_
  var email      = $('#email_participant').val();_x000D_
  _x000D_
  if(!first_name && !last_name) return;_x000D_
_x000D_
  $('#registered_participants').append('<tr><td><a href="#" class="new_participant_form">Participant Registration</a></td><td>' + first_name + ' ' + last_name + '</td><td>' + role + '</td><td>0% done</td></tr>');_x000D_
_x000D_
});
_x000D_
<table id="registered_participants" class="tablesorter">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Form</th>_x000D_
      <th>Name</th>_x000D_
      <th>Role</th>_x000D_
      <th>Progress </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td><a href="#" class="new_participant_form">Participant Registration</a></td>_x000D_
      <td>Smith Johnson</td>_x000D_
      <td>Parent</td>_x000D_
      <td>60% done</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<input type="text" id="f_name_participant" placeholder="Name">_x000D_
<input type="text" id="l_name_participant" placeholder="Surname">_x000D_
<select id="new_participant_role">_x000D_
  <option>Parent</option>_x000D_
  <option>Child</option>_x000D_
</select>_x000D_
<button id="add_new_participant">Add New Entry</button>_x000D_
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Read more: http://api.jquery.com/on/

How to debug a referenced dll (having pdb)

When you want to set a breakpoint in source code of a referenced dll, first make sure that you have a pdb file available for it. Then you can just open the related source code file and set a breakpoint over there. The source file does not need to be part of your solution. As explained in How can I set a breakpoint in referenced code in Visual Studio?

You can review your breakpoints through the breakpoints window, available via Debug -> Windows -> Breakpoints.

This approach has the benefit that you are not required to add an existing project to your solution just for debugging purposes as leaving it out has saved me a lot of build time. Evidently, building a solution with only one project in it is much faster than building a solution with lots of them.

react-router getting this.props.location in child components

(Update) V5.1 & Hooks (Requires React >= 16.8)

You can use useHistory, useLocation and useRouteMatch in your component to get match, history and location .

const Child = () => {
  const location = useLocation();
  const history = useHistory();
  const match = useRouteMatch("write-the-url-you-want-to-match-here");

  return (
    <div>{location.pathname}</div>
  )
}

export default Child

(Update) V4 & V5

You can use withRouter HOC in order to inject match, history and location in your component props.

class Child extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

(Update) V3

You can use withRouter HOC in order to inject router, params, location, routes in your component props.

class Child extends React.Component {

  render() {
    const { router, params, location, routes } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

Original answer

If you don't want to use the props, you can use the context as described in React Router documentation

First, you have to set up your childContextTypes and getChildContext

class App extends React.Component{

  getChildContext() {
    return {
      location: this.props.location
    }
  }

  render() {
    return <Child/>;
  }
}

App.childContextTypes = {
    location: React.PropTypes.object
}

Then, you will be able to access to the location object in your child components using the context like this

class Child extends React.Component{

   render() {
     return (
       <div>{this.context.location.pathname}</div>
     )
   }

}

Child.contextTypes = {
    location: React.PropTypes.object
 }

How to launch Windows Scheduler by command-line?

You can use either TASKSCHD.MSC or CONTROL SCHEDTASKS

Here are some more such commands.

Get current URL/URI without some of $_GET variables

To get the absolute current request url (exactly as seen in the address bar, with GET params and http://) I found that the following works well:

Yii::app()->request->hostInfo . Yii::app()->request->url

How to sum data.frame column values?

You can just use sum(people$Weight).

sum sums up a vector, and people$Weight retrieves the weight column from your data frame.

Note - you can get built-in help by using ?sum, ?colSums, etc. (by the way, colSums will give you the sum for each column).

What is the best (idiomatic) way to check the type of a Python variable?

I think I will go for the duck typing approach - "if it walks like a duck, it quacks like a duck, its a duck". This way you will need not worry about if the string is a unicode or ascii.

Here is what I will do:

In [53]: s='somestring'

In [54]: u=u'someunicodestring'

In [55]: d={}

In [56]: for each in s,u,d:
    if hasattr(each, 'keys'):
        print list(set(each.values()))
    elif hasattr(each, 'lower'):
        print [each]
    else:
        print "error"
   ....:         
   ....:         
['somestring']
[u'someunicodestring']
[]

The experts here are welcome to comment on this type of usage of ducktyping, I have been using it but got introduced to the exact concept behind it lately and am very excited about it. So I would like to know if thats an overkill to do.

What does T&& (double ampersand) mean in C++11?

The term for T&& when used with type deduction (such as for perfect forwarding) is known colloquially as a forwarding reference. The term "universal reference" was coined by Scott Meyers in this article, but was later changed.

That is because it may be either r-value or l-value.

Examples are:

// template
template<class T> foo(T&& t) { ... }

// auto
auto&& t = ...;

// typedef
typedef ... T;
T&& t = ...;

// decltype
decltype(...)&& t = ...;

More discussion can be found in the answer for: Syntax for universal references

Copy Data from a table in one Database to another separate database

It's db1.dbo.TempTable and db2.dbo.TempTable

The four-part naming scheme goes:

ServerName.DatabaseName.Schema.Object

Adding machineKey to web.config on web-farm sites

Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.

An alternative option is to set it in the machine level web.config, so its not even in the web site folder.

To generate it do it just like the linked article in David's answer.

Classes vs. Functions

Before answering your question:

If you do not have a Person class, first you must consider whether you want to create a Person class. Do you plan to reuse the concept of a Person very often? If so, you should create a Person class. (You have access to this data in the form of a passed-in variable and you don't care about being messy and sloppy.)

To answer your question:

You have access to their birthyear, so in that case you likely have a Person class with a someperson.birthdate field. In that case, you have to ask yourself, is someperson.age a value that is reusable?

The answer is yes. We often care about age more than the birthdate, so if the birthdate is a field, age should definitely be a derived field. (A case where we would not do this: if we were calculating values like someperson.chanceIsFemale or someperson.positionToDisplayInGrid or other irrelevant values, we would not extend the Person class; you just ask yourself, "Would another program care about the fields I am thinking of extending the class with?" The answer to that question will determine if you extend the original class, or make a function (or your own class like PersonAnalysisData or something).)

Carriage return and Line feed... Are both required in C#?

It's always a good idea, and while it's not always required, the Windows standard is to include both.

\n actually represents a Line Feed, or the number 10, and canonically a Line Feed means just "move down one row" on terminals and teletypes.

\r represents CR, a Carriage Return, or the number 13. On Windows, Unix, and most terminals, a CR moves the cursor to the beginning of the line. (This is not the case for 8-bit computers: most of those do advance to the next line with a CR.)

Anyway, some processes, such as the text console, might add a CR automatically when you send an LF. However, since the CR simply moves to the start of the line, there's no harm in sending the CR twice.

On the other hand, dialog boxes, text boxes, and other display elements require both CR and LF to properly start a new line.

Since there's really no downside to sending both, and both are required in some situations, the simplest policy is to use both, if you're not sure.

Android SDK location should not contain whitespace, as this cause problems with NDK tools

There is another way:

  1. Open up CMD (as Administrator)
  2. Type: mklink /J C:\Program-Files "C:\Program Files" (Or in my case mklink /J C:\Program-Files-(x86) "C:\Program Files (x86)")
  3. Hit enter
  4. Magic happens! (Check your C drive)

Now you can point to C:\Program-Files (C:\Program-Files-(x86)).

What is a 'Closure'?

Here is another real life example, and using a scripting language popular in games - Lua. I needed to slightly change the way a library function worked to avoid a problem with stdin not being available.

local old_dofile = dofile

function dofile( filename )
  if filename == nil then
    error( 'Can not use default of stdin.' )
  end

  old_dofile( filename )
end

The value of old_dofile disappears when this block of code finishes it's scope (because it's local), however the value has been enclosed in a closure, so the new redefined dofile function CAN access it, or rather a copy stored along with the function as an 'upvalue'.

Query grants for a table in postgres

Here is a script which generates grant queries for a particular table. It omits owner's privileges.

SELECT 
    format (
      'GRANT %s ON TABLE %I.%I TO %I%s;',
      string_agg(tg.privilege_type, ', '),
      tg.table_schema,
      tg.table_name,
      tg.grantee,
      CASE
        WHEN tg.is_grantable = 'YES' 
        THEN ' WITH GRANT OPTION' 
        ELSE '' 
      END
    )
  FROM information_schema.role_table_grants tg
  JOIN pg_tables t ON t.schemaname = tg.table_schema AND t.tablename = tg.table_name
  WHERE
    tg.table_schema = 'myschema' AND
    tg.table_name='mytable' AND
    t.tableowner <> tg.grantee
  GROUP BY tg.table_schema, tg.table_name, tg.grantee, tg.is_grantable;

What value could I insert into a bit type column?

Your issue is in PHPMyAdmin itself. Some versions do not display the value of bit columns, even though you did set it correctly.

What is __pycache__?

When you run a program in python, the interpreter compiles it to bytecode first (this is an oversimplification) and stores it in the __pycache__ folder. If you look in there you will find a bunch of files sharing the names of the .py files in your project's folder, only their extensions will be either .pyc or .pyo. These are bytecode-compiled and optimized bytecode-compiled versions of your program's files, respectively.

As a programmer, you can largely just ignore it... All it does is make your program start a little faster. When your scripts change, they will be recompiled, and if you delete the files or the whole folder and run your program again, they will reappear (unless you specifically suppress that behavior).

When you're sending your code to other people, the common practice is to delete that folder, but it doesn't really matter whether you do or don't. When you're using version control (git), this folder is typically listed in the ignore file (.gitignore) and thus not included.

If you are using cpython (which is the most common, as it's the reference implementation) and you don't want that folder, then you can suppress it by starting the interpreter with the -B flag, for example

python -B foo.py

Another option, as noted by tcaswell, is to set the environment variable PYTHONDONTWRITEBYTECODE to any value (according to python's man page, any "non-empty string").

How can you check for a #hash in a URL using JavaScript?

window.location.hash 

will return the hash identifier

In R, how to find the standard error of the mean?

As I'm going back to this question every now and then and because this question is old, I'm posting a benchmark for the most voted answers.

Note, that for @Ian's and @John's answers I created another version. Instead of using length(x), I used sum(!is.na(x)) (to avoid NAs). I used a vector of 10^6, with 1,000 repetitions.

library(microbenchmark)

set.seed(123)
myVec <- rnorm(10^6)

IanStd <- function(x) sd(x)/sqrt(length(x))

JohnSe <- function(x) sqrt(var(x)/length(x))

IanStdisNA <- function(x) sd(x)/sqrt(sum(!is.na(x)))

JohnSeisNA <- function(x) sqrt(var(x)/sum(!is.na(x)))

AranStderr <- function(x, na.rm=FALSE) {
  if (na.rm) x <- na.omit(x)
  sqrt(var(x)/length(x))
}

mbm <- microbenchmark(
  "plotrix" = {plotrix::std.error(myVec)},
  "IanStd" = {IanStd(myVec)},
  "JohnSe" = {JohnSe(myVec)},
  "IanStdisNA" = {IanStdisNA(myVec)},
  "JohnSeisNA" = {JohnSeisNA(myVec)},
  "AranStderr" = {AranStderr(myVec)}, 
  times = 1000)

mbm

Results:

Unit: milliseconds
       expr     min       lq      mean   median       uq      max neval cld
    plotrix 10.3033 10.89360 13.869947 11.36050 15.89165 125.8733  1000   c
     IanStd  4.3132  4.41730  4.618690  4.47425  4.63185   8.4388  1000 a  
     JohnSe  4.3324  4.41875  4.640725  4.48330  4.64935   9.4435  1000 a  
 IanStdisNA  8.4976  8.99980 11.278352  9.34315 12.62075 120.8937  1000  b 
 JohnSeisNA  8.5138  8.96600 11.127796  9.35725 12.63630 118.4796  1000  b 
 AranStderr  4.3324  4.41995  4.634949  4.47440  4.62620  14.3511  1000 a  


library(ggplot2)
autoplot(mbm)

enter image description here

Check if an element is present in an array

Single line code.. will return true or false

!!(arr.indexOf("val")+1)

What is the difference between "is None" and "== None"

In this case, they are the same. None is a singleton object (there only ever exists one None).

is checks to see if the object is the same object, while == just checks if they are equivalent.

For example:

p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent

But since there is only one None, they will always be the same, and is will return True.

p = None
q = None
p is q # True because they are both pointing to the same "None"

xlsxwriter: is there a way to open an existing worksheet in my workbook?

You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name

According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.

"Release 0.8.7 - May 13 2016

-Fix for issue when inserting read-only images on Windows. Issue #352.

-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.

-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."

Read and write to binary files in C?

this questions is linked with the question How to write binary data file on C and plot it using Gnuplot by CAMILO HG. I know that the real problem have two parts: 1) Write the binary data file, 2) Plot it using Gnuplot.

The first part has been very clearly answered here, so I do not have something to add.

For the second, the easy way is send the people to the Gnuplot manual, and I sure someone find a good answer, but I do not find it in the web, so I am going to explain one solution (which must be in the real question, but I new in stackoverflow and I can not answer there):

After write your binary data file using fwrite(), you should create a very simple program in C, a reader. The reader only contains the same structure as the writer, but you use fread() instead fwrite(). So it is very ease to generate this program: copy in the reader.c file the writing part of your original code and change write for read (and "wb" for "rb"). In addition, you could include some checks for the data, for example, if the length of the file is correct. And finally, your program need to print the data in the standard output using a printf().

For be clear: your program run like this

$ ./reader data.dat

X_position Y_position  (it must be a comment for Gnuplot)*

1.23 2.45

2.54 3.12

5.98 9.52

Okey, with this program, in Gnuplot you only need to pipe the standard output of the reader to the Gnuplot, something like this:

plot '< ./reader data.dat'

This line, run the program reader, and the output is connected with Gnuplot and it plot the data.

*Because Gnuplot is going to read the output of the program, you must know what can Gnuplot read and plot and what can not.

Basic text editor in command prompt?

vim may be challenging for beginners. For a quick-and-dirty Windows console-mode text editor, I would suggest Kinesics Text Editor.

Eclipse "Invalid Project Description" when creating new project from existing source

Go to the .project file of your project make sure it display the same name as displayed in project folder. if not change the name. it will work.

How to get all registered routes in Express?

In express 4.*

//Obtiene las rutas declaradas de la API
    let listPathRoutes: any[] = [];
    let rutasRouter = _.filter(application._router.stack, rutaTmp => rutaTmp.name === 'router');
    rutasRouter.forEach((pathRoute: any) => {
        let pathPrincipal = pathRoute.regexp.toString();
        pathPrincipal = pathPrincipal.replace('/^\\','');
        pathPrincipal = pathPrincipal.replace('?(?=\\/|$)/i','');
        pathPrincipal = pathPrincipal.replace(/\\\//g,'/');
        let routesTemp = _.filter(pathRoute.handle.stack, rutasTmp => rutasTmp.route !== undefined);
        routesTemp.forEach((route: any) => {
            let pathRuta = `${pathPrincipal.replace(/\/\//g,'')}${route.route.path}`;
            let ruta = {
                path: pathRuta.replace('//','/'),
                methods: route.route.methods
            }
            listPathRoutes.push(ruta);
        });
    });console.log(listPathRoutes)

Convert a double to a QString

Instead of QString::number() i would use QLocale::toString(), so i can get locale aware group seperatores like german "1.234.567,89".

How to Query an NTP Server using C#?

A modified version to compensate network times and calculate with DateTime-Ticks (more precise than milliseconds)

public static DateTime GetNetworkTime()
{
  const string NtpServer = "pool.ntp.org";

  const int DaysTo1900 = 1900 * 365 + 95; // 95 = offset for leap-years etc.
  const long TicksPerSecond = 10000000L;
  const long TicksPerDay = 24 * 60 * 60 * TicksPerSecond;
  const long TicksTo1900 = DaysTo1900 * TicksPerDay;

  var ntpData = new byte[48];
  ntpData[0] = 0x1B; // LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)

  var addresses = Dns.GetHostEntry(NtpServer).AddressList;
  var ipEndPoint = new IPEndPoint(addresses[0], 123);
  long pingDuration = Stopwatch.GetTimestamp(); // temp access (JIT-Compiler need some time at first call)
  using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
  {
    socket.Connect(ipEndPoint);
    socket.ReceiveTimeout = 5000;
    socket.Send(ntpData);
    pingDuration = Stopwatch.GetTimestamp(); // after Send-Method to reduce WinSocket API-Call time

    socket.Receive(ntpData);
    pingDuration = Stopwatch.GetTimestamp() - pingDuration;
  }

  long pingTicks = pingDuration * TicksPerSecond / Stopwatch.Frequency;

  // optional: display response-time
  // Console.WriteLine("{0:N2} ms", new TimeSpan(pingTicks).TotalMilliseconds);

  long intPart = (long)ntpData[40] << 24 | (long)ntpData[41] << 16 | (long)ntpData[42] << 8 | ntpData[43];
  long fractPart = (long)ntpData[44] << 24 | (long)ntpData[45] << 16 | (long)ntpData[46] << 8 | ntpData[47];
  long netTicks = intPart * TicksPerSecond + (fractPart * TicksPerSecond >> 32);

  var networkDateTime = new DateTime(TicksTo1900 + netTicks + pingTicks / 2);

  return networkDateTime.ToLocalTime(); // without ToLocalTime() = faster
}

git-diff to ignore ^M

Also see:

core.whitespace = cr-at-eol

or equivalently,

[core]
    whitespace = cr-at-eol

where whitespace is preceded by a tab character.

SQL Server - copy stored procedures from one db to another

In Mgmt Studio, right-click on your original database then Tasks then Generate Scripts... - follow the wizard.

Converting stream of int's to char's in java

Basing my answer on assumption that user just wanted to literaaly convert an int to char , for example

Input: 
int i = 5; 
Output:
char c = '5'

This has been already answered above, however if the integer value i > 10, then need to use char array.

char[] c = String.valueOf(i).toCharArray();

JavaScript Object Id

No, objects don't have a built in identifier, though you can add one by modifying the object prototype. Here's an example of how you might do that:

(function() {
    var id = 0;

    function generateId() { return id++; };

    Object.prototype.id = function() {
        var newId = generateId();

        this.id = function() { return newId; };

        return newId;
    };
})();

That said, in general modifying the object prototype is considered very bad practice. I would instead recommend that you manually assign an id to objects as needed or use a touch function as others have suggested.

Redirect on select option in select box

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value=""></option>
    <option value="http://google.com">Google</option>
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

Find duplicate records in MongoDB

The answer anhic gave can be very inefficient if you have a large database and the attribute name is present only in some of the documents.

To improve efficiency you can add a $match to the aggregation.

db.collection.aggregate(
    {"$match": {"name" :{ "$ne" : null } } }, 
    {"$group" : {"_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
)

Native query with named parameter fails with "Not all named parameters have been set"

Use set Parameter from query.

Query q = (Query) em.createNativeQuery("SELECT count(*) FROM mytable where username = ?1");
q.setParameter(1, "test");

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

As Coli88 said, you should check the UINavigationBarDelegate protocol.

In a more general way, you can also use the - (void)viewWillDisapear:(BOOL)animated to perform custom work when the view retained by the currently visible view controller is about to disappear. Unfortunately, this would cover bother the push and the pop cases.

VueJS conditionally add an attribute for an element

Simplest form:

<input :required="test">   // if true
<input :required="!test">  // if false
<input :required="!!test"> // test ? true : false

First char to upper case

Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.

What replaceFirst() does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.

What you want to do is convert the string to an array using the String class' charAt() method, and then use Character.toUpperCase() to change the character to upper case (obviously). Your code would look like this:

char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);

Or, if you feel comfortable with more complex, one-lined java code:

betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);

Both of these do the same thing, which is converting the first character of userIdea to an upper case character.

Inner Joining three tables

select *
from
    tableA a
        inner join
    tableB b
        on a.common = b.common
        inner join 
    TableC c
        on b.common = c.common

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

For those who are getting to this question via google... this error can also happen if you try to rename a field that is acting as a foreign key.

Hide header in stack navigator React navigation

I am using header : null instead of header : { visible : true } i am using react-native cli. this is the example :

static navigationOptions = {
   header : null   
};

Python xticks in subplots

There are two ways:

  1. Use the axes methods of the subplot object (e.g. ax.set_xticks and ax.set_xticklabels) or
  2. Use plt.sca to set the current axes for the pyplot state machine (i.e. the plt interface).

As an example (this also illustrates using setp to change the properties of all of the subplots):

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=3, ncols=4)

# Set the ticks and ticklabels for all axes
plt.setp(axes, xticks=[0.1, 0.5, 0.9], xticklabels=['a', 'b', 'c'],
        yticks=[1, 2, 3])

# Use the pyplot interface to change just one subplot...
plt.sca(axes[1, 1])
plt.xticks(range(3), ['A', 'Big', 'Cat'], color='red')

fig.tight_layout()
plt.show()

enter image description here

How can I update npm on Windows?

How to Update Node.js:

  1. Uninstall Node.js. Click the Start menu, type "Change or Remove a Program", click on the item shown, find Node.js in the list and uninstall it.

  2. Delete directories, both C:\Program Files (x86)\nodejs\ and C:\Program Files\nodejs\ if they exist.

  3. Install the latest, https://nodejs.org/en/download

    The uninstall/delete/install seems unnecessary, but it often is and this will save your time.     These instructions come from Microsoft.

How to Update NPM:

    https://www.npmjs.com/package/npm-windows-upgrade

    This is the official documentation for upgrading npm on windows.

All was tested and working on Windows 10 (2017).

Generate class from database table

I'm confused as to what you want out of this, but here are the general options when designing what you want to design.

  1. Using the built-in ORM in your version Visual Studio.
  2. Write one yourself, similar to your code example. As usual, a tutorial is your best friend if you're not sure how.
  3. Use an alternative ORM such as NHibernate.

Sublime Text 3 how to change the font size of the file sidebar?

Default.sublime-theme file works unless you have installed a theme. If you did, go to your theme's github repo and download the your_theme.sublime-theme file and put it in your 'User' folder. In that file, find "class": "sidebar_label", add "font.size":16 to that section.

Function of Project > Clean in Eclipse

It removes whatever already-compiled files are in your project so that you can do a complete fresh rebuild.

Angular 5 - Copy to clipboard

The best way to do this in Angular and keep the code simple is to use this project.

https://www.npmjs.com/package/ngx-clipboard

    <fa-icon icon="copy" ngbTooltip="Copy to Clipboard" aria-hidden="true" 
    ngxClipboard [cbContent]="target value here" 
    (cbOnSuccess)="copied($event)"></fa-icon>

Are querystring parameters secure in HTTPS (HTTP + SSL)?

Yes. The querystring is also encrypted with SSL. Nevertheless, as this article shows, it isn't a good idea to put sensitive information in the URL. For example:

URLs are stored in web server logs - typically the whole URL of each request is stored in a server log. This means that any sensitive data in the URL (e.g. a password) is being saved in clear text on the server

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

Since Java 8, you can use:

How to import Google Web Font in CSS file?

  1. Just go to https://fonts.google.com/
  2. Add font by clicking +
  3. Go to selected font > Embed > @IMPORT > copy url and paste in your .css file above body tag.
  4. It's done.

JQUERY ajax passing value from MVC View to Controller

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatu`enter code here`s) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

How do I set a program to launch at startup

You can do this with the win32 class in the Microsoft namespace

using Microsoft.Win32;

using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
 {
            key.SetValue("aldwin", "\"" + Application.ExecutablePath + "\"");
 }

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

The regex you're looking for is ^[A-Za-z.\s_-]+$

  • ^ asserts that the regular expression must match at the beginning of the subject
  • [] is a character class - any character that matches inside this expression is allowed
  • A-Z allows a range of uppercase characters
  • a-z allows a range of lowercase characters
  • . matches a period rather than a range of characters
  • \s matches whitespace (spaces and tabs)
  • _ matches an underscore
  • - matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-) instead and put it anywhere in the character class, but that's less clear
  • + asserts that the preceding expression (in our case, the character class) must match one or more times
  • $ Finally, this asserts that we're now at the end of the subject

When you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.

Custom Listview Adapter with filter Android

You can use the Filterable interface on your Adapter, have a look at the example below:

public class SearchableAdapter extends BaseAdapter implements Filterable {
    
    private List<String>originalData = null;
    private List<String>filteredData = null;
    private LayoutInflater mInflater;
    private ItemFilter mFilter = new ItemFilter();
    
    public SearchableAdapter(Context context, List<String> data) {
        this.filteredData = data ;
        this.originalData = data ;
        mInflater = LayoutInflater.from(context);
    }
 
    public int getCount() {
        return filteredData.size();
    }
 
    public Object getItem(int position) {
        return filteredData.get(position);
    }
 
    public long getItemId(int position) {
        return position;
    }
 
    public View getView(int position, View convertView, ViewGroup parent) {
        // A ViewHolder keeps references to children views to avoid unnecessary calls
        // to findViewById() on each row.
        ViewHolder holder;
 
        // When convertView is not null, we can reuse it directly, there is no need
        // to reinflate it. We only inflate a new View when the convertView supplied
        // by ListView is null.
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null);
 
            // Creates a ViewHolder and store references to the two children views
            // we want to bind data to.
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.list_view);
 
            // Bind the data efficiently with the holder.
 
            convertView.setTag(holder);
        } else {
            // Get the ViewHolder back to get fast access to the TextView
            // and the ImageView.
            holder = (ViewHolder) convertView.getTag();
        }
 
        // If weren't re-ordering this you could rely on what you set last time
        holder.text.setText(filteredData.get(position));
 
        return convertView;
    }
    
    static class ViewHolder {
        TextView text;
    }
 
    public Filter getFilter() {
        return mFilter;
    }
 
    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            
            String filterString = constraint.toString().toLowerCase();
            
            FilterResults results = new FilterResults();
            
            final List<String> list = originalData;
 
            int count = list.size();
            final ArrayList<String> nlist = new ArrayList<String>(count);
 
            String filterableString ;
            
            for (int i = 0; i < count; i++) {
                filterableString = list.get(i);
                if (filterableString.toLowerCase().contains(filterString)) {
                    nlist.add(filterableString);
                }
            }
            
            results.values = nlist;
            results.count = nlist.size();
 
            return results;
        }
 
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredData = (ArrayList<String>) results.values;
            notifyDataSetChanged();
        }
 
    }
}

In your Activity or Fragment where of Adapter is instantiated :

editTxt.addTextChangedListener(new TextWatcher() {
  
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        System.out.println("Text ["+s+"]");
        
        mSearchableAdapter.getFilter().filter(s.toString());                           
    }
     
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
         
    }
     
    @Override
    public void afterTextChanged(Editable s) {
    }
});

Here are the links for the original source and another example

error: cast from 'void*' to 'int' loses precision

Well it does this because you are converting a 64 bits pointer to an 32 bits integer so you loose information.

You can use a 64 bits integer instead howerver I usually use a function with the right prototype and I cast the function type : eg.

void thread_func(int arg){
...
}

and I create the thread like this :

pthread_create(&tid, NULL, (void*(*)(void*))thread_func, (void*)arg);

What is a handle in C++?

A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.

For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense).

EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.

Bootstrap 4 navbar color

To change navbar background color:

.navbar-custom {

    background-color: yourcolor !important;
}

How to find the kth largest element in an unsorted array of length n in O(n)?

Sexy quickselect in Python

def quickselect(arr, k):
    '''
     k = 1 returns first element in ascending order.
     can be easily modified to return first element in descending order
    '''

    r = random.randrange(0, len(arr))

    a1 = [i for i in arr if i < arr[r]] '''partition'''
    a2 = [i for i in arr if i > arr[r]]

    if k <= len(a1):
        return quickselect(a1, k)
    elif k > len(arr)-len(a2):
        return quickselect(a2, k - (len(arr) - len(a2)))
    else:
        return arr[r]

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

I faced the same problem,Eclipse splash screen for a second and it disappears.Then i noticed due to auto update of java there are two java version installed in my system. when i uninstalled one eclipse started working.

Thanks you..

How to rename JSON key

As mentioned by evanmcdonnal, the easiest solution is to process this as string instead of JSON,

_x000D_
_x000D_
var json = [{"_id":"5078c3a803ff4197dc81fbfb","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","image":"some_image_url","name":"Name 2"}];_x000D_
    _x000D_
json = JSON.parse(JSON.stringify(json).split('"_id":').join('"id":'));_x000D_
_x000D_
document.write(JSON.stringify(json));
_x000D_
_x000D_
_x000D_

This will convert given JSON data to string and replace "_id" to "id" then converting it back to the required JSON format. But I used split and join instead of replace, because replace will replace only the first occurrence of the string.

List all tables in postgresql information_schema

The "\z" COMMAND is also a good way to list tables when inside the interactive psql session.

eg.

# psql -d mcdb -U admin -p 5555
mcdb=# /z
                           Access privileges for database "mcdb"
 Schema |              Name              |   Type   |           Access privileges
--------+--------------------------------+----------+---------------------------------------
 public | activities                     | table    |
 public | activities_id_seq              | sequence |
 public | activities_users_mapping       | table    |
[..]
 public | v_schedules_2                  | view     | {admin=arwdxt/admin,viewuser=r/admin}
 public | v_systems                      | view     |
 public | vapp_backups                   | table    |
 public | vm_client                      | table    |
 public | vm_datastore                   | table    |
 public | vmentity_hle_map               | table    |
(148 rows)

Connecting to a network folder with username/password in Powershell

At first glance one really wants to use New-PSDrive supplying it credentials.

> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user

Fails!

New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.

The documentation states that you can provide a PSCredential object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.

Therefore you can either use net use or the WScript.Network object, calling the MapNetworkDrive function:

$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")

Edit for New-PSDrive in PowerShell 3.0

Apparently with newer versions of PowerShell, the New-PSDrive cmdlet works to map network shares with credentials!

New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist

Border around specific rows in a table?

An easier way is to make the table a server side control. You could use something similar to this:

Dim x As Integer
table1.Border = "1"

'Change the first 10 rows to have a black border
 For x = 1 To 10
     table1.Rows(x).BorderColor = "Black"
 Next

'Change the rest of the rows to white
 For x = 11 To 22
     table1.Rows(x).BorderColor = "White"
 Next

MINGW64 "make build" error: "bash: make: command not found"

Try using cmake itself. In the build directory, run:

cmake --build .

Get Hard disk serial Number

Below a fully functional method to get hard disk serial number:

public string GetHardDiskSerialNo()
    {
        ManagementClass mangnmt = new ManagementClass("Win32_LogicalDisk");
        ManagementObjectCollection mcol = mangnmt.GetInstances();
        string result = "";
        foreach (ManagementObject strt in mcol)
        {
            result += Convert.ToString(strt["VolumeSerialNumber"]);
        }
        return result;
    }

Convert integer to class Date

Another way to get the same result:

date <- strptime(v,format="%Y%m%d")

Use -notlike to filter out multiple strings in PowerShell

don't use -notLike, -notMatch with Regular-Expression works in one line:

Get-MailBoxPermission -id newsletter | ? {$_.User -NotMatch "NT-AUTORIT.*|.*-Admins|.*Administrators|.*Manage.*"}

Docker error cannot delete docker container, conflict: unable to remove repository reference

Remove just the containers associated with a specific image

docker ps -a | grep training/webapp | cut -d ' ' -f 1 | xargs docker rm
  • ps -a: list all containers
  • grep training/webapp : filter out everything but the containers started from the training/webapp image
  • cut -d ' ' -f 1: list only the container ids (first field when delimited by space)
  • xargs docker rm : send the container id list output to the docker rm command to remove the container

Remove lines that contain certain string

You could simply not include the line into the new file instead of doing replace.

for line in infile :
     if 'bad' not in line and 'naughty' not in line:
            newopen.write(line)

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

Angular.js programmatically setting a form field to dirty

Made a jsFiddle just for you that solves this issue. simply set $dirty to true, but with a $timeout 0 so it runs after DOM was loaded.

Find it here: JsFiddle

$timeout(function () {
  $scope.form.uName.$dirty = true;
}, 0);

How to get the background color code of an element in hex?

My beautiful non-standard solution

HTML

<div style="background-color:#f5b405"></div>

jQuery

$(this).attr("style").replace("background-color:", "");

Result

#f5b405

Rounding to two decimal places in Python 2.7?

A rather simple workaround is to convert the float into string first, the select the substring of the first four numbers, finally convert the substring back to float. For example:

>>> out1 = 1.2345
>>> out1 = float(str(out1)[0:4])
>>> out1

May not be super efficient but simple and works :)

Cannot kill Python script with Ctrl-C

An improved version of @Thomas K's answer:

  • Defining an assistant function is_any_thread_alive() according to this gist, which can terminates the main() automatically.

Example codes:

import threading

def job1():
    ...

def job2():
    ...

def is_any_thread_alive(threads):
    return True in [t.is_alive() for t in threads]

if __name__ == "__main__":
    ...
    t1 = threading.Thread(target=job1,daemon=True)
    t2 = threading.Thread(target=job2,daemon=True)
    t1.start()
    t2.start()

    while is_any_thread_alive([t1,t2]):
        time.sleep(0)

Can I pass a JavaScript variable to another browser window?

Alternatively, you can add it to the URL and let the scripting language (PHP, Perl, ASP, Python, Ruby, whatever) handle it on the other side. Something like:

var x = 10;
window.open('mypage.php?x='+x);

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

It's actually a simple answer.

Your function is returning a string rather than the div node. appendChild can only append a node.

For example, if you try to appendChild the string:

var z = '<p>test satu dua tiga</p>'; // is a string 
document.body.appendChild(z);

The above code will never work. What will work is:

var z = document.createElement('p'); // is a node
z.innerHTML = 'test satu dua tiga';
document.body.appendChild(z);

Android- create JSON Array and JSON Object

            Map<String, String> params = new HashMap<String, String>();

            //** Temp array
            List<String[]> tmpArray = new ArrayList<>();
            tmpArray.add(new String[]{"b001","book1"}); 
            tmpArray.add(new String[]{"b002","book2"}); 

            //** Json Array Example
            JSONArray jrrM = new JSONArray();
            for(int i=0; i<tmpArray.size(); i++){
                JSONArray jrr = new JSONArray();
                jrr.put(tmpArray.get(i)[0]);
                jrr.put(tmpArray.get(i)[1]);
                jrrM.put(jrr);
            }

           //Json Object Example
           JSONObject jsonObj = new JSONObject();
            try {
                jsonObj.put("plno","000000001");                   
                jsonObj.put("rows", jrrM);

            }catch (JSONException ex){
                ex.printStackTrace();
            }   


            // Bundles them
            params.put("user", "guest");
            params.put("tb", "book_store");
            params.put("action","save");
            params.put("data", jsonObj.toString());

           // Now you can send them to the server.

How do I compare a value to a backslash?

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):
    do_stuff()

Is it possible to use std::string in a constexpr?

Since the problem is the non-trivial destructor so if the destructor is removed from the std::string, it's possible to define a constexpr instance of that type. Like this

struct constexpr_str {
    char const* str;
    std::size_t size;

    // can only construct from a char[] literal
    template <std::size_t N>
    constexpr constexpr_str(char const (&s)[N])
        : str(s)
        , size(N - 1) // not count the trailing nul
    {}
};

int main()
{
    constexpr constexpr_str s("constString");

    // its .size is a constexpr
    std::array<int, s.size> a;
    return 0;
}

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

What is "entropy and information gain"?

When I was implementing an algorithm to calculate the entropy of an image I found these links, see here and here.

This is the pseudo-code I used, you'll need to adapt it to work with text rather than images but the principles should be the same.

//Loop over image array elements and count occurrences of each possible
//pixel to pixel difference value. Store these values in prob_array
for j = 0, ysize-1 do $
    for i = 0, xsize-2 do begin
       diff = array(i+1,j) - array(i,j)
       if diff lt (array_size+1)/2 and diff gt -(array_size+1)/2 then begin
            prob_array(diff+(array_size-1)/2) = prob_array(diff+(array_size-1)/2) + 1
       endif
     endfor

//Convert values in prob_array to probabilities and compute entropy
n = total(prob_array)

entrop = 0
for i = 0, array_size-1 do begin
    prob_array(i) = prob_array(i)/n

    //Base 2 log of x is Ln(x)/Ln(2). Take Ln of array element
    //here and divide final sum by Ln(2)
    if prob_array(i) ne 0 then begin
        entrop = entrop - prob_array(i)*alog(prob_array(i))
    endif
endfor

entrop = entrop/alog(2)

I got this code from somewhere, but I can't dig out the link.

How to create an Oracle sequence starting with max value from a table?

If you can use PL/SQL, try (EDIT: Incorporates Neil's xlnt suggestion to start at next higher value):

SELECT 'CREATE SEQUENCE transaction_sequence MINVALUE 0 START WITH '||MAX(trans_seq_no)+1||' INCREMENT BY 1 CACHE 20'
  INTO v_sql
  FROM transaction_log;

EXECUTE IMMEDIATE v_sql;

Another point to consider: By setting the CACHE parameter to 20, you run the risk of losing up to 19 values in your sequence if the database goes down. CACHEd values are lost on database restarts. Unless you're hitting the sequence very often, or, you don't care that much about gaps, I'd set it to 1.

One final nit: the values you specified for CACHE and INCREMENT BY are the defaults. You can leave them off and get the same result.

Java String - See if a string contains only numbers and not letters

Apache Commons Lang provides org.apache.commons.lang.StringUtils.isNumeric(CharSequence cs), which takes as an argument a String and checks if it consists of purely numeric characters (including numbers from non-Latin scripts). That method returns false if there are characters such as space, minus, plus, and decimal separators such as comma and dot.

Other methods of that class allow for further numeric checks.

What values for checked and selected are false?

The checked and selected attributes are allowed only two values, which are a copy of the attribute name and (from HTML 5 onwards) an empty string. Giving any other value is an error.

If you don't want to set the attribute, then the entire attribute must be omitted.

Note that in HTML 4 you may omit everything except the value. HTML 5 changed this to omit everything except the name (which makes no practical difference).

Thus, the complete (aside from variations in cAsE) set of valid representations of the attribute are:

<input ... checked="checked"> <!-- All versions of HTML / XHTML -->
<input ...          checked > <!-- Only HTML 4.01 and earlier -->
<input ... checked          > <!-- Only HTML 5 and later -->
<input ... checked=""       > <!-- Only HTML 5 and later -->

Documents served as text/html (HTML or XHTML) will be fed through a tag soup parser, and the presence of a checked attribute (with any value) will be treated as "This element should be checked". Thus, while invalid, checked="true", checked="yes", and checked="false" will all trigger the checked state.

I've not had any inclination to find out what error recovery mechanisms are in place for XML parsing mode should a different value be given to the attribute, but I would expect that the legacy of HTML and/or simple error recovery would treat it in the same way: If the attribute is there then the element is checked.

(And all the above applies equally to selected as it does to checked.)

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

jQuery.active function

For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:

jQuery.ajaxPrefilter(function( options ) {
    options.global = true;
});

Keep in mind that you'll need a timeout on your JSONP request to catch failures.

Apache error: _default_ virtualhost overlap on port 443

It is highly unlikely that adding NameVirtualHost *:443 is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).

If you're running a relatively stock Apache configuration, you probably have this somewhere:

<VirtualHost _default_:443>

Your best bet is to either:

  • Place your additional SSL configuration into this existing VirtualHost container, or
  • Comment out this entire VirtualHost block and create a new one. Don't forget to include all the relevant SSL options.

What is the easiest way to initialize a std::vector with hardcoded elements?

If you want something on the same general order as Boost::assign without creating a dependency on Boost, the following is at least vaguely similar:

template<class T>
class make_vector {
    std::vector<T> data;
public:
    make_vector(T const &val) { 
        data.push_back(val);
    }

    make_vector<T> &operator,(T const &t) {
        data.push_back(t);
        return *this;
    }

    operator std::vector<T>() { return data; }
};

template<class T> 
make_vector<T> makeVect(T const &t) { 
    return make_vector<T>(t);
}

While I wish the syntax for using it was cleaner, it's still not particularly awful:

std::vector<int> x = (makeVect(1), 2, 3, 4);

In Rails, how do you render JSON using a view?

As others have mentioned you need a users/show.json view, but there are options to consider for the templating language...

ERB

Works out of the box. Great for HTML, but you'll quickly find it's awful for JSON.

RABL

Good solution. Have to add a dependency and learn its DSL.

JSON Builder

Same deal as RABL: Good solution. Have to add a dependency and learn its DSL.

Plain Ruby

Ruby is awesome at generating JSON and there's nothing new to learn as you can call to_json on a Hash or an AR object. Simply register the .rb extension for templates (in an initializer):

ActionView::Template.register_template_handler(:rb, :source.to_proc)

Then create the view users/show.json.rb:

@user.to_json

For more info on this approach see http://railscasts.com/episodes/379-template-handlers

Finding the 'type' of an input element

Check the type property. Would that suffice?

How to remove \xa0 from string in Python?

In Beautiful Soup, you can pass get_text() the strip parameter, which strips white space from the beginning and end of the text. This will remove \xa0 or any other white space if it occurs at the start or end of the string. Beautiful Soup replaced an empty string with \xa0 and this solved the problem for me.

mytext = soup.get_text(strip=True)

What does -XX:MaxPermSize do?

In Java 8 that parameter is commonly used to print a warning message like this one:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0

The reason why you get this message in Java 8 is because Permgen has been replaced by Metaspace to address some of PermGen's drawbacks (as you were able to see for yourself, one of those drawbacks is that it had a fixed size).

FYI: an article on Metaspace: http://java-latte.blogspot.in/2014/03/metaspace-in-java-8.html

How to convert PDF files to images

I used PDFiumSharp and ImageSharp in a .NET Standard 2.1 class library.

/// <summary>
/// Saves a thumbnail (jpg) to the same folder as the PDF file, using dimensions 300x423,
/// which corresponds to the aspect ratio of 'A' paper sizes like A4 (ratio h/w=sqrt(2))
/// </summary>
/// <param name="pdfPath">Source path of the pdf file.</param>
/// <param name="thumbnailPath">Target path of the thumbnail file.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public static void SaveThumbnail(string pdfPath, string thumbnailPath = "", int width = 300, int height = 423)
{
    using var pdfDocument = new PdfDocument(pdfPath);
    var firstPage = pdfDocument.Pages[0];

    using var pageBitmap = new PDFiumBitmap(width, height, true);

    firstPage.Render(pageBitmap);

    var imageJpgPath = string.IsNullOrWhiteSpace(thumbnailPath)
        ? Path.ChangeExtension(pdfPath, "jpg")
        : thumbnailPath;
    var image = Image.Load(pageBitmap.AsBmpStream());

    // Set the background to white, otherwise it's black. https://github.com/SixLabors/ImageSharp/issues/355#issuecomment-333133991
    image.Mutate(x => x.BackgroundColor(Rgba32.White));

    image.Save(imageJpgPath, new JpegEncoder());
}

div with dynamic min-height based on browser window height

It's hard to do this.

There is a min-height: css style, but it doesn't work in all browsers. You can use it, but the biggest problem is that you will need to set it to something like 90% or numbers like that (percents), but the top and bottom divs use fixed pixel sizes, and you won't be able to reconcile them.

 var minHeight = $(window).height() -
                 $('#a').outerHeight(true) -
                 $('#c').outerHeight(true));

if($('#b').height() < minHeight) $('#b').height(minHeight);

I know a and c have fixed heights, but I rather measure them in case they change later.

Also, I am measuring the height of b (I don't want to make is smaller after all), but if there is an image in there that did not load the height can change, so watch out for things like that.

It may be safer to do:

$('#b').prepend('<div style="float: left; width: 1px; height: ' + minHeight + 'px;">&nbsp;</div>');

Which simply adds an element into that div with the correct height - that effectively acts as min-height even for browsers that don't have it. (You may want to add the element into your markup, and then just control the height of it via javascript instead of also adding it that way, that way you can take it into account when designing the layout.)

Change File Extension Using C#

The method GetFileNameWithoutExtension, as the name implies, does not return the extension on the file. In your case, it would only return "a". You want to append your ".Jpeg" to that result. However, at a different level, this seems strange, as image files have different metadata and cannot be converted so easily.

finding the type of an element using jQuery

The following will return true if the element is an input:

$("#elementId").is("input") 

or you can use the following to get the name of the tag:

$("#elementId").get(0).tagName

Kill python interpeter in linux from the terminal

pgrep -f youAppFile.py | xargs kill -9

pgrep returns the PID of the specific file will only kill the specific application.

How to pass parameter to function using in addEventListener?

No need to pass anything in. The function used for addEventListener will automatically have this bound to the current element. Simply use this in your function:

productLineSelect.addEventListener('change', getSelection, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Here's the fiddle: http://jsfiddle.net/dJ4Wm/


If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:

productLineSelect.addEventListener('change', function() {
    foo('bar');
}, false);

function foo(message) {
    alert(message);
}

Here's the fiddle: http://jsfiddle.net/t4Gun/


If you want to set the value of this manually, you can use the call method to call the function:

var self = this;
productLineSelect.addEventListener('change', function() {
    getSelection.call(self);
    // This'll set the `this` value inside of `getSelection` to `self`
}, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Scrolling to an Anchor using Transition/CSS3

If anybody is just like me willing to use jQuery, but still found himself looking to this question then this may help you guys:

https://html-online.com/articles/animated-scroll-anchorid-function-jquery/

_x000D_
_x000D_
$(document).ready(function () {_x000D_
            $("a.scrollLink").click(function (event) {_x000D_
                event.preventDefault();_x000D_
                $("html, body").animate({ scrollTop: $($(this).attr("href")).offset().top }, 500);_x000D_
            });_x000D_
        });
_x000D_
<a href="#anchor1" class="scrollLink">Scroll to anchor 1</a>_x000D_
<a href="#anchor2" class="scrollLink">Scroll to anchor 2</a>_x000D_
<p id="anchor1"><strong>Anchor 1</strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea.</p>_x000D_
<p id="anchor2"><strong>Anchor 2</strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas.</p>
_x000D_
_x000D_
_x000D_

How to store an output of shell script to a variable in Unix?

You should probably re-write the script to return a value rather than output it. Instead of:

a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
   success) echo script succeeded;;
   Failed) echo script failed;;
esac

you would be able to do:

if script.sh > /dev/null; then
    echo script succeeded
else
    echo script failed
fi

It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0 instead of printing success, and exit 1 instead of printing Failed. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.

Difference between jQuery’s .hide() and setting CSS to display: none

Looking at the jQuery code, this is what happens:

hide: function( speed, easing, callback ) {
    if ( speed || speed === 0 ) {
        return this.animate( genFx("hide", 3), speed, easing, callback);

    } else {
        for ( var i = 0, j = this.length; i < j; i++ ) {
            var display = jQuery.css( this[i], "display" );

            if ( display !== "none" ) {
                jQuery.data( this[i], "olddisplay", display );
            }
        }

        // Set the display of the elements in a second loop
        // to avoid the constant reflow
        for ( i = 0; i < j; i++ ) {
            this[i].style.display = "none";
        }

        return this;
    }
},

exception.getMessage() output with class name

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

public static void main(String[] args) {
    try {
        throw new RuntimeException("Cannot move file");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
    }
}

...you will see a popup that says exactly what you want.


However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:

public static void main(String[] args) {
    try {
        throw new Exception(new RuntimeException("Cannot move file"));
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                                      "Error: " + getRootCause(ex).getMessage());
    }
}

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

Replace part of a string with another string

If all strings are std::string, you'll find strange problems with the cutoff of characters if using sizeof() because it's meant for C strings, not C++ strings. The fix is to use the .size() class method of std::string.

sHaystack.replace(sHaystack.find(sNeedle), sNeedle.size(), sReplace);

That replaces sHaystack inline -- no need to do an = assignment back on that.

Example usage:

std::string sHaystack = "This is %XXX% test.";
std::string sNeedle = "%XXX%";
std::string sReplace = "my special";
sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
std::cout << sHaystack << std::endl;

how to set mongod --dbpath

For me it must have:

mongod --dbpath=/whatever/data/path

how to open an URL in Swift3

Above answer is correct but if you want to check you canOpenUrl or not try like this.

let url = URL(string: "http://www.facebook.com")!
if UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
    //If you want handle the completion block than 
    UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
         print("Open url : \(success)")
    })
}

Note: If you do not want to handle completion you can also write like this.

UIApplication.shared.open(url, options: [:])

No need to write completionHandler as it contains default value nil, check apple documentation for more detail.

Apply CSS Style to child elements

Here is some code that I recently wrote. I think that it provides a basic explanation of combining class/ID names with pseudoclasses.

_x000D_
_x000D_
.content {_x000D_
  width: 800px;_x000D_
  border: 1px solid black;_x000D_
  border-radius: 10px;_x000D_
  box-shadow: 0 0 5px 2px grey;_x000D_
  margin: 30px auto 20px auto;_x000D_
  /*height:200px;*/_x000D_
_x000D_
}_x000D_
p.red {_x000D_
  color: red;_x000D_
}_x000D_
p.blue {_x000D_
  color: blue;_x000D_
}_x000D_
p#orange {_x000D_
  color: orange;_x000D_
}_x000D_
p#green {_x000D_
  color: green;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Class practice</title>_x000D_
  <link href="wrench_favicon.ico" rel="icon" type="image/x-icon" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="content">_x000D_
    <p id="orange">orange</p>_x000D_
    <p id="green">green</p>_x000D_
    <p class="red">red</p>_x000D_
    <p class="blue">blue</p>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Change keystore password from no password to a non blank password

this way worked better for me:

echo y | keytool -storepasswd -storepass 123456 -keystore /tmp/IT-Root-CA.keystore -import -alias IT-Root-CA -file /etc/pki/ca-trust/source/anchors/IT-Root-CA.crt

machine running:

[root@rhel80-68]# cat /etc/redhat-release 
Red Hat Enterprise Linux release 8.1 (Ootpa)

How to develop or migrate apps for iPhone 5 screen resolution?

  1. Download and install latest version of Xcode.
  2. Set a Launch Screen File for your app (in the general tab of your target settings). This is how you get to use the full size of any screen, including iPad split view sizes in iOS 9.
  3. Test your app, and hopefully do nothing else, since everything should work magically if you had set auto resizing masks properly, or used Auto Layout.
  4. If you didn't, adjust your view layouts, preferably with Auto Layout.
  5. If there is something you have to do for the larger screens specifically, then it looks like you have to check height of [[UIScreen mainScreen] bounds] as there seems to be no specific API for that. As of iOS 8 there are also size classes that abstract screen sizes into regular or compact vertically and horizontally and are recommended way to adapt your UI.

How to delete a folder and all contents using a bat file in windows?

@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"

Explanation:

Removes (deletes) a directory.

RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path

/S      Removes all directories and files in the specified directory
        in addition to the directory itself.  Used to remove a directory
        tree.

/Q      Quiet mode, do not ask if ok to remove a directory tree with /S

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

for this small example:

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

while True:
    data = mysock.recv(512)
    if ( len(data) < 1 ) :
        break
    print (data);

mysock.close()

adding the "b" before 'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n' solved my problem

How to empty a list?

You could try:

alist[:] = []

Which means: Splice in the list [] (0 elements) at the location [:] (all indexes from start to finish)

The [:] is the slice operator. See this question for more information.

How do I close an Android alertdialog

Replying to an old post but hopefully somebody might find this useful. Do this instead

final AlertDialog builder = new AlertDialog.Builder(getActivity()).create();

You can then go ahead and do,

builder.dismiss();

get UTC timestamp in python with datetime

I think the correct way to phrase your question is Is there a way to get the timestamp by specifying the date in UTC?, because timestamp is just a number which is absolute, not relative. The relative (or timezone aware) piece is the date.

I find pandas very convenient for timestamps, so:

import pandas as pd
dt1 = datetime(2008, 1, 1, 0, 0, 0, 0)
ts1 = pd.Timestamp(dt1, tz='utc').timestamp()
# make sure you get back dt1
datetime.utcfromtimestamp(ts1)  

How to get JSON response from http.Get

You need upper case property names in your structs in order to be used by the json packages.

Upper case property names are exported properties. Lower case property names are not exported.

You also need to pass the your data object by reference (&data).

package main

import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type tracks struct {
    Toptracks []toptracks_info
}

type toptracks_info struct {
    Track []track_info
    Attr  []attr_info
}

type track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []streamable_info
    Artist     []artist_info
    Attr       []track_attr_info
}

type attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type streamable_info struct {
    Text      string
    Fulltrack string
}

type artist_info struct {
    Name string
    Mbid string
    Url  string
}

type track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"

    res, err := http.Get(url)

    if err != nil {
        panic(err.Error())
    }

    body, err := ioutil.ReadAll(res.Body)

    if err != nil {
        panic(err.Error())
    }

    var data tracks
    json.Unmarshal(body, &data)
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

How to use wait and notify in Java without IllegalMonitorStateException?

This looks like a situation for producer-consumer pattern. If you’re using java 5 or up, you may consider using blocking queue(java.util.concurrent.BlockingQueue) and leave the thread coordination work to the underlying framework/api implementation. See the example from java 5: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html or java 7 (same example): http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html