Programs & Examples On #Expandometaclass

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

How about a workaround? In my case I took the value of the textarea in a jQuery variable, and changed all "<p>&nbsp" to <p class="clear"> and clear class to have certain height and margin, as the following example:

jQuery

tinyMCE.triggerSave();
var val = $('textarea').val();
val = val.replace(/<p>&nbsp/g, '<p class="clear">');

the val is then saved to the database with the new val.

CSS

p.clear{height: 2px; margin-bottom: 3px;}

You can adjust the height & margin as you wish. And since 'p' is a display: block element. it should give you the expected output.

Hope that helps!

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

I was getting this error today and couldn't work it out for a while, but I realised it was after adding some RequireAttributes to my models and that some development seed data was not populating all of the required fields.
So just a note that if you're getting this error whilst updating the database through some sort of init strategy like DropCreateDatabaseIfModelChanges then you have to make sure that your seed data fulfils and satisfies any model data validation attributes.

I know this is slightly different to the problem in the question, but it's a popular question so I thought I'd add a bit more to the answer for others having the same issue as myself.
Hope this helps others :)

How to get a enum value from string in C#?

With some error handling...

uint key = 0;
string s = "HKEY_LOCAL_MACHINE";
try
{
   key = (uint)Enum.Parse(typeof(baseKey), s);
}
catch(ArgumentException)
{
   //unknown string or s is null
}

WCF ServiceHost access rights

Please open your Visual Studio as administrator:

enter image description here

mysqldump with create database line

By default mysqldump always creates the CREATE DATABASE IF NOT EXISTS db_name; statement at the beginning of the dump file.

[EDIT] Few things about the mysqldump file and it's options:

--all-databases, -A

Dump all tables in all databases. This is the same as using the --databases option and naming all the databases on the command line.

--add-drop-database

Add a DROP DATABASE statement before each CREATE DATABASE statement. This option is typically used in conjunction with the --all-databases or --databases option because no CREATE DATABASE statements are written unless one of those options is specified.

--databases, -B

Dump several databases. Normally, mysqldump treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE and USE statements are included in the output before each new database.

--no-create-db, -n

This option suppresses the CREATE DATABASE statements that are otherwise included in the output if the --databases or --all-databases option is given.

Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.

So to answer your question:

  • if you have one database to dump, you should have the --add-drop-database option in your mysqldump statement.
  • if you have multiple databases to dump, you should use the option --databases or --all-databases and the CREATE DATABASE syntax will be added automatically

More information at MySQL Reference Manual

What's the difference between :: (double colon) and -> (arrow) in PHP?

:: is used in static context, ie. when some method or property is declared as static:

class Math {
    public static function sin($angle) {
        return ...;
    }
}

$result = Math::sin(123);

Also, the :: operator (the Scope Resolution Operator, a.k.a Paamayim Nekudotayim) is used in dynamic context when you invoke a method/property of a parent class:

class Rectangle {
     protected $x, $y;

     public function __construct($x, $y) {
         $this->x = $x;
         $this->y = $y;
     }
}

class Square extends Rectangle {
    public function __construct($x) {
        parent::__construct($x, $x);
    }
}

-> is used in dynamic context, ie. when you deal with some instance of some class:

class Hello {
    public function say() {
       echo 'hello!';
    }
}

$h = new Hello();
$h->say();

By the way: I don't think that using Symfony is a good idea when you don't have any OOP experience.

Powershell command to hide user from exchange address lists

You can use the following script, just replace DOMAIN with the name of your domain. When executed it will prompt you for a userlogin then hide that user's account from the address lists.

$name=Read-Host "Enter login name of user to hide"
Set-Mailbox -Identity DOMAIN\$name -HiddenFromAddressListsEnabled $true

Brian.

Using npm behind corporate proxy .pac

Download your .pac file. Open it in any editor and look for PROXY = "PROXY X.X.X.X:80;. You may have many proxies, copy any of them and run the following terminal commands:

npm config set proxy http://X.X.X.X:80
npm config set https-proxy http://X.X.X.X:80

Now you should be able to install any package!

How to fix missing dependency warning when using useEffect React Hook?

you try this way

const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"}
    )
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      })
      .then(rcvdBusinesses => {
        // some stuff
      })
      .catch(err => {
        // some error handling
      });
  };

and

useEffect(() => {
    fetchBusinesses();
  });

it's work for you. But my suggestion is try this way also work for you. It's better than before way. I use this way:

useEffect(() => {
        const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"}
    )
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      })
      .then(rcvdBusinesses => {
        // some stuff
      })
      .catch(err => {
        // some error handling
      });
  };
        fetchBusinesses();
      }, []);

if you get data on the base of specific id then add in callback useEffect [id] then cannot show you warning React Hook useEffect has a missing dependency: 'any thing'. Either include it or remove the dependency array

jquery how to use multiple ajax calls one after the end of the other

This is the most elegant solution I've been using for a while. It doesn't require external counter variable and it provides nice degree of encapsulation.

var urls = ['http://..', 'http://..', ..];

function ajaxRequest (urls) {
    if (urls.length > 0) {
        $.ajax({
            method: 'GET',
            url: urls.pop()
        })
        .done(function (result)) {
            ajaxRequest(urls);
        });
    }
}

ajaxRequest(urls); 

Apache Tomcat :java.net.ConnectException: Connection refused

Depending on your version of Tomcat, this might be a simple problem (bug) with a 0-byte log file. Take a look at /var/log/tomcatX.Y where X.Y is your version you're working with and check if the log file catalina.out is read- and writeable. If it has 0 byte and is not accessible, then simply delete it and re-start Tomcat. This solved the problem for us a few times already.

Convert a Python int into a big-endian string of bytes

In Python 3.2+, you can use int.to_bytes:

If you don't want to specify the size

>>> n = 1245427
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0'
b'\x13\x00\xf3'

If you don't mind specifying the size

>>> (1245427).to_bytes(3, byteorder='big')
b'\x13\x00\xf3'

Loading scripts after page load?

For a Progressive Web App I wrote a script to easily load javascript files async on demand. Scripts are only loaded once. So you can call loadScript as often as you want for the same file. It wouldn't be loaded twice. This script requires JQuery to work.

For example:

loadScript("js/myscript.js").then(function(){
    // Do whatever you want to do after script load
});

or when used in an async function:

await loadScript("js/myscript.js");
// Do whatever you want to do after script load

In your case you may execute this after document ready:

$(document).ready(async function() {
    await loadScript("js/myscript.js");
    // Do whatever you want to do after script is ready
});

Function for loadScript:

function loadScript(src) {
  return new Promise(function (resolve, reject) {
    if ($("script[src='" + src + "']").length === 0) {
        var script = document.createElement('script');
        script.onload = function () {
            resolve();
        };
        script.onerror = function () {
            reject();
        };
        script.src = src;
        document.body.appendChild(script);
    } else {
        resolve();
    }
});
}

Benefit of this way:

  • It uses browser cache
  • You can load the script file when a user performs an action which needs the script instead loading it always.

Why is textarea filled with mysterious white spaces?

The text area shows mysterious spaces because there is a real space exists in the tags. <textarea> <php? echo $var; ?> </textarea> after removing these extra spaces between the tags will solve the issue , as following. <textarea><php? echo $var; ?></textarea>

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

How to convert a SVG to a PNG with ImageMagick?

In order to rescale the image, the option -density should be used. As far as I know the standard density is 72 and maps the size 1:1. If you want the output png to be twice as big as the original svg, set the density to 72*2=144:

convert -density 144 source.svg target.png

Using relative URL in CSS file, what location is it relative to?

In order to create modular style sheets that are not dependent on the absolute location of a resource, authors may use relative URIs. Relative URIs (as defined in [RFC3986]) are resolved to full URIs using a base URI. RFC 3986, section 5, defines the normative algorithm for this process. For CSS style sheets, the base URI is that of the style sheet, not that of the source document.

For example, suppose the following rule:

body { background: url("yellow") }

is located in a style sheet designated by the URI:

http://www.example.org/style/basic.css

The background of the source document's BODY will be tiled with whatever image is described by the resource designated by the URI

http://www.example.org/style/yellow

User agents may vary in how they handle invalid URIs or URIs that designate unavailable or inapplicable resources.

Taken from the CSS 2.1 spec.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

How open PowerShell as administrator from the run window

Windows 10 appears to have a keyboard shortcut. According to How to open elevated command prompt in Windows 10 you can press ctrl + shift + enter from the search or start menu after typing cmd for the search term.

image of win 10 start menu
(source: winaero.com)

How do I find the mime-type of a file with php?

If you run Linux and have the extension you could simply read the MIME type from /etc/mime.types by making a hash array. You can then store that in memory and simply call the MIME by array key :)

/**
 * Helper function to extract all mime types from the default Linux /etc/mime.types
 */
function get_mime_types() {
    $mime_types = array();
    if (
        file_exists('/etc/mime.types') &&
        ($fh = fopen('/etc/mime.types', 'r')) !== false
    ) {
        while (($line = fgets($fh)) !== false) {
            if (!trim($line) || substr($line, 0, 1) === '#') continue;
            $mime_type = preg_split('/\t+/', rtrim($line));
            if (
                is_array($mime_type) &&
                isset($mime_type[0]) && $mime_type[0] &&
                isset($mime_type[1]) && $mime_type[1]
            ) {
                foreach (explode(' ', $mime_type[1]) as $ext) {
                    $mime_types[$ext] = $mime_type[0];
                }
            }
        }
        fclose($fh);
    }
    return $mime_types;
}

Add inline style using Javascript

Try something like this

document.getElementById("vid-holder").style.width=300 + "px";

How can I get the sha1 hash of a string in node.js?

Tips to prevent issue (bad hash) :

I experienced that NodeJS is hashing the UTF-8 representation of the string. Other languages (like Python, PHP or PERL...) are hashing the byte string.

We can add binary argument to use the byte string.

const crypto = require("crypto");

function sha1(data) {
    return crypto.createHash("sha1").update(data, "binary").digest("hex");
}

sha1("Your text ;)");

You can try with : "\xac", "\xd1", "\xb9", "\xe2", "\xbb", "\x93", etc...

Other languages (Python, PHP, ...):

sha1("\xac") //39527c59247a39d18ad48b9947ea738396a3bc47

Nodejs:

sha1 = crypto.createHash("sha1").update("\xac", "binary").digest("hex") //39527c59247a39d18ad48b9947ea738396a3bc47
//without:
sha1 = crypto.createHash("sha1").update("\xac").digest("hex") //f50eb35d94f1d75480496e54f4b4a472a9148752

Download file from an ASP.NET Web API method using AngularJS

Support for downloading binary files in using ajax is not great, it is very much still under development as working drafts.

Simple download method:

You can have the browser download the requested file simply by using the code below, and this is supported in all browsers, and will obviously trigger the WebApi request just the same.

$scope.downloadFile = function(downloadPath) { 
    window.open(downloadPath, '_blank', '');  
}

Ajax binary download method:

Using ajax to download the binary file can be done in some browsers and below is an implementation that will work in the latest flavours of Chrome, Internet Explorer, FireFox and Safari.

It uses an arraybuffer response type, which is then converted into a JavaScript blob, which is then either presented to save using the saveBlob method - though this is only currently present in Internet Explorer - or turned into a blob data URL which is opened by the browser, triggering the download dialog if the mime type is supported for viewing in the browser.

Internet Explorer 11 Support (Fixed)

Note: Internet Explorer 11 did not like using the msSaveBlob function if it had been aliased - perhaps a security feature, but more likely a flaw, So using var saveBlob = navigator.msSaveBlob || navigator.webkitSaveBlob ... etc. to determine the available saveBlob support caused an exception; hence why the code below now tests for navigator.msSaveBlob separately. Thanks? Microsoft

// Based on an implementation here: web.student.tuwien.ac.at/~e0427417/jsdownload.html
$scope.downloadFile = function(httpPath) {
    // Use an arraybuffer
    $http.get(httpPath, { responseType: 'arraybuffer' })
    .success( function(data, status, headers) {

        var octetStreamMime = 'application/octet-stream';
        var success = false;

        // Get the headers
        headers = headers();

        // Get the filename from the x-filename header or default to "download.bin"
        var filename = headers['x-filename'] || 'download.bin';

        // Determine the content type from the header or default to "application/octet-stream"
        var contentType = headers['content-type'] || octetStreamMime;

        try
        {
            // Try using msSaveBlob if supported
            console.log("Trying saveBlob method ...");
            var blob = new Blob([data], { type: contentType });
            if(navigator.msSaveBlob)
                navigator.msSaveBlob(blob, filename);
            else {
                // Try using other saveBlob implementations, if available
                var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                if(saveBlob === undefined) throw "Not supported";
                saveBlob(blob, filename);
            }
            console.log("saveBlob succeeded");
            success = true;
        } catch(ex)
        {
            console.log("saveBlob method failed with the following exception:");
            console.log(ex);
        }

        if(!success)
        {
            // Get the blob url creator
            var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
            if(urlCreator)
            {
                // Try to use a download link
                var link = document.createElement('a');
                if('download' in link)
                {
                    // Try to simulate a click
                    try
                    {
                        // Prepare a blob URL
                        console.log("Trying download link method with simulated click ...");
                        var blob = new Blob([data], { type: contentType });
                        var url = urlCreator.createObjectURL(blob);
                        link.setAttribute('href', url);

                        // Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
                        link.setAttribute("download", filename);

                        // Simulate clicking the download link
                        var event = document.createEvent('MouseEvents');
                        event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                        link.dispatchEvent(event);
                        console.log("Download link method with simulated click succeeded");
                        success = true;

                    } catch(ex) {
                        console.log("Download link method with simulated click failed with the following exception:");
                        console.log(ex);
                    }
                }

                if(!success)
                {
                    // Fallback to window.location method
                    try
                    {
                        // Prepare a blob URL
                        // Use application/octet-stream when using window.location to force download
                        console.log("Trying download link method with window.location ...");
                        var blob = new Blob([data], { type: octetStreamMime });
                        var url = urlCreator.createObjectURL(blob);
                        window.location = url;
                        console.log("Download link method with window.location succeeded");
                        success = true;
                    } catch(ex) {
                        console.log("Download link method with window.location failed with the following exception:");
                        console.log(ex);
                    }
                }

            }
        }

        if(!success)
        {
            // Fallback to window.open method
            console.log("No methods worked for saving the arraybuffer, using last resort window.open");
            window.open(httpPath, '_blank', '');
        }
    })
    .error(function(data, status) {
        console.log("Request failed with status: " + status);

        // Optionally write the error out to scope
        $scope.errorDetails = "Request failed with status: " + status;
    });
};

Usage:

var downloadPath = "/files/instructions.pdf";
$scope.downloadFile(downloadPath);

Notes:

You should modify your WebApi method to return the following headers:

  • I have used the x-filename header to send the filename. This is a custom header for convenience, you could however extract the filename from the content-disposition header using regular expressions.

  • You should set the content-type mime header for your response too, so the browser knows the data format.

I hope this helps.

ReferenceError: fetch is not defined

It seems fetch support URL scheme with "http" or "https" for CORS request.

Install node fetch library npm install node-fetch, read the file and parse to json.

const fs = require('fs')
const readJson = filename => {
  return new Promise((resolve, reject) => {
    if (filename.toLowerCase().endsWith(".json")) {
      fs.readFile(filename, (err, data) => {
        if (err) {
          reject(err)
          return
        }
        resolve(JSON.parse(data))
      })
    }
    else {
      reject(new Error("Invalid filetype, <*.json> required."))
      return
    }
  })
}

// usage
const filename = "../data.json"
readJson(filename).then(data => console.log(data)).catch(err => console.log(err.message))

How to remove "index.php" in codeigniter's path

As an .htaccess file, a good option is to use the one provided by the Kohana Framework:

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /

# Protect hidden files from being viewed
<Files .*>
    Order Deny,Allow
    Deny From All
</Files>

# Protect application and system files from being viewed
RewriteRule ^(?:application|system)\b.* index.php/$0 [L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]

It's a well thought out .htaccess that just works.

Error 1053 the service did not respond to the start or control request in a timely fashion

Both Local System Account and Local Service would not work for me, i then set it to Network Service and this worked fine.

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

Instead of an ObservableCollection or TrulyObservableCollection, consider using a BindingList and calling the ResetBindings method.

For example:

private BindingList<TfsFile> _tfsFiles;

public BindingList<TfsFile> TfsFiles
{
    get { return _tfsFiles; }
    set
    {
        _tfsFiles = value;
        NotifyPropertyChanged();
    }
}

Given an event, such as a click your code would look like this:

foreach (var file in TfsFiles)
{
    SelectedFile = file;
    file.Name = "Different Text";
    TfsFiles.ResetBindings();
}

My model looked like this:

namespace Models
{
    public class TfsFile 
    {
        public string ImagePath { get; set; }

        public string FullPath { get; set; }

        public string Name { get; set; }

        public string Text { get; set; }

    }
}

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

You should not use the viewport meta tag at all if your design is not responsive. Misusing this tag may lead to broken layouts. You may read this article for documentation about why you should'n use this tag unless you know what you're doing. http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho

"user-scalable=no" also helps to prevent the zoom-in effect on iOS input boxes.

How to connect wireless network adapter to VMWare workstation?

I also encountered a similar problem. I run Ubuntu 11.04 on VMware on a Windows 7 host OS. Virtual machines can't expose the physical wireless cards. All of that is using a virtualization layer.

C++ "Access violation reading location" Error

Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

Because findVertex can return NULL if it can't find the vertex.

Otherwise this f->adj; is trying to do

NULL->adj;

Which causes access violation.

How do I add a placeholder on a CharField in Django?

It's undesirable to have to know how to instantiate a widget when you just want to override its placeholder.

    q = forms.CharField(label='search')
    ...
    q.widget.attrs['placeholder'] = "Search"

Vuex - passing multiple parameters to mutation

i think this can be as simple let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context and payload which is your data you want to pass in action so let take an example

Setting up Action

instead of

actions: {
        authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
    }

do

actions: {
        authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
    }

Calling (dispatching) Action

instead of

this.$store.dispatch({
                  type: 'authenticate',
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

do

this.$store.dispatch('authenticate',{
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

hope this gonna help

Wireshark localhost traffic capture

If you're using Windows it's not possible - read below. You can use the local address of your machine instead and then you'll be able to capture stuff. See CaptureSetup/Loopback.

Summary: you can capture on the loopback interface on Linux, on various BSDs including Mac OS X, and on Digital/Tru64 UNIX, and you might be able to do it on Irix and AIX, but you definitely cannot do so on Solaris, HP-UX....

Although the page mentions that this is not possible on Windows using Wireshark alone, you can actually record it using a workaround as mentioned in a different answer.


EDIT: Some 3 years later, this answer is no longer completely correct. The linked page contains instructions for capturing on the loopback interface.

.NET Core vs Mono

This is no more .NET Core vs. Mono. It's unified.

Update as of November 2020 - .NET 5 released that unifies .NET Framework and .NET Core

.NET and Mono will be unified under .NET 6 that would be released in November 2021

  • .NET 6.0 will add net6.0-ios and net6.0-android.
  • The OS-specific names can include OS version numbers, like net6.0-ios14.

Check below articles:

How do I best silence a warning about unused variables?

You can use __unused to tell the compiler that variable might not be used.

- (void)myMethod:(__unused NSObject *)theObject    
{
    // there will be no warning about `theObject`, because you wrote `__unused`

    __unused int theInt = 0;
    // there will be no warning, but you are still able to use `theInt` in the future
}

Html.BeginForm and adding properties

You can also use the following syntax for the strongly typed version:

<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(), 
          FormMethod.Post, 
          new { enctype = "multipart/form-data" })) 
   { %>

Using member variable in lambda capture list inside a member function

I believe VS2010 to be right this time, and I'd check if I had the standard handy, but currently I don't.

Now, it's exactly like the error message says: You can't capture stuff outside of the enclosing scope of the lambda. grid is not in the enclosing scope, but this is (every access to grid actually happens as this->grid in member functions). For your usecase, capturing this works, since you'll use it right away and you don't want to copy the grid

auto lambda = [this](){ std::cout << grid[0][0] << "\n"; }

If however, you want to store the grid and copy it for later access, where your puzzle object might already be destroyed, you'll need to make an intermediate, local copy:

vector<vector<int> > tmp(grid);
auto lambda = [tmp](){}; // capture the local copy per copy

† I'm simplifying - Google for "reaching scope" or see §5.1.2 for all the gory details.

jQuery Force set src attribute for iframe

Setting src attribute didn't work for me. The iframe didn't display the url.

What worked for me was:

window.open(url, "nameof_iframe");

Hope it helps someone.

How can I count the rows with data in an Excel sheet?

If you don't mind VBA, here is a function that will do it for you. Your call would be something like:

=CountRows(1:10) 
Function CountRows(ByVal range As range) As Long

Application.ScreenUpdating = False
Dim row As range
Dim count As Long

For Each row In range.Rows
    If (Application.WorksheetFunction.CountBlank(row)) - 256 <> 0 Then
        count = count + 1
    End If
Next

CountRows = count
Application.ScreenUpdating = True

End Function

How it works: I am exploiting the fact that there is a 256 row limit. The worksheet formula CountBlank will tell you how many cells in a row are blank. If the row has no cells with values, then it will be 256. So I just minus 256 and if it's not 0 then I know there is a cell somewhere that has some value.

SQL Server : trigger how to read value for Insert, Update, Delete

There is no updated dynamic table. There is just inserted and deleted. On an UPDATE command, the old data is stored in the deleted dynamic table, and the new values are stored in the inserted dynamic table.

Think of an UPDATE as a DELETE/INSERT combination.

Set View Width Programmatically

This code let you fill the banner to the maximum width and keep the ratio. This will only work in portrait. You must recreate the ad when you rotate the device. In landscape you should just leave the ad as is because it will be quite big an blurred.

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
double ratio = ((float) (width))/300.0;
int height = (int)(ratio*50);

AdView adView = new AdView(this,"ad_url","my_ad_key",true,true);
LinearLayout layout = (LinearLayout) findViewById(R.id.testing);
mAdView.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,height));
adView.setAdListener(this);
layout.addView(adView);

Why is my CSS style not being applied?

Clear the cache and cookies and restart the browser .As the style is not suppose to change frequently for a website browser kinda store it .

SHA512 vs. Blowfish and Bcrypt

It should suffice to say whether bcrypt or SHA-512 (in the context of an appropriate algorithm like PBKDF2) is good enough. And the answer is yes, either algorithm is secure enough that a breach will occur through an implementation flaw, not cryptanalysis.

If you insist on knowing which is "better", SHA-512 has had in-depth reviews by NIST and others. It's good, but flaws have been recognized that, while not exploitable now, have led to the the SHA-3 competition for new hash algorithms. Also, keep in mind that the study of hash algorithms is "newer" than that of ciphers, and cryptographers are still learning about them.

Even though bcrypt as a whole hasn't had as much scrutiny as Blowfish itself, I believe that being based on a cipher with a well-understood structure gives it some inherent security that hash-based authentication lacks. Also, it is easier to use common GPUs as a tool for attacking SHA-2–based hashes; because of its memory requirements, optimizing bcrypt requires more specialized hardware like FPGA with some on-board RAM.


Note: bcrypt is an algorithm that uses Blowfish internally. It is not an encryption algorithm itself. It is used to irreversibly obscure passwords, just as hash functions are used to do a "one-way hash".

Cryptographic hash algorithms are designed to be impossible to reverse. In other words, given only the output of a hash function, it should take "forever" to find a message that will produce the same hash output. In fact, it should be computationally infeasible to find any two messages that produce the same hash value. Unlike a cipher, hash functions aren't parameterized with a key; the same input will always produce the same output.

If someone provides a password that hashes to the value stored in the password table, they are authenticated. In particular, because of the irreversibility of the hash function, it's assumed that the user isn't an attacker that got hold of the hash and reversed it to find a working password.

Now consider bcrypt. It uses Blowfish to encrypt a magic string, using a key "derived" from the password. Later, when a user enters a password, the key is derived again, and if the ciphertext produced by encrypting with that key matches the stored ciphertext, the user is authenticated. The ciphertext is stored in the "password" table, but the derived key is never stored.

In order to break the cryptography here, an attacker would have to recover the key from the ciphertext. This is called a "known-plaintext" attack, since the attack knows the magic string that has been encrypted, but not the key used. Blowfish has been studied extensively, and no attacks are yet known that would allow an attacker to find the key with a single known plaintext.

So, just like irreversible algorithms based cryptographic digests, bcrypt produces an irreversible output, from a password, salt, and cost factor. Its strength lies in Blowfish's resistance to known plaintext attacks, which is analogous to a "first pre-image attack" on a digest algorithm. Since it can be used in place of a hash algorithm to protect passwords, bcrypt is confusingly referred to as a "hash" algorithm itself.

Assuming that rainbow tables have been thwarted by proper use of salt, any truly irreversible function reduces the attacker to trial-and-error. And the rate that the attacker can make trials is determined by the speed of that irreversible "hash" algorithm. If a single iteration of a hash function is used, an attacker can make millions of trials per second using equipment that costs on the order of $1000, testing all passwords up to 8 characters long in a few months.

If however, the digest output is "fed back" thousands of times, it will take hundreds of years to test the same set of passwords on that hardware. Bcrypt achieves the same "key strengthening" effect by iterating inside its key derivation routine, and a proper hash-based method like PBKDF2 does the same thing; in this respect, the two methods are similar.

So, my recommendation of bcrypt stems from the assumptions 1) that a Blowfish has had a similar level of scrutiny as the SHA-2 family of hash functions, and 2) that cryptanalytic methods for ciphers are better developed than those for hash functions.

How to duplicate a git repository? (without forking)

If you just want to create a new repository using all or most of the files from an existing one (i.e., as a kind of template), I find the easiest approach is to make a new repo with the desired name etc, clone it to your desktop, then just add the files and folders you want in it.

You don't get all the history etc, but you probably don't want that in this case.

How to Export Private / Secret ASC Key to Decrypt GPG Files

1.Export a Secret Key (this is what your boss should have done for you)

gpg --export-secret-keys yourKeyName > privateKey.asc

2.Import Secret Key (import your privateKey)

gpg --import privateKey.asc

3.Not done yet, you still need to ultimately trust a key. You will need to make sure that you also ultimately trust a key.

gpg --edit-key yourKeyName

Enter trust, 5, y, and then quit

Source: https://medium.com/@GalarnykMichael/public-key-asymmetric-cryptography-using-gpg-5a8d914c9bca

JavaScript DOM remove element

In most browsers, there's a slightly more succinct way of removing an element from the DOM than calling .removeChild(element) on its parent, which is to just call element.remove(). In due course, this will probably become the standard and idiomatic way of removing an element from the DOM.

The .remove() method was added to the DOM Living Standard in 2011 (commit), and has since been implemented by Chrome, Firefox, Safari, Opera, and Edge. It was not supported in any version of Internet Explorer.

If you want to support older browsers, you'll need to shim it. This turns out to be a little irritating, both because nobody seems to have made a all-purpose DOM shim that contains these methods, and because we're not just adding the method to a single prototype; it's a method of ChildNode, which is just an interface defined by the spec and isn't accessible to JavaScript, so we can't add anything to its prototype. So we need to find all the prototypes that inherit from ChildNode and are actually defined in the browser, and add .remove to them.

Here's the shim I came up with, which I've confirmed works in IE 8.

(function () {
    var typesToPatch = ['DocumentType', 'Element', 'CharacterData'],
        remove = function () {
            // The check here seems pointless, since we're not adding this
            // method to the prototypes of any any elements that CAN be the
            // root of the DOM. However, it's required by spec (see point 1 of
            // https://dom.spec.whatwg.org/#dom-childnode-remove) and would
            // theoretically make a difference if somebody .apply()ed this
            // method to the DOM's root node, so let's roll with it.
            if (this.parentNode != null) {
                this.parentNode.removeChild(this);
            }
        };

    for (var i=0; i<typesToPatch.length; i++) {
        var type = typesToPatch[i];
        if (window[type] && !window[type].prototype.remove) {
            window[type].prototype.remove = remove;
        }
    }
})();

This won't work in IE 7 or lower, since extending DOM prototypes isn't possible before IE 8. I figure, though, that on the verge of 2015 most people needn't care about such things.

Once you've included them shim, you'll be able to remove a DOM element element from the DOM by simply calling

element.remove();

for each inside a for each - Java

So you really want:

for each tweet
    unless tweet is in db
        insert tweet

If so, just write it down in your programming language. Hint: The loop over the array is to be done before the insert, which is done depending on the outcome.

What you want to test is that all array elements are not equal to the current one. But your for loop does not do that.

SVN upgrade working copy

If you're getting this error from Netbeans (7.2+) then it means that your separately installed version of Subversion is higher than the version in netbeans. In my case Netbeans (v7.3.1) had SVN v1.7 and I'd just upgraded my SVN to v1.8.

If you look in Tools > Options > Miscellaneous (tab) > Versioning (tab) > Subversion (pane), set the Preferred Client = CLI, then you can set the path the the installed SVN which for me was C:\Program Files\TortoiseSVN\bin.

More can be found on the Netbeans Subversion Clients FAQ.

How to split a string with angularJS

You could try this:

$scope.testdata = [{ 'name': 'name,id' }, {'name':'someName,someId'}]
$scope.array= [];
angular.forEach($scope.testdata, function (value, key) {
    $scope.array.push({ 'name': value.name.split(',')[0], 'id': value.name.split(',')[1] });
});
console.log($scope.array)

This way you can save the data for later use and acces it by using an ng-repeat like this:

<div ng-repeat="item in array">{{item.name}}{{item.id}}</div>


I hope this helped someone,
Plunker link: here
All credits go to @jwpfox and @Mohideen ibn Mohammed from the answer above.

Creating a new user and password with Ansible

This is the easy way:

---
- name: Create user
  user: name=user shell=/bin/bash home=/srv/user groups=admin,sudo generate_ssh_key=yes ssh_key_bits=2048
- name: Set password to user
  shell: echo user:plain_text_password | sudo chpasswd
  no_log: True

Pandas: Return Hour from Datetime Column Directly

Since the quickest, shortest answer is in a comment (from Jeff) and has a typo, here it is corrected and in full:

sales['time_hour'] = pd.DatetimeIndex(sales['timestamp']).hour

Unlocking tables if thread is lost

Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL

1) Enter MySQL

mysql -u your_user -p

2) Let's see the list of locked tables

mysql> show open tables where in_use>0;

3) Let's see the list of the current processes, one of them is locking your table(s)

mysql> show processlist;

4) Let's kill one of these processes

mysql> kill put_process_id_here;

MySQL error - #1062 - Duplicate entry ' ' for key 2

As it was said you have a unique index.

However, when I added most of the list yesterday I didn't get this error once even though a lot of the entries I added yesterday have a blank cell in column 2 as well. Whats going on?

That means that all these entries contain value NULL, not empty string ''. Mysql lets you have multiple NULL values in unique fields.

Reference — What does this symbol mean in PHP?

QUESTION:

What does => mean?


ANSWER:

=> Is the symbol we humans decided to use to separate "Key" => "Value" pairs in Associative Arrays.

ELABORATING:

To understand this, we have to know what Associative Arrays are. The first thing that comes up when a conventional programmer thinks of an array (in PHP) would be something similar to:

$myArray1 = array(2016, "hello", 33);//option 1

$myArray2 = [2016, "hello", 33];//option 2

$myArray3 = [];//option 3
$myArray3[] = 2016; 
$myArray3[] = "hello"; 
$myArray3[] = 33;

Where as, if we wanted to call the array in some later part of the code, we could do:

echo $myArray1[1];// output: hello
echo $myArray2[1];// output: hello
echo $myArray3[1];// output: hello

So far so good. However, as humans, we might find it hard to remember that index [0] of the array is the value of the year 2016, index [1] of the array is a greetings, and index [2] of the array is a simple integer value. The alternative we would then have is to use what is called an Associative Array. An Associative array has a few differences from a Sequential Array (which is what the previous cases were since they increment the index used in a predetermined sequence, by incrementing by 1 for each following value).

Differences (between a sequential and associative array):

  • Durring the declaration of an Associative Array, you don't only include the value of what you want to put in the array, but you also put the index value (called the key) which you want to use when calling the array in later parts of the code. The following syntax is used during it's declaration: "key" => "value".

  • When using the Associative Array, the key value would then be placed inside the index of the array to retrieve the desired value.

For instance:

$myArray1 = array( 
    "Year" => 2016, 
    "Greetings" => "hello", 
    "Integer_value" => 33);//option 1

$myArray2 = [ 
    "Year" =>  2016, 
    "Greetings" => "hello", 
    "Integer_value" => 33];//option 2

$myArray3 = [];//option 3
$myArray3["Year"] = 2016; 
$myArray3["Greetings"] = "hello"; 
$myArray3["Integer_value"] = 33;

And now, to receive the same output as before, the key value would be used in the arrays index:

echo $myArray1["Greetings"];// output: hello
echo $myArray2["Greetings"];// output: hello
echo $myArray3["Greetings"];// output: hello

FINAL POINT:

So from the above example, it is pretty easy to see that the => symbol is used to express the relationship of an Associative Array between each of the key and value pairs in an array DURING the initiation of the values within the array.

pandas loc vs. iloc vs. at vs. iat?

loc: only work on index
iloc: work on position
at: get scalar values. It's a very fast loc
iat: Get scalar values. It's a very fast iloc

Also,

at and iat are meant to access a scalar, that is, a single element in the dataframe, while loc and iloc are ments to access several elements at the same time, potentially to perform vectorized operations.

http://pyciencia.blogspot.com/2015/05/obtener-y-filtrar-datos-de-un-dataframe.html

Transfer data between iOS and Android via Bluetooth?

This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

Some possible alternatives:

  1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
  2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
  3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
  4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

Create an instance of a class from a string

I've used this method successfully:

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)

You'll need to cast the returned object to your desired object type.

How to get text in QlineEdit when QpushButton is pressed in a string?

The object name is not very important. what you should be focusing at is the variable that stores the lineedit object (le) and your pushbutton object(pb)

QObject(self.pb, SIGNAL("clicked()"), self.button_clicked)

def button_clicked(self):
  self.le.setText("shost")

I think this is what you want. I hope i got your question correctly :)

javascript code to check special characters

Directly from the w3schools website:

   var str = "The best things in life are free";
   var patt = new RegExp("e");
   var res = patt.test(str);

To combine their example with a regular expression, you could do the following:

function checkUserName() {
    var username = document.getElementsByName("username").value;
    var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
    if (pattern.test(username)) {
        alert("Please only use standard alphanumerics");
        return false;
    }
    return true; //good user input
}

How to Find App Pool Recycles in Event Log

It seemed quite hard to find this information, but eventually, I came across this question
You have to look at the 'System' event log, and filter by the WAS source.
Here is more info about the WAS (Windows Process Activation Service)

Difference between Relative path and absolute path in javascript

I think this example will help you in understanding this more simply.

Path differences in Windows

Windows absolute path C:\Windows\calc.exe

Windows non absolute path (relative path) calc.exe

In the above example, the absolute path contains the full path to the file and not just the file as seen in the non absolute path. In this example, if you were in a directory that did not contain "calc.exe" you would get an error message. However, when using an absolute path you can be in any directory and the computer would know where to open the "calc.exe" file.

Path differences in Linux

Linux absolute path /home/users/c/computerhope/public_html/cgi-bin

Linux non absolute path (relative path) /public_html/cgi-bin

In these example, the absolute path contains the full path to the cgi-bin directory on that computer. How to find the absolute path of a file in Linux Since most users do not want to see the full path as their prompt, by default the prompt is relative to their personal directory as shown above. To find the full absolute path of the current directory use the pwd command.

It is a best practice to use relative file paths (if possible).

When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.

Is there a php echo/print equivalent in javascript

We would create our own function in js like echo "Hello world".

function echo( ...s ) // rest operator
 { 
   for(var i = 0; i < s.length; i++ ) {

    document.write(s[i] + ' '); // quotes for space

   }

 } 

  // Now call to this function like echo

 echo('Hellow', "World");

Note: (...) rest operator dotes for access more parameters in one as object/array, to get value from object/array we should iterate the whole object/array by using for loop, like above and s is name i just kept you can write whatever you want.

Using RegEX To Prefix And Append In Notepad++

Use a Macro.

Macro>Start Recording

Use the keyboard to make your changes in a repeatable manner e.g.

home>type "able">end>down arrow>home

Then go back to the menu and click stop recording then run a macro multiple times.

That should do it and no regex based complications!

Is Python strongly typed?

A Python variable stores an untyped reference to the target object that represent the value.

Any assignment operation means assigning the untyped reference to the assigned object -- i.e. the object is shared via the original and the new (counted) references.

The value type is bound to the target object, not to the reference value. The (strong) type checking is done when an operation with the value is performed (run time).

In other words, variables (technically) have no type -- it does not make sense to think in terms of a variable type if one wants to be exact. But references are automatically dereferenced and we actually think in terms of the type of the target object.

How do I send a file as an email attachment using Linux command line?

If the file is text, you can send it easiest in the body as:

sendmail [email protected] < message.txt

Is try-catch like error handling possible in ASP Classic?

There are two approaches, you can code in JScript or VBScript which do have the construct or you can fudge it in your code.

Using JScript you'd use the following type of construct:

<script language="jscript" runat="server">
try  {
    tryStatements
}
catch(exception) {
    catchStatements
}
finally {
    finallyStatements
}
</script>

In your ASP code you fudge it by using on error resume next at the point you'd have a try and checking err.Number at the point of a catch like:

<%
' Turn off error Handling
On Error Resume Next


'Code here that you want to catch errors from

' Error Handler
If Err.Number <> 0 Then
   ' Error Occurred - Trap it
   On Error Goto 0 ' Turn error handling back on for errors in your handling block
   ' Code to cope with the error here
End If
On Error Goto 0 ' Reset error handling.

%>

How to throw a C++ exception

Simple:

#include <stdexcept>

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throw std::invalid_argument( "received negative value" );
    }
}

The Standard Library comes with a nice collection of built-in exception objects you can throw. Keep in mind that you should always throw by value and catch by reference:

try {
    compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
    // do stuff with exception... 
}

You can have multiple catch() statements after each try, so you can handle different exception types separately if you want.

You can also re-throw exceptions:

catch( const std::invalid_argument& e ) {
    // do something

    // let someone higher up the call stack handle it if they want
    throw;
}

And to catch exceptions regardless of type:

catch( ... ) { };

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

Data at the root level is invalid

This:

doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));

should be:

doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));

LoadXml() is for loading an XML string, not a file name.

TypeError: Can't convert 'int' object to str implicitly

def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
    print("Your SP balance is now 0.")
    attributeConfirmation()
elif strength < 0:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif strength > balance:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
    print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
    print("That is an invalid input. Restarting attribute selection.")
    attributeSelection()

Iterate through dictionary values?

You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items(). Then you have both directly in variables and don't need a lookup at all:

for key, value in PIX0.items():
    NUM = input("What is the Resolution of %s?"  % key)
    if NUM == value:

You can of course use that both ways then.

Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.

C++ wait for user input

There is no "standard" library function to do this. The standard (perhaps surprisingly) does not actually recognise the concept of a "keyboard", albeit it does have a standard for "console input".

There are various ways to achieve it on different operating systems (see herohuyongtao's solution) but it is not portable across all platforms that support keyboard input.

Remember that C++ (and C) are devised to be languages that can run on embedded systems that do not have keyboards. (Having said that, an embedded system might not have various other devices that the standard library supports).

This matter has been debated for a long time.

Ruby: kind_of? vs. instance_of? vs. is_a?

What is the difference?

From the documentation:

- (Boolean) instance_of?(class)
Returns true if obj is an instance of the given class.

and:

- (Boolean) is_a?(class)
- (Boolean) kind_of?(class)
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.

When should I use which?

Never. Use polymorphism instead.

Why are there so many of them?

I wouldn't call two "many". There are two of them, because they do two different things.

ScrollIntoView() causing the whole page to move

Play around with scrollIntoViewIfNeeded() ... make sure it's supported by the browser.

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

If bind-address is not present in your configuration file and mysql is hosted on AWS instance, please check your security group. In ideal conditions, the inbound rules should accept all connection from port 3306 and outbound rule should respond back to all valid IPs.

Git with SSH on Windows

I've found my ssh.exe in "C:/Program Files/Git/usr/bin" directory

Find duplicate records in MongoDB

Use aggregation on name and get name with count > 1:

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

To sort the results by most to least duplicates:

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

To use with another column name than "name", change "$name" to "$column_name"

Get pandas.read_csv to read empty values as empty string instead of nan

We have a simple argument in Pandas read_csv for this:

Use:

df = pd.read_csv('test.csv', na_filter= False)

Pandas documentation clearly explains how the above argument works.

Link

Change Primary Key

Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:

ALTER TABLE city
DROP CONSTRAINT pk_city;

ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);

Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.

Refresh page after form submitting

action attribute in <form method="post" action="action="""> should be just action=""

Create numpy matrix filled with NaNs

Are you familiar with numpy.nan?

You can create your own method such as:

def nans(shape, dtype=float):
    a = numpy.empty(shape, dtype)
    a.fill(numpy.nan)
    return a

Then

nans([3,4])

would output

array([[ NaN,  NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN,  NaN]])

I found this code in a mailing list thread.

How to execute a Windows command on a remote PC?

psexec \\RemoteComputer cmd.exe

or use ssh or TeamViewer or RemoteDesktop!

how to get docker-compose to use the latest image from repository

Since 2020-05-07, the docker-compose spec also defines the "pull_policy" property for a service:

version: '3.7'

services:
  my-service:
    image: someimage/somewhere
    pull_policy: always

The docker-compose spec says:

pull_policy defines the decisions Compose implementations will make when it starts to pull images.

Possible values are (tl;dr, check spec for more details):

  • always: always pull
  • never: don't pull (breaks if the image can not be found)
  • missing: pulls if the image is not cached
  • build: always build or rebuild

TypeScript - Append HTML to container element in Angular 2

1.

<div class="one" [innerHtml]="htmlToAdd"></div>
this.htmlToAdd = '<div class="two">two</div>';

See also In RC.1 some styles can't be added using binding syntax

  1. Alternatively
<div class="one" #one></div>
@ViewChild('one') d1:ElementRef;

ngAfterViewInit() {
  d1.nativeElement.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
}

or to prevent direct DOM access:

constructor(private renderer:Renderer) {}

@ViewChild('one') d1:ElementRef;

ngAfterViewInit() {
  this.renderer.invokeElementMethod(this.d1.nativeElement', 'insertAdjacentHTML' ['beforeend', '<div class="two">two</div>']);
}
    3.
constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  var d1 = this.elementRef.nativeElement.querySelector('.one');
  d1.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
}

java.time.format.DateTimeParseException: Text could not be parsed at index 21

The following worked for me

import java.time.*;
import java.time.format.*;

public class Times {

  public static void main(String[] args) {
    final String dateTime = "2012-02-22T02:06:58.147Z";
    DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
    final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter.withZone(ZoneId.of("UTC")));
    System.out.println(parsed.toLocalDateTime());
  }
}

and gave me output as

2012-02-22T02:06:58.147

How to add a default "Select" option to this ASP.NET DropDownList control?

The reason it is not working is because you are adding an item to the list and then overriding the whole list with a new DataSource which will clear and re-populate your list, losing the first manually added item.

So, you need to do this in reverse like this:

Status status = new Status();
DropDownList1.DataSource = status.getData();
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Description";
DropDownList1.DataBind();

// Then add your first item
DropDownList1.Items.Insert(0, "Select");

How to remove leading and trailing zeros in a string? Python

Remove leading + trailing '0':

list = [i.strip('0') for i in listOfNum ]

Remove leading '0':

list = [ i.lstrip('0') for i in listOfNum ]

Remove trailing '0':

list = [ i.rstrip('0') for i in listOfNum ]

How do I disable right click on my web page?

If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag

<body oncontextmenu="return false;">

This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).

However, as mentioned in the other answers, there really is no point adding a right click disabler. Anyone with basic browser knowledge can view the source and extract the information they need.

Relative paths based on file location instead of current working directory

What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}) and then use this to get the parent directory and cd to it at the beginning of the script.

#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

cd "$parent_path"
cat ../some.text

This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh inside dir.

Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)

Find all packages installed with easy_install/pip?

As of version 1.3 of pip you can now use pip list

It has some useful options including the ability to show outdated packages. Here's the documentation: https://pip.pypa.io/en/latest/reference/pip_list/

.ssh directory not being created

Is there a step missing?

Yes. You need to create the directory:

mkdir ${HOME}/.ssh

Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:

% chmod 700 ~/.ssh

Should the .ssh dir be generated when I use the ssh-keygen command?

No. This command generates an SSH key pair but will fail if it cannot write to the required directory:

% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.

Once you've created your keys, you should also restrict who can read those key files to just yourself:

% chmod -R go-wrx ~/.ssh/*

Get the Id of current table row with Jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Untitled</title>

<script type="text/javascript"><!--

function getVal(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    alert(targ.innerHTML);
}

onload = function() {
    var t = document.getElementById("main").getElementsByTagName("td");
    for ( var i = 0; i < t.length; i++ )
        t[i].onclick = getVal;
}

</script>



<body>

<table id="main"><tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
</tr><tr>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
</tr><tr>
    <td>9</td>
    <td>10</td>
    <td>11</td>
    <td>12</td>
</tr></table>

</body>
</html>

MySQL: NOT LIKE

categories_posts and categories_news start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique starts with 'categories' instead of check if it contains the given substring. Translating all that into a query:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I have found the problem.

The problem was that the HTML I was trying to validate was not contained within a <form>...</form> tag.

As soon as I did that, I had a context that was not null.

Retrieve the position (X,Y) of an HTML element relative to the browser window

HTML elements on most browsers will have:-

offsetLeft
offsetTop

These specifiy the position of the element relative its nearest parent that has layout. This parent can often be accessed bif the offsetParent property.

IE and FF3 have

clientLeft
clientTop

These properties are less common, they specify an elements position with its parents client area (padded area is part of the client area but border and margin is not).

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Update: Using DateTimeFormat, introduced in java 8:

The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.

Your input format looks quite standard, except the trailing Z. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". The trailing 'Z' is the interesting part. Usually there's time zone data here, like -0700. So the pattern would be ...Z, i.e. without apostrophes.

The output format is way more simple: "dd-MM-yyyy". Mind the small y -s.

Here is the example code:

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018

Original answer - with old API SimpleDateFormat

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018

How to merge a list of lists with same type of items to a single list of items?

Use the SelectMany extension method

list = listOfList.SelectMany(x => x).ToList();

Java says FileNotFoundException but file exists

There are a number situation where a FileNotFoundException may be thrown at runtime.

  1. The named file does not exist. This could be for a number of reasons including:

    • The pathname is simply wrong
    • The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
    • The pathname is relative, and it doesn't resolve correctly relative to the actual current directory of the running application. This typically happens because the application's current directory is not what you are expecting or assuming.
    • The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
  2. The named file is actually a directory.

  3. The named file cannot be opened for reading for some reason.

The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:

  • Calling file.exists() will tell you if any file system object exists with the given name / pathname.
  • Calling file.isDirectory() will test if it is a directory.
  • Calling file.canRead() will test if it is a readable file.
  • This line will tell you what the current directory is:

    System.out.println(new File(".").getAbsolutePath());
    
  • This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trainiong whitespace:

    System.out.println("The path is '" + path + "'");
    

    Look for unexpected spaces, line breaks, etc in the output.


It turns out that your example code has a compilation error.

I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

If you change your code to the following, it will fix that problem.

public static void main(String[] args) throws FileNotFoundException {    
    File file = new File("scores.dat");
    System.out.println(file.exists());
    Scanner scan = new Scanner(file);
}

Explanation: the Scanner(File) constructor is declared as throwing the FileNotFoundException exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws clause. The above fix takes the latter approach.

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

DISCLAIMER: this answer is from Jul 2015 and uses Retrofit and OkHttp from that time.
Check this link for more info on Retrofit v2 and this one for the current OkHttp methods.

Okay, I got it working using Android Developers guide.

Just as OP, I'm trying to use Retrofit and OkHttp to connect to a self-signed SSL-enabled server.

Here's the code that got things working (I've removed the try/catch blocks):

public static RestAdapter createAdapter(Context context) {
  // loading CAs from an InputStream
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  InputStream cert = context.getResources().openRawResource(R.raw.my_cert);
  Certificate ca;
  try {
    ca = cf.generateCertificate(cert);
  } finally { cert.close(); }

  // creating a KeyStore containing our trusted CAs
  String keyStoreType = KeyStore.getDefaultType();
  KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  keyStore.load(null, null);
  keyStore.setCertificateEntry("ca", ca);

  // creating a TrustManager that trusts the CAs in our KeyStore
  String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
  tmf.init(keyStore);

  // creating an SSLSocketFactory that uses our TrustManager
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, tmf.getTrustManagers(), null);

  // creating an OkHttpClient that uses our SSLSocketFactory
  OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());

  // creating a RestAdapter that uses this custom client
  return new RestAdapter.Builder()
              .setEndpoint(UrlRepository.API_BASE)
              .setClient(new OkClient(okHttpClient))
              .build();
}

To help in debugging, I also added .setLogLevel(RestAdapter.LogLevel.FULL) to my RestAdapter creation commands and I could see it connecting and getting the response from the server.

All it took was my original .crt file saved in main/res/raw. The .crt file, aka the certificate, is one of the two files created when you create a certificate using openssl. Generally, it is a .crt or .cert file, while the other is a .key file.

Afaik, the .crt file is your public key and the .key file is your private key.

As I can see, you already have a .cert file, which is the same, so try to use it.


PS: For those that read it in the future and only have a .pem file, according to this answer, you only need this to convert one to the other:

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

PS²: For those that don't have any file at all, you can use the following command (bash) to extract the public key (aka certificate) from any server:

echo -n | openssl s_client -connect your.server.com:443 | \
  sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/my_cert.crt

Just replace the your.server.com and the port (if it is not standard HTTPS) and choose a valid path for your output file to be created.

How to measure time taken between lines of code in python?

I was looking for a way how to output a formatted time with minimal code, so here is my solution. Many people use Pandas anyway, so in some cases this can save from additional library imports.

import pandas as pd
start = pd.Timestamp.now()
# code
print(pd.Timestamp.now()-start)

Output:

0 days 00:05:32.541600

I would recommend using this if time precision is not the most important, otherwise use time library:

%timeit pd.Timestamp.now() outputs 3.29 µs ± 214 ns per loop

%timeit time.time() outputs 154 ns ± 13.3 ns per loop

XML Carriage return encoding

xml:space="preserve" has to work for all compliant XML parsers.

However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br /> (X)HTML tag, maybe this is the problem which you are facing.

You can also add &#10; and/or &#13; to insert CR/LF characters.

Change CSS properties on click

Try this:

$('#foo').css({backgroundColor:'red', color:'white',fontSize:'44px'});

How to convert text to binary code in JavaScript?

Try this:

String.prototype.toBinaryString = function(spaces = 0) {
    return this.split("").map(function(character) {
        return character.charCodeAt(0).toString(2);
    }).join(" ".repeat(spaces));
}

And use it like this:

"test string".toBinaryString(1); // with spaces
"test string".toBinaryString(); // without spaces
"test string".toBinaryString(2); // with 2 spaces

Failed to add the host to the list of know hosts

Okay so ideal permissions look like this
For ssh directory (You can get this by typing ls -ld ~/.ssh/)
drwx------ 2 oroborus oroborus 4096 Nov 28 12:05 /home/oroborus/.ssh/

d means directory, rwx means the user oroborus has read write and execute permission. Here oroborus is my computer name, you can find yours by echoing $USER. The second oroborus is actually the group. You can read more about what does each field mean here. It is very important to learn this because if you are working on ubuntu/osx or any Linux distro chances are you will encounter it again.

Now to make your permission look like this, you need to type
sudo chmod 700 ~/.ssh

7 in binary is 111 which means read 1 write 1 and execute 1, you can decode 6 by similar logic means only read-write permissions

You have given your user read write and execute permissions. Make sure your file permissions look like this.

total 20
-rw------- 1 oroborus oroborus  418 Nov  8  2014 authorized_keys
-rw------- 1 oroborus oroborus   34 Oct 19 14:25 config
-rw------- 1 oroborus oroborus 1679 Nov 15  2015 id_rsa
-rw------- 1 oroborus oroborus  418 Nov 15  2015 id_rsa.pub
-rw-r--r-- 1 oroborus root      222 Nov 28 12:12 known_hosts

You have given here read-write permission to your user here for all files. You can see this by typing ls -l ~/.ssh/

This issue occurs because ssh is a program is trying to write to a file called known_hosts in its folder. While writing if it knows that it doesn't have sufficient permissions it will not write in that file and hence fail. This is my understanding of the issue, more knowledgeable people can throw more light in this. Hope it helps

Length of a JavaScript object

Use:

_x000D_
_x000D_
var myArray = new Object();_x000D_
myArray["firstname"] = "Gareth";_x000D_
myArray["lastname"] = "Simpson";_x000D_
myArray["age"] = 21;_x000D_
obj = Object.keys(myArray).length;_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

How to make multiple divs display in one line but still retain width?

You can float your column divs using float: left; and give them widths.

And to make sure none of your other content gets messed up, you can wrap the floated divs within a parent div and give it some clear float styling.

Hope this helps.

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

I found that I could access the checkbox directly using Worksheets("SheetName").CB_Checkboxname.value directly without relating to additional objects.

type object 'datetime.datetime' has no attribute 'datetime'

You should really import the module into its own alias.

import datetime as dt
my_datetime = dt.datetime(year, month, day)

The above has the following benefits over the other solutions:

  • Calling the variable my_datetime instead of date reduces confusion since there is already a date in the datetime module (datetime.date).
  • The module and the class (both called datetime) do not shadow each other.

Where are include files stored - Ubuntu Linux, GCC

gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo" and #include <zap> will search on your system, I recommend:

$ touch a.c
$ gcc -v -E a.c
 ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"

This is one way to see the search lists for included files, including (if any) directories into which #include "..." will look but #include <...> won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ... here;-) on any system on which gcc runs properly.

Send file using POST from a Python script

Yes. You'd use the urllib2 module, and encode using the multipart/form-data content type. Here is some sample code to get you started -- it's a bit more than just file uploading, but you should be able to read through it and see how it works:

user_agent = "image uploader"
default_message = "Image $current of $total"

import logging
import os
from os.path import abspath, isabs, isdir, isfile, join
import random
import string
import sys
import mimetypes
import urllib2
import httplib
import time
import re

def random_string (length):
    return ''.join (random.choice (string.letters) for ii in range (length + 1))

def encode_multipart_data (data, files):
    boundary = random_string (30)

    def get_content_type (filename):
        return mimetypes.guess_type (filename)[0] or 'application/octet-stream'

    def encode_field (field_name):
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"' % field_name,
                '', str (data [field_name]))

    def encode_file (field_name):
        filename = files [field_name]
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, filename),
                'Content-Type: %s' % get_content_type(filename),
                '', open (filename, 'rb').read ())

    lines = []
    for name in data:
        lines.extend (encode_field (name))
    for name in files:
        lines.extend (encode_file (name))
    lines.extend (('--%s--' % boundary, ''))
    body = '\r\n'.join (lines)

    headers = {'content-type': 'multipart/form-data; boundary=' + boundary,
               'content-length': str (len (body))}

    return body, headers

def send_post (url, data, files):
    req = urllib2.Request (url)
    connection = httplib.HTTPConnection (req.get_host ())
    connection.request ('POST', req.get_selector (),
                        *encode_multipart_data (data, files))
    response = connection.getresponse ()
    logging.debug ('response = %s', response.read ())
    logging.debug ('Code: %s %s', response.status, response.reason)

def make_upload_file (server, thread, delay = 15, message = None,
                      username = None, email = None, password = None):

    delay = max (int (delay or '0'), 15)

    def upload_file (path, current, total):
        assert isabs (path)
        assert isfile (path)

        logging.debug ('Uploading %r to %r', path, server)
        message_template = string.Template (message or default_message)

        data = {'MAX_FILE_SIZE': '3145728',
                'sub': '',
                'mode': 'regist',
                'com': message_template.safe_substitute (current = current, total = total),
                'resto': thread,
                'name': username or '',
                'email': email or '',
                'pwd': password or random_string (20),}
        files = {'upfile': path}

        send_post (server, data, files)

        logging.info ('Uploaded %r', path)
        rand_delay = random.randint (delay, delay + 5)
        logging.debug ('Sleeping for %.2f seconds------------------------------\n\n', rand_delay)
        time.sleep (rand_delay)

    return upload_file

def upload_directory (path, upload_file):
    assert isabs (path)
    assert isdir (path)

    matching_filenames = []
    file_matcher = re.compile (r'\.(?:jpe?g|gif|png)$', re.IGNORECASE)

    for dirpath, dirnames, filenames in os.walk (path):
        for name in filenames:
            file_path = join (dirpath, name)
            logging.debug ('Testing file_path %r', file_path)
            if file_matcher.search (file_path):
                matching_filenames.append (file_path)
            else:
                logging.info ('Ignoring non-image file %r', path)

    total_count = len (matching_filenames)
    for index, file_path in enumerate (matching_filenames):
        upload_file (file_path, index + 1, total_count)

def run_upload (options, paths):
    upload_file = make_upload_file (**options)

    for arg in paths:
        path = abspath (arg)
        if isdir (path):
            upload_directory (path, upload_file)
        elif isfile (path):
            upload_file (path)
        else:
            logging.error ('No such path: %r' % path)

    logging.info ('Done!')

How to hide .php extension in .htaccess

I've used this:

RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L]

# Redirect external .php requests to extensionless URL
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/folder/$1 [R=301,L]

# Resolve .php file for extensionless PHP URLs
RewriteRule ^([^/.]+)$ $1.php [L]

See also: this question

How to trim leading and trailing white spaces of a string?

A quick string "GOTCHA" with JSON Unmarshall which will add wrapping quotes to strings.

(example: the string value of {"first_name":" I have whitespace "} will convert to "\" I have whitespace \"")

Before you can trim anything, you'll need to remove the extra quotes first:

playground example

// ScrubString is a string that might contain whitespace that needs scrubbing.
type ScrubString string

// UnmarshalJSON scrubs out whitespace from a valid json string, if any.
func (s *ScrubString) UnmarshalJSON(data []byte) error {
    ns := string(data)
    // Make sure we don't have a blank string of "\"\"".
    if len(ns) > 2 && ns[0] != '"' && ns[len(ns)] != '"' {
        *s = ""
        return nil
    }
    // Remove the added wrapping quotes.
    ns, err := strconv.Unquote(ns)
    if err != nil {
        return err
    }
    // We can now trim the whitespace.
    *s = ScrubString(strings.TrimSpace(ns))

    return nil
}

When should an Excel VBA variable be killed or set to Nothing?

I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:

Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)

When UserForm was destroyed (after Unload Me) the memory allocated for the data loaded in the mainPicture was not being de-allocated. I had to add an explicit

mainPicture = Nothing

in the terminate event.

Check for column name in a SqlDataReader object

Hashtable ht = new Hashtable();
    Hashtable CreateColumnHash(SqlDataReader dr)
    {
        ht = new Hashtable();
        for (int i = 0; i < dr.FieldCount; i++)
        {
            ht.Add(dr.GetName(i), dr.GetName(i));
        }
        return ht;
    }

    bool ValidateColumn(string ColumnName)
    {
        return ht.Contains(ColumnName);
    }

What is the apply function in Scala?

1 - Treat functions as objects.

2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.

How to convert a Django QuerySet to a list

def querySet_to_list(qs):
    """
    this will return python list<dict>
    """
    return [dict(q) for q in qs]

def get_answer_by_something(request):
    ss = Answer.objects.filter(something).values()
    querySet_to_list(ss) # python list return.(json-able)

this code convert django queryset to python list

How to start and stop android service from a adb shell?

You may get an error "*Error: app is in background *" while using

adb shell am startservice 

in Oreo (26+). This requires services in the foreground. Use the following.

adb shell am start-foreground-service com.some.package.name/.YourServiceSubClassName

Find an item in List by LINQ?

I used to use a Dictionary which is some sort of an indexed list which will give me exactly what I want when I want it.

Dictionary<string, int> margins = new Dictionary<string, int>();
margins.Add("left", 10);
margins.Add("right", 10);
margins.Add("top", 20);
margins.Add("bottom", 30);

Whenever I wish to access my margins values, for instance, I address my dictionary:

int xStartPos = margins["left"];
int xLimitPos = margins["right"];
int yStartPos = margins["top"];
int yLimitPos = margins["bottom"];

So, depending on what you're doing, a dictionary can be useful.

how to configure hibernate config file for sql server

Finally this is for Hibernate 5 in Tomcat.

Compiled all the answers from the above and added my tips which works like a charm for Hibernate 5 and SQL Server 2014.

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
   org.hibernate.dialect.SQLServerDialect
</property>
<property name="hibernate.connection.driver_class">
   com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<property name="hibernate.connection.url">  
jdbc:sqlserver://localhost\ServerInstanceOrServerName:1433;databaseName=DATABASE_NAME 
</property>
<property name="hibernate.default_schema">theSchemaNameUsuallydbo</property>
<property name="hibernate.connection.username">
   YourUsername
</property>
<property name="hibernate.connection.password">
   YourPasswordForMSSQL
</property>

req.body empty on posts

I made a really dumb mistake and forgot to define name attributes for inputs in my html file.

So instead of

<input type="password" class="form-control" id="password">

I have this.

<input type="password" class="form-control" id="password" name="password">

Now request.body is populated like this: { password: 'hhiiii' }

How to get the selected item from ListView?

You are implementing the Click Handler rather than Select Handler. A List by default doesn't suppose to have selection.

What you should change, in your above example, is to

public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    MyClass item = (MyClass) adapter.getItem(position);
}

Regular expression that doesn't contain certain string

I'm not sure it's a standard construct, but I think you should have a look on "negative lookahead" (which writes : "?!", without the quotes). It's far easier than all answers in this thread, including the accepted one.

Example : Regex : "^(?!123)[0-9]*\w" Captures any string beginning by digits followed by letters, UNLESS if "these digits" are 123.

http://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx#grouping_constructs (microsoft page, but quite comprehensive) for lookahead / lookbehind

PS : it works well for me (.Net). But if I'm wrong on something, please let us know. I find this construct very simple and effective, so I'm surprised of the accepted answer.

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

Oracle database: How to read a BLOB?

If you use the Oracle native data provider rather than the Microsoft driver then you can get at all field types

Dim cn As New Oracle.DataAccess.Client.OracleConnection
Dim cm As New Oracle.DataAccess.Client.OracleCommand
Dim dr As Oracle.DataAccess.Client.OracleDataReader

The connection string does not require a Provider value so you would use something like:

"Data Source=myOracle;UserID=Me;Password=secret"

Open the connection:

cn.ConnectionString = "Data Source=myOracle;UserID=Me;Password=secret"
cn.Open()

Attach the command and set the Sql statement

cm.Connection = cn
cm.CommandText = strCommand

Set the Fetch size. I use 4000 because it's as big as a varchar can be

cm.InitialLONGFetchSize = 4000

Start the reader and loop through the records/columns

dr = cm.ExecuteReader

Do while dr.read()
    strMyLongString = dr(i)
Loop

You can be more specific with the read, eg dr.GetOracleString(i) dr.GetOracleClob(i) etc. if you first identify the data type in the column. If you're reading a LONG datatype then the simple dr(i) or dr.GetOracleString(i) works fine. The key is to ensure that the InitialLONGFetchSize is big enough for the datatype. Note also that the native driver does not support CommandBehavior.SequentialAccess for the data reader but you don't need it and also, the LONG field does not even have to be the last field in the select statement.

Parsing CSV / tab-delimited txt file with Python

Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.

Pandas is a library for handling data in Python, preferred by many Data Scientists.

Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.

In your case:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe columns you don't want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Problem: Even I was facing the problem where we were sending '£' with some string in POST request to CRM System, but when we were doing the GET call from CRM , it was returning '£' with some string content. So what we have analysed is that '£' was getting converted to '£'.

Analysis: The glitch which we have found after doing research is that in POST call we have set HttpWebRequest ContentType as "text/xml" while in GET Call it was "text/xml; charset:utf-8".

Solution: So as the part of solution we have included the charset:utf-8 in POST request and it works.

Render Content Dynamically from an array map function in React Native

Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}

Encrypt Password in Configuration Files?

I think that the best approach is to ensure that your config file (containing your password) is only accessible to a specific user account. For example, you might have an application specific user appuser to which only trusted people have the password (and to which they su to).

That way, there's no annoying cryptography overhead and you still have a password which is secure.

EDIT: I am assuming that you are not exporting your application configuration outside of a trusted environment (which I'm not sure would make any sense, given the question)

Quickest way to clear all sheet contents VBA

Try this one:

Sub clear_sht
  Dim sht As Worksheet
  Set sht = Worksheets(GENERATOR_SHT_NAME)
  col_cnt = sht.UsedRange.Columns.count
  If col_cnt = 0 Then
    col_cnt = 1
  End If

  sht.Range(sht.Cells(1, 1), sht.Cells(sht.UsedRange.Rows.count, col_cnt)).Clear
End Sub

XPath - Selecting elements that equal a value

The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.

This explains the "strange results".

"Better" results can be obtained using the expressions below:

//*[text() = 'qwerty']

The above selects every element in the document that has at least one text-node child with value 'qwerty'.

//*[text() = 'qwerty' and not(text()[2])]

The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

In my case the issue was caused due to mismatch in .Xauthority file. Which initially showed up with "Invalid MIT-MAGIC-COOKIE-1" error and then "Error: cannot open display: :0.0" afterwards

Regenerating the .Xauthorityfile from the user under which I am running the vncserver and resetting the password with a restart of the vnc service and dbus service fixed the issue for me.

How to add buttons at top of map fragment API v2 layout

Maybe a simpler solution is to set an overlay in front of your map using FrameLayout or RelativeLayout and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapActivity" >

    <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scrollbars="vertical"  
        class="com.google.android.gms.maps.SupportMapFragment"/>

    <RadioGroup 
        android:id="@+id/radio_group_list_selector"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:orientation="horizontal" 
        android:background="#80000000"
        android:padding="4dp" >

        <RadioButton
            android:id="@+id/radioPopular"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="@string/Popular"
            android:gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioAZ"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/AZ"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />

        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioCategory"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/Category"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioNearBy"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/NearBy"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton3"
            android:textColor="@color/textcolor_radiobutton" />
    </RadioGroup>
</FrameLayout>

How to force 'cp' to overwrite directory instead of creating another one inside?

The following command ensures dotfiles (hidden files) are included in the copy:

$ cp -Rf foo/. bar

How can I mock the JavaScript window object using Jest?

You can try this:

import * as _Window from "jsdom/lib/jsdom/browser/Window";

window.open = jest.fn().mockImplementationOnce(() => {
    return new _Window({ parsingMode: "html" });
});

it("correct url is called", () => {
    statementService.openStatementsReport(111);
    expect(window.open).toHaveBeenCalled();
});

How to detect if user select cancel InputBox VBA Excel

If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...

EDIT to properly differentiate between empty string and cancel, according to this answer.

Your example

Private Sub test()
    Dim result As String
    result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
    If StrPtr(result) = 0 Then
        MsgBox ("User canceled!")
    ElseIf result = vbNullString Then
        MsgBox ("User didn't enter anything!")
    Else
        MsgBox ("User entered " & result)
    End If
End Sub

Would tell the user they canceled when they delete the default string, or they click cancel.

See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

Hibernate Group by Criteria Object

GroupBy using in Hibernate

This is the resulting code

public Map getStateCounts(final Collection ids) {
    HibernateSession hibernateSession = new HibernateSession();
    Session session = hibernateSession.getSession();
    Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
            .add(Restrictions.in("id", ids));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("state"));
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);
    List results = criteria.list();
    Map stateMap = new HashMap();
    for (Object[] obj : results) {
        DownloadState downloadState = (DownloadState) obj[0];
        stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
    }
    hibernateSession.closeSession();
    return stateMap;
}

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

Find out free space on tablespace

column pct_free format 999.99
select
     used.tablespace_name,
     (reserv.maxbytes - used.bytes)*100/reserv.maxbytes pct_free,
     used.bytes/1024/1024/1024 used_gb,
     reserv.maxbytes/1024/1024/1024 maxgb,
     reserv.bytes/1024/1024/1024 gb,
     (reserv.maxbytes - used.bytes)/1024/1024/1024 "max free bytes",
     reserv.datafiles
from
    (select tablespace_name, count(1) datafiles, sum(greatest(maxbytes,bytes)) maxbytes, sum(bytes) bytes from dba_data_files group by tablespace_name) reserv,
    (select tablespace_name, sum(bytes) bytes from dba_segments group by tablespace_name) used
where used.tablespace_name = reserv.tablespace_name
order by 2
/

Playing mp3 song on python

As it wasn't already suggested here, but is probably one of the easiest solutions:

import subprocess

def play_mp3(path):
    subprocess.Popen(['mpg123', '-q', path]).wait()

It depends on any mpg123 compliant player, which you get e.g. for Debian using:

apt-get install mpg123

or

apt-get install mpg321

Updating version numbers of modules in a multi-module Maven project

You may want to look into Maven release plugin's release:update-versions goal. It will update the parent's version as well as all the modules under it.


Update: Please note that the above is the release plugin. If you are not releasing, you may want to use versions:set

mvn versions:set -DnewVersion=1.2.3-SNAPSHOT

Commands out of sync; you can't run this command now

Another cause: store_result() cannot be called twice.

For instance, in the following code, Error 5 is printed.

<?php

$db = new mysqli("localhost", "something", "something", "something");

$stmt = $db->stmt_init();
if ($stmt->error) printf("Error 1 : %s\n", $stmt->error);

$stmt->prepare("select 1");
if ($stmt->error) printf("Error 2 : %s\n", $stmt->error);

$stmt->execute();
if ($stmt->error) printf("Error 3 : %s\n", $stmt->error);

$stmt->store_result();
if ($stmt->error) printf("Error 4 : %s\n", $stmt->error);

$stmt->store_result();
if ($stmt->error) printf("Error 5 : %s\n", $stmt->error);

(This may not be relevant to the original sample code, but it can be relevant to people seeking answers to this error.)

how to run or install a *.jar file in windows?

Have you tried (from a command line)

java -jar jbpm-installer-3.2.7.jar

or double clicking it with the mouse ?

Found this and this by googling.

Hope it helps

Force Internet Explorer to use a specific Java Runtime Environment install?

If you mean when you are not the person writing the web page, then you could disable the add ons you do not wish to use with the Manage Add-Ons IE Options screen added in Win XP SP2

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

Pass -noverify JVM argument to your test task. If you are using gradle, in the build.gradle you can have something like:

test {
  jvmArgs "-noverify"
}

Unix tail equivalent command in Windows Powershell

There have been many valid answers, however, none of them has the same syntax as tail in linux. The following function can be stored in your $Home\Documents\PowerShell\Microsoft.PowerShell_profile.ps1 for persistency (see powershell profiles documentation for more details).

This allows you to call...

tail server.log
tail -n 5 server.log
tail -f server.log
tail -Follow -Lines 5 -Path server.log

which comes quite close to the linux syntax.

function tail {
<#
    .SYNOPSIS
        Get the last n lines of a text file.
    .PARAMETER Follow
        output appended data as the file grows
    .PARAMETER Lines
        output the last N lines (default: 10)
    .PARAMETER Path
        path to the text file
    .INPUTS
        System.Int
        IO.FileInfo
    .OUTPUTS
        System.String
    .EXAMPLE
        PS> tail c:\server.log
    .EXAMPLE
        PS> tail -f -n 20 c:\server.log
#>
    [CmdletBinding()]
    [OutputType('System.String')]
    Param(
        [Alias("f")]
        [parameter(Mandatory=$false)]
        [switch]$Follow,

        [Alias("n")]
        [parameter(Mandatory=$false)]
        [Int]$Lines = 10,

        [parameter(Mandatory=$true, Position=5)]
        [ValidateNotNullOrEmpty()]
        [IO.FileInfo]$Path
    )
    if ($Follow)
    {
        Get-Content -Path $Path -Tail $Lines -Wait
    }
    else
    {
        Get-Content -Path $Path -Tail $Lines
    }
}

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}

Resize UIImage and change the size of UIImageView

If you have the size of the image, why don't you set the frame.size of the image view to be of this size?

EDIT----

Ok, so seeing your comment I propose this:

UIImageView *imageView;
//so let's say you're image view size is set to the maximum size you want

CGFloat maxWidth = imageView.frame.size.width;
CGFloat maxHeight = imageView.frame.size.height;

CGFloat viewRatio = maxWidth / maxHeight;
CGFloat imageRatio = image.size.height / image.size.width;

if (imageRatio > viewRatio) {
    CGFloat imageViewHeight = round(maxWidth * imageRatio);
    imageView.frame = CGRectMake(0, ceil((self.bounds.size.height - imageViewHeight) / 2.f), maxWidth, imageViewHeight);
}
else if (imageRatio < viewRatio) {
    CGFloat imageViewWidth = roundf(maxHeight / imageRatio);
    imageView.frame = CGRectMake(ceil((maxWidth - imageViewWidth) / 2.f), 0, imageViewWidth, maxHeight);
} else {
    //your image view is already at the good size
}

This code will resize your image view to its image ratio, and also position the image view to the same centre as your "default" position.

PS: I hope you're setting imageView.layer.shouldRasterise = YES and imageView.layer.rasterizationScale = [UIScreen mainScreen].scale;

if you're using CALayer shadow effect ;) It will greatly improve the performance of your UI.

Explain the different tiers of 2 tier & 3 tier architecture?

Here is some help for 2Tier and 3Tier difference, please refer below.

ANSWER:
1. 2Tier is Client server architecture and 3Tier is Client, Server and Database architecture.
2. 3Tier has a Middle stage to communicate client to server, Where as in 2Tier client directly get communication to server.
3. 3Tier is like a MVC, But having difference in topologies
4. 3Tier is linear means in that request flow is Client>>>Middle Layer(SErver application) >>>Databse server and Response is reverse.
While in 2Tier it a Triangular View >>Controller>>Model
5. 3Tier is like Website while web browser is Client application(middle layer), and ASP/PHP language code is server application.

Looping through a hash, or using an array in PowerShell

A short traverse could be given too using the sub-expression operator $( ), which returns the result of one or more statements.

$hash = @{ a = 1; b = 2; c = 3}

forEach($y in $hash.Keys){
    Write-Host "$y -> $($hash[$y])"
}

Result:

a -> 1
b -> 2
c -> 3

Parse a URI String into Name-Value Collection

If you are looking for a way to achieve it without using an external library, the following code will help you.

public static Map<String, String> splitQuery(URL url) throws UnsupportedEncodingException {
    Map<String, String> query_pairs = new LinkedHashMap<String, String>();
    String query = url.getQuery();
    String[] pairs = query.split("&");
    for (String pair : pairs) {
        int idx = pair.indexOf("=");
        query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
    }
    return query_pairs;
}

You can access the returned Map using <map>.get("client_id"), with the URL given in your question this would return "SS".

UPDATE URL-Decoding added

UPDATE As this answer is still quite popular, I made an improved version of the method above, which handles multiple parameters with the same key and parameters with no value as well.

public static Map<String, List<String>> splitQuery(URL url) throws UnsupportedEncodingException {
  final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>();
  final String[] pairs = url.getQuery().split("&");
  for (String pair : pairs) {
    final int idx = pair.indexOf("=");
    final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
    if (!query_pairs.containsKey(key)) {
      query_pairs.put(key, new LinkedList<String>());
    }
    final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
    query_pairs.get(key).add(value);
  }
  return query_pairs;
}

UPDATE Java8 version

public Map<String, List<String>> splitQuery(URL url) {
    if (Strings.isNullOrEmpty(url.getQuery())) {
        return Collections.emptyMap();
    }
    return Arrays.stream(url.getQuery().split("&"))
            .map(this::splitQueryParameter)
            .collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, mapping(Map.Entry::getValue, toList())));
}

public SimpleImmutableEntry<String, String> splitQueryParameter(String it) {
    final int idx = it.indexOf("=");
    final String key = idx > 0 ? it.substring(0, idx) : it;
    final String value = idx > 0 && it.length() > idx + 1 ? it.substring(idx + 1) : null;
    return new SimpleImmutableEntry<>(
        URLDecoder.decode(key, "UTF-8"),
        URLDecoder.decode(value, "UTF-8")
    );
}

Running the above method with the URL

https://stackoverflow.com?param1=value1&param2=&param3=value3&param3

returns this Map:

{param1=["value1"], param2=[null], param3=["value3", null]}

How to use doxygen to create UML class diagrams from C++ source

Enterprise Architect will build a UML diagram from imported source code.

Can an ASP.NET MVC controller return an Image?

You could use the HttpContext.Response and directly write the content to it (WriteFile() might work for you) and then return ContentResult from your action instead of ActionResult.

Disclaimer: I have not tried this, it's based on looking at the available APIs. :-)

Is Spring annotation @Controller same as @Service?

No, @Controller is not the same as @Service, although they both are specializations of @Component, making them both candidates for discovery by classpath scanning. The @Service annotation is used in your service layer, and @Controller is for Spring MVC controllers in your presentation layer. A @Controller typically would have a URL mapping and be triggered by a web request.

How to set fake GPS location on IOS real device

Of course ios7 prohibits creating fake locations on real device.
For testing purpose there are two approches:
1) while device is connected to xcode, use the simulator and let it play a gpx track.

2) for real world testing, not connected to simu, one possibility is that your app, has a special modus built in, where you set it to "playback" mode. In that mode the app has to create the locations itself, using a timer of 1s, and creating a new CLLocation object.

3) A third possibility is described here: https://blackpixel.com/writing/2013/05/simulating-locations-with-xcode.html

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

Here's a plain JavaScript version:

function scroll(e) {
  var delta = (e.type === "mousewheel") ? e.wheelDelta : e.detail * -40;
  if (delta < 0 && (this.scrollHeight - this.offsetHeight - this.scrollTop) <= 0) {
    this.scrollTop = this.scrollHeight;
    e.preventDefault();
  } else if (delta > 0 && delta > this.scrollTop) {
    this.scrollTop = 0;
    e.preventDefault();
  }
}
document.querySelectorAll(".scroller").addEventListener("mousewheel", scroll);
document.querySelectorAll(".scroller").addEventListener("DOMMouseScroll", scroll);

Finding a substring within a list in Python

I'd just use a simple regex, you can do something like this

import re
old_list = ['abc123', 'def456', 'ghi789']
new_list = [x for x in old_list if re.search('abc', x)]
for item in new_list:
    print item

multi line comment vb.net in Visual studio 2010

The only way is to highlight the lines to comment and press

ctrl + k, ctrl + c

or after highlighted press the toolbar option to comment out the selected lines.

The icons look like this enter image description here

websocket closing connection automatically

Here is an example on how to configure Jetty's websocket timeout (the most likely culprit) using WebSocketServlet (in scala, sorry, but the syntax is pretty much the same).

import javax.servlet.annotation.WebServlet
import org.eclipse.jetty.websocket.servlet.{WebSocketServletFactory, WebSocketServlet}

@WebServlet(name = "WebSocket Servlet")
class WebsocketServlet extends WebSocketServlet {
  override def configure(factory: WebSocketServletFactory): Unit = {
    factory.getPolicy.setIdleTimeout(1000 * 3600)
    factory.register(classOf[ClientWebsocket])
  }
}

Login credentials not working with Gmail SMTP

I had already enabled "Allow less secure apps" and my SMPT python program was working perfectly!

But next day it stared giving me "Bad Credentials error (SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted)". I was using the exact same credentials as before and the less secure apps option was also enabled..!

Changed my password again but that also did not help.

Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

https://accounts.google.com/DisplayUnlockCaptcha

Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

Note: Had to try multipe times to get this option enabled. Once enabled, I tried connecting after 30mins and it worked..!!!

Hope this helps.

How to get Time from DateTime format in SQL?

SQL Server 2008:

SELECT cast(AttDate as time) [time]
FROM yourtable

Earlier versions:

SELECT convert(char(5), AttDate, 108) [time]
FROM yourtable

compare two list and return not matching items using linq

If u wanna Select items of List from 2nd list:

MainList.Where(p => 2ndlist.Contains(p.columns from MainList )).ToList();

Error: unmappable character for encoding UTF8 during maven compilation

This happens in the following scenario: When working on Windows, the IDE is more than likely configured to edit files in Cp1252, which is a Microsoft adaptation of latin-11. The developer checks in, and the Continuous Integration server (usually running on Linux, which nowadays is all utf8) picks up the file, and tries to compile as a UTF-8 file, hence the warning.

Try changing the encoding to cp1252. This works. To avoid future problems of this kind, use the same encoding on all the developer machines.

Good luck...

how to calculate binary search complexity

Here is wikipedia entry

If you look at the simple iterative approach. You are just eliminating half of the elements to be searched for until you find the element you need.

Here is the explanation of how we come up with the formula.

Say initially you have N number of elements and then what you do is ?N/2? as a first attempt. Where N is sum of lower bound and upper bound. The first time value of N would be equal to (L + H), where L is the first index (0) and H is the last index of the list you are searching for. If you are lucky, the element you try to find will be in the middle [eg. You are searching for 18 in the list {16, 17, 18, 19, 20} then you calculate ?(0+4)/2? = 2 where 0 is lower bound (L - index of the first element of the array) and 4 is the higher bound (H - index of the last element of the array). In the above case L = 0 and H = 4. Now 2 is the index of the element 18 that you are searching found. Bingo! You found it.

If the case was a different array{15,16,17,18,19} but you were still searching for 18 then you would not be lucky and you would be doing first N/2 (which is ?(0+4)/2? = 2 and then realize element 17 at the index 2 is not the number you are looking for. Now you know that you don’t have to look for at least half of the array in your next attempt to search iterative manner. Your effort of searching is halved. So basically, you do not search half the list of elements that you searched previously, every time you try to find the element that you were not able to find in your previous attempt.

So the worst case would be

[N]/2 + [(N/2)]/2 + [((N/2)/2)]/2.....
i.e:
N/21 + N/22 + N/23 +..... + N/2x …..

until …you have finished searching, where in the element you are trying to find is at the ends of the list.

That shows the worst case is when you reach N/2x where x is such that 2x = N

In other cases N/2x where x is such that 2x < N Minimum value of x can be 1, which is the best case.

Now since mathematically worst case is when the value of
2x = N
=> log2(2x) = log2(N)
=> x * log2(2) = log2(N)
=> x * 1 = log2(N)
=> More formally ?log2(N)+1?

How to make Python script run as service?

first import os module in your app than with use from getpid function get pid's app and save in a file.for example :

import os
pid = os.getpid()
op = open("/var/us.pid","w")
op.write("%s" % pid)
op.close()

and create a bash file in /etc/init.d path: /etc/init.d/servername

PATHAPP="/etc/bin/userscript.py &"
PIDAPP="/var/us.pid"
case $1 in 
        start)
                echo "starting"
                $(python $PATHAPP)
        ;;
        stop)
                echo "stoping"
                PID=$(cat $PIDAPP)
                kill $PID
        ;;

esac

now , u can start and stop ur app with down command:

service servername stop service servername start

or

/etc/init.d/servername stop /etc/init.d/servername start

How do I set a fixed background image for a PHP file?

You should consider have other php files included if you're going to derive a website from it. Instead of doing all the css/etc in that file, you can do

<head>
    <?php include_once('C:\Users\George\Documents\HTML\style.css'); ?>
    <title>Title</title>
</hea>

Then you can have a separate CSS file that is just being pulled into your php file. It provides some "neater" coding.

Remove duplicated rows

Or you could nest the data in cols 4 and 5 into a single row with tidyr:

library(tidyr)
df %>% nest(V4:V5)

# A tibble: 1 × 4
#                      V1    V2    V3             data
#                  <fctr> <int> <int>           <list>
#1 platform_external_dbus   202    16 <tibble [5 × 2]>

The col 2 and 3 duplicates are now removed for statistical analysis, but you have kept the col 4 and 5 data in a tibble and can go back to the original data frame at any point with unnest().

How can I iterate over an enum?

The typical way is as follows:

enum Foo {
  One,
  Two,
  Three,
  Last
};

for ( int fooInt = One; fooInt != Last; fooInt++ )
{
   Foo foo = static_cast<Foo>(fooInt);
   // ...
}

Please note, the enum Last is meant to be skipped by the iteration. Utilizing this "fake" Last enum, you don't have to update your terminating condition in the for loop to the last "real" enum each time you want to add a new enum. If you want to add more enums later, just add them before Last. The loop in this example will still work.

Of course, this breaks down if the enum values are specified:

enum Foo {
  One = 1,
  Two = 9,
  Three = 4,
  Last
};

This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.

switch ( foo )
{
    case One:
        // ..
        break;
    case Two:  // intentional fall-through
    case Three:
        // ..
        break;
    case Four:
        // ..
        break;
     default:
        assert( ! "Invalid Foo enum value" );
        break;
}

If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.

How can I change the default width of a Twitter Bootstrap modal box?

you can use any prefix or postfix name for modal. but you need to make sure that's should use everywhere with same prefix/postfix name.    

body .modal-nk {
        /* new custom width */
        width: 560px;
        /* must be half of the width, minus scrollbar on the left (30px) */
        margin-left: -280px;
    }

or

body .nk-modal {
            /* new custom width */
            width: 560px;
            /* must be half of the width, minus scrollbar on the left (30px) */
            margin-left: -280px;
        }

WPF - add static items to a combo box

Here is the code from MSDN and the link - Article Link, which you should check out for more detail.

<ComboBox Text="Is not open">
    <ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
    <ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
    <ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

Twitter Bootstrap Button Text Word Wrap

You can simply add this class.

.btn {
    white-space:normal !important;
    word-wrap: break-word; 
}

The backend version is not supported to design database diagrams or tables

I was having the same problem, although I solved out by creating the table using a script query instead of doing it graphically. See the snipped below:

USE [Database_Name]
GO

CREATE TABLE [dbo].[Table_Name](
[tableID] [int] IDENTITY(1,1) NOT NULL,
[column_2] [datatype] NOT NULL,
[column_3] [datatype] NOT NULL,

CONSTRAINT [PK_Table_Name] PRIMARY KEY CLUSTERED 
(
[tableID] ASC
)
)

Allow only pdf, doc, docx format for file upload?

For only acept files with extension doc and docx in the explorer window try this

    <input type="file" id="docpicker"
  accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">

How to hide a div element depending on Model value? MVC

Try:

<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

Python dictionary: Get list of values for list of keys

Try this:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one'] # if there are many keys, use a set

[mydict[k] for k in mykeys]
=> [3, 1]

Submitting a form on 'Enter' with jQuery?

Here's a way to do this as a JQuery plugin (in case you want to re-use the functionality):

$.fn.onEnterKey =
    function( closure ) {
        $(this).keypress(
            function( event ) {
                var code = event.keyCode ? event.keyCode : event.which;

                if (code == 13) {
                    closure();
                    return false;
                }
            } );
    }

Now if you want to decorate an <input> element with this type of functionality it's as simple as this:

$('#your-input-id').onEnterKey(
    function() {
        // Do stuff here
    } );

Run reg command in cmd (bat file)?

You could also just create a Group Policy Preference and have it create the reg key for you. (no scripting involved)

How to write a caption under an image?

<div style="margin: 0 auto; text-align: center; overflow: hidden;">
  <div style="float: left;">
    <a href="http://xyz.com/hello"><img src="hello.png" width="100px" height="100px"></a>
    caption 1
  </div>
 <div style="float: left;">
   <a href="http://xyz.com/hi"><img src="hi.png" width="100px" height="100px"></a>
   caption 2                      
 </div>
</div>

what is the difference between GROUP BY and ORDER BY in sql

ORDER BY alters the order in which items are returned.

GROUP BY will aggregate records by the specified columns which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc).

Get height of div with no height set in css

Just a note in case others have the same problem.

I had the same problem and found a different answer. I found that getting the height of a div that's height is determined by its contents needs to be initiated on window.load, or window.scroll not document.ready otherwise i get odd heights/smaller heights, i.e before the images have loaded. I also used outerHeight().

var currentHeight = 0;
$(window).load(function() {
    //get the natural page height -set it in variable above.

    currentHeight = $('#js_content_container').outerHeight();

    console.log("set current height on load = " + currentHeight)
    console.log("content height function (should be 374)  = " + contentHeight());   

});

List all indexes on ElasticSearch server?

For a concise list of all indices in your cluster, call

curl http://localhost:9200/_aliases

this will give you a list of indices and their aliases.

If you want it pretty-printed, add pretty=true:

curl http://localhost:9200/_aliases?pretty=true

The result will look something like this, if your indices are called old_deuteronomy and mungojerrie:

{
  "old_deuteronomy" : {
    "aliases" : { }
  },
  "mungojerrie" : {
    "aliases" : {
      "rumpleteazer" : { },
      "that_horrible_cat" : { }
    }
  }
}

Add CSS class to a div in code behind

The Style property gets a collection of all the cascading style sheet (CSS) properties; you cannot set it.

Try BtnventCss.CssClass = "hom_but_a"; instead.

I'm assuming BtnventCss is a WebControl.

I have just seen you're probably using <div runat="server"...

If so, you can try:

BtnventCss.Attributes.Add("class", "hom_but_a");

You could make the div an asp:panel - they will render the same and you'll get better server-side support.

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

This can be done without terminal, directly from IDE. Netbeans, for example.

  1. Create a separate project with packages (Create Project - Java - Java Class Library).
  2. Put your .java classes there.
  3. Build this project.
  4. Go to your project folder and find build and dist folders there.
  5. Find .jar file in your dist folder.
  6. Get your other project and add this .jar file to project libraries.
  7. You can now reference classes from this library and its methods directly from code, if import is automatically done for you.

How do I find numeric columns in Pandas?

Adapting this answer, you could do

df.ix[:,df.applymap(np.isreal).all(axis=0)]

Here, np.applymap(np.isreal) shows whether every cell in the data frame is numeric, and .axis(all=0) checks if all values in a column are True and returns a series of Booleans that can be used to index the desired columns.

Bind failed: Address already in use

You have a process that is already using that port. netstat -tulpn will enable one to find the process ID of that is using a particular port.

Maximum concurrent connections to MySQL

I can assure you that raw speed ultimately lies in the non-standard use of Indexes for blazing speed using large tables.

How to pass model attributes from one Spring MVC controller to another controller?

If you want just pass all attributes to redirect...

public String yourMethod( ...., HttpServletRequest request, RedirectAttributes redirectAttributes) {
    if(shouldIRedirect()) {
        redirectAttributes.addAllAttributes(request.getParameterMap());
        return "redirect:/newPage.html";
    }
}

Linux command-line call not returning what it should from os.system?

okey I believe the fastest way it would be

import os
print(os.popen('command').readline())
x = _
print(x)

How to access the elements of a 2D array?

If you have

a=[[1,1],[2,1],[3,1]]
b=[[1,2],[2,2],[3,2]]

Then

a[1][1]

Will work fine. It points to the second column, second row just like you wanted.

I'm not sure what you did wrong.

To multiply the cells in the third column you can just do

c = [a[2][i] * b[2][i] for i in range(len(a[2]))] 

Which will work for any number of rows.

Edit: The first number is the column, the second number is the row, with your current layout. They are both numbered from zero. If you want to switch the order you can do

a = zip(*a)

or you can create it that way:

a=[[1, 2, 3], [1, 1, 1]]

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Try this in the console:

JSON.parse(undefined)

Here is what you will get:

Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

In other words, your app is attempting to parse undefined, which is not valid JSON.

There are two common causes for this. The first is that you may be referencing a non-existent property (or even a non-existent variable if not in strict mode).

window.foobar = '{"some":"data"}';
JSON.parse(window.foobarn)  // oops, misspelled!

The second common cause is failure to receive the JSON in the first place, which could be caused by client side scripts that ignore errors and send a request when they shouldn't.

Make sure both your server-side and client-side scripts are running in strict mode and lint them using ESLint. This will give you pretty good confidence that there are no typos.

How to make the main content div fill height of screen with css

This allows for a centered content body with min-width for my forms to not collapse funny:

html {
    overflow-y: scroll;
    height: 100%;
    margin: 0px auto;
    padding: 0;
}

body {
    height: 100%;
    margin: 0px auto;
    max-width: 960px;
    min-width: 750px;
    padding: 0;
}
div#footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    height: 60px;
}

div#wrapper {
    height: auto !important;
    min-height: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
}

div#pageContent {
    padding-bottom: 60px;
}

div#header {
    width: 100%;
}

And my layout page looks like:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>
    <title></title>
</head>
<body>
<div id="wrapper">
        <div id="header"></div>
        <div id="pageContent"></div>
        <div id="footer"></div>
    </div>
</body>
</html>

Example here: http://data.nwtresearch.com/

One more note, if you want the full page background like the code you added looks like, remove the height: auto !important; from the wrapper div: http://jsfiddle.net/mdares/a8VVw/

Table scroll with HTML and CSS

Works only in Chrome but it can be adapted to other modern browsers. Table falls back to common table with scroll bar in other brws. Uses CSS3 FLEX property.

http://jsfiddle.net/4SUP8/1/

<table border="1px" class="flexy">
    <caption>Lista Sumnjivih vozila:</caption>
    <thead>
        <tr>
            <td>Opis Sumnje</td>
        <td>Registarski<br>broj vozila</td>
        <td>Datum<br>Vreme</td>
        <td>Brzina<br>(km/h)</td>
        <td>Lokacija</td>
        <td>Status</td>
        <td>Akcija</td>
        </tr>
    </thead>
    <tbody>

        <tr>
        <td>Osumnjicen tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>
        <tr>

        <tr>
        <td>Osumnjicen tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>
        <tr>

        <tr>
        <td>Osumnjicen tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>
        <tr>


        <tr>
        <td>Osumnjicen tranzit</td>
        <td>NS182TP</td>
        <td>23-03-2014 20:48:08</td>
        <td>11.3</td>
        <td>Raskrsnica kod pumpe<br></td>
        <td></td>
        <td>Prikaz</td>
        </tr>

    </tbody>
</table>

Style (CSS 3):

caption {
    display: block;
    line-height: 3em;
    width: 100%;
    -webkit-align-items: stretch;
    border: 1px solid #eee;
}

       .flexy {
            display: block;
            width: 90%;
            border: 1px solid #eee;
            max-height: 320px;
            overflow: auto;
        }

        .flexy thead {
            display: -webkit-flex;
            -webkit-flex-flow: row;
        }

        .flexy thead tr {
            padding-right: 15px;
            display: -webkit-flex;
            width: 100%;
            -webkit-align-items: stretch;
        }

        .flexy tbody {
            display: -webkit-flex;
            height: 100px;
            overflow: auto;
            -webkit-flex-flow: row wrap;
        }
        .flexy tbody tr{
            display: -webkit-flex;
            width: 100%;
        }

        .flexy tr td {
            width: 15%;
        }

how to read value from string.xml in android?

getString(R.string.your_string) get the result

At runtime, find all classes in a Java application that extend a base class

One way is to make the classes use a static initializers... I don't think these are inherited (it won't work if they are):

public class Dog extends Animal{

static
{
   Animal a = new Dog();
   //add a to the List
}

It requires you to add this code to all of the classes involved. But it avoids having a big ugly loop somewhere, testing every class searching for children of Animal.

Rails: How can I rename a database column in a Ruby on Rails migration?

If your code is not shared with other one, then best option is to do just rake db:rollback then edit your column name in migration and rake db:migrate. Thats it

And you can write another migration to rename the column

 def change
    rename_column :table_name, :old_name, :new_name
  end

Thats it.

How to convert a HTMLElement to a string

I was using Angular, and needed the same thing, and landed at this post.

@ViewChild('myHTML', {static: false}) _html: ElementRef;
this._html.nativeElement;

How to clear a textbox using javascript

<input type="text" value="A new value" onfocus="this.value='';">

However this will be very irrigating for users that focus the element a second time e.g. to correct something.

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

I had this issue with a WinForms Project using VS 2015. My solution was:

  1. right click the Project
  2. select properties
  3. check "Prefer 32-bit"
  4. Platform target: Any CPU

fail to change placeholder color with Bootstrap 3

A Possible Gotcha

Recommended Sanity Check - Make sure to add the form-control class to your inputs.

If you have bootstrap css loaded on your page, but your inputs don't have the
class="form-control" then placeholder CSS selector won't apply to them.

Example markup from the docs:

I know this didn't apply to the OP's markup but as I missed this at first and spent a little bit of effort trying to debug it, I'm posting this answer to help others.

jQuery vs. javascript?

Jquery like any other good JavaScript frameworks supplies you with functionality independent of browser platform wrapping all the intricacies, which you may not care about or don't want to care about.

I think using a framework is better instead of using pure JavaScript and doing all the stuff from scratch, unless you usage is very limited.

I definitely recommend JQuery!

Thanks