Programs & Examples On #Google chrome frame

Google Chrome Frame is a plug-in designed for Internet Explorer based on the open-source Chromium project; it brings Google Chrome's open web technologies to Internet Explorer.

Is it still valid to use IE=edge,chrome=1?

It's still valid to use IE=edge,chrome=1.

But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.

I use the following for correctness nowadays

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

You need to annotate your Customer class with @Named or @Model annotation:

package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
    private String email;
    private String password;
}

or create/modify beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">
</beans>

How to remove MySQL root password

I have also been through this problem,

First i tried setting my password of root to blank using command :

SET PASSWORD FOR root@localhost=PASSWORD('');

But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.

SET PASSWORD FOR [email protected]=PASSWORD('');

Just replace localhost with 127.0.0.1 and you are done .

Git ignore file for Xcode projects

For Xcode 4 I also add:

YourProjectName.xcodeproj/xcuserdata/*
YourProjectName.xcodeproj/project.xcworkspace/xcuserdata/*

How to make div background color transparent in CSS

Opacity gives you translucency or transparency. See an example Fiddle here.

-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";       /* IE 8 */
filter: alpha(opacity=50);  /* IE 5-7 */
-moz-opacity: 0.5;          /* Netscape */
-khtml-opacity: 0.5;        /* Safari 1.x */
opacity: 0.5;               /* Good browsers */

Note: these are NOT CSS3 properties

See http://css-tricks.com/snippets/css/cross-browser-opacity/

Where value in column containing comma delimited values

SELECT * FROM TABLE_NAME WHERE
        (
            LOCATE(',DOG,', CONCAT(',',COLUMN,','))>0 OR
            LOCATE(',CAT,', CONCAT(',',COLUMN,','))>0
        );

Cannot access wamp server on local network

1.

first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)

2.

If you are using WAMPServer 3 See bottom of answer

For WAMPServer versions <= 2.5

You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf file.

Change this section from :

#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

To :

#   onlineoffline tag - don't remove
    Order Allow,Deny
      Allow from all

if "Allow from all" line not work for your then use "Require all granted" then it will work for you.

WAMPServer 3 has a different method

In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost so dont amend the httpd.conf file at all, leave it as you found it.

Using the menus, edit the httpd-vhosts.conf file.

enter image description here

It should look like this :

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

Amend it to

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80

3. Dont forget to restart All Services of Wamp or Apache after making this change

Javascript getElementById based on a partial string

Try this.

function getElementsByIdStartsWith(container, selectorTag, prefix) {
    var items = [];
    var myPosts = document.getElementById(container).getElementsByTagName(selectorTag);
    for (var i = 0; i < myPosts.length; i++) {
        //omitting undefined null check for brevity
        if (myPosts[i].id.lastIndexOf(prefix, 0) === 0) {
            items.push(myPosts[i]);
        }
    }
    return items;
}

Sample HTML Markup.

<div id="posts">
    <div id="post-1">post 1</div>
    <div id="post-12">post 12</div>
    <div id="post-123">post 123</div>
    <div id="pst-123">post 123</div>
</div>

Call it like

var postedOnes = getElementsByIdStartsWith("posts", "div", "post-");

Demo here: http://jsfiddle.net/naveen/P4cFu/

Cheap way to search a large text file for a string

This is entirely inspired by laurasia's answer above, but it refines the structure.

It also adds some checks:

  • It will correctly return 0 when searching an empty file for the empty string. In laurasia's answer, this is an edge case that will return -1.
  • It also pre-checks whether the goal string is larger than the buffer size, and raises an error if this is the case.

In practice, the goal string should be much smaller than the buffer for efficiency, and there are more efficient methods of searching if the size of the goal string is very close to the size of the buffer.

def fnd(fname, goal, start=0, bsize=4096):
    if bsize < len(goal):
        raise ValueError("The buffer size must be larger than the string being searched for.")
    with open(fname, 'rb') as f:
        if start > 0:
            f.seek(start)
        overlap = len(goal) - 1
        while True:
            buffer = f.read(bsize)
            pos = buffer.find(goal)
            if pos >= 0:
                return f.tell() - len(buffer) + pos
            if not buffer:
                return -1
            f.seek(f.tell() - overlap)

How to calculate the number of occurrence of a given character in each row of a column of strings?

nchar(as.character(q.data$string)) -nchar( gsub("a", "", q.data$string))
[1] 2 1 0

Notice that I coerce the factor variable to character, before passing to nchar. The regex functions appear to do that internally.

Here's benchmark results (with a scaled up size of the test to 3000 rows)

 q.data<-q.data[rep(1:NROW(q.data), 1000),]
 str(q.data)
'data.frame':   3000 obs. of  3 variables:
 $ number     : int  1 2 3 1 2 3 1 2 3 1 ...
 $ string     : Factor w/ 3 levels "greatgreat","magic",..: 1 2 3 1 2 3 1 2 3 1 ...
 $ number.of.a: int  2 1 0 2 1 0 2 1 0 2 ...

 benchmark( Dason = { q.data$number.of.a <- str_count(as.character(q.data$string), "a") },
 Tim = {resT <- sapply(as.character(q.data$string), function(x, letter = "a"){
                            sum(unlist(strsplit(x, split = "")) == letter) }) }, 

 DWin = {resW <- nchar(as.character(q.data$string)) -nchar( gsub("a", "", q.data$string))},
 Josh = {x <- sapply(regmatches(q.data$string, gregexpr("g",q.data$string )), length)}, replications=100)
#-----------------------
   test replications elapsed  relative user.self sys.self user.child sys.child
1 Dason          100   4.173  9.959427     2.985    1.204          0         0
3  DWin          100   0.419  1.000000     0.417    0.003          0         0
4  Josh          100  18.635 44.474940    17.883    0.827          0         0
2   Tim          100   3.705  8.842482     3.646    0.072          0         0

SQL query, if value is null then return 1

You can use a CASE statement.

SELECT 
    CASE WHEN currate.currentrate IS NULL THEN 1 ELSE currate.currentrate END
FROM ...

What's the console.log() of java?

console.log() in java is System.out.println(); to put text on the next line

And System.out.print(); puts text on the same line.

How to save .xlsx data to file as a blob

Solution for me.

Step: 1

<a onclick="exportAsExcel()">Export to excel</a>

Step: 2

I'm using file-saver lib.

Read more: https://www.npmjs.com/package/file-saver

npm i file-saver

Step: 3

let FileSaver = require('file-saver'); // path to file-saver

function exportAsExcel() {
    let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only
    this.downloadFile(dataBlob);
}

function downloadFile(blobContent){
    let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});
    FileSaver.saveAs(blob, 'report.xlsx');
}

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    let sliceSize = 1024;
    let byteCharacters = atob(base64Data);
    let bytesLength = byteCharacters.length;
    let slicesCount = Math.ceil(bytesLength / sliceSize);
    let byteArrays = new Array(slicesCount);
    for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        let begin = sliceIndex * sliceSize;
        let end = Math.min(begin + sliceSize, bytesLength);

        let bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Work for me. ^^

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

This is due to the mismatch of the data type of your java Entity and the database table column. Please review if all the column is exact same data type as your entity. This mismatch happens when we update our model attribute's data-type.

Bootstrap row class contains margin-left and margin-right which creates problems

Here is your simple and easy answer

Go to your class where you want to give a negative margin then copy and paste this inside the class.

Example for negative margin top

mt-n3

Example for negative margin bottom

mb-n2

Static variables in JavaScript

I've seen a couple of similar answers, but I'd like to mention that this post describes it best, so I'd like to share it with you.

Here's some code taken from it, which I have modified to get a complete example which hopefully gives benefit to the community because it can be used as a design template for classes.

It also answers your question:

function Podcast() {

    // private variables
    var _somePrivateVariable = 123;

    // object properties (read/write)
    this.title = 'Astronomy Cast';
    this.description = 'A fact-based journey through the galaxy.';
    this.link = 'http://www.astronomycast.com';

    // for read access to _somePrivateVariable via immutableProp 
    this.immutableProp = function() {
        return _somePrivateVariable;
    }

    // object function
    this.toString = function() {
       return 'Title: ' + this.title;
    }
};

// static property
Podcast.FILE_EXTENSION = 'mp3';
// static function
Podcast.download = function(podcast) {
    console.log('Downloading ' + podcast + ' ...');
};

Given that example, you can access the static properties/function as follows:

// access static properties/functions
console.log(Podcast.FILE_EXTENSION);   // 'mp3'
Podcast.download('Astronomy cast');    // 'Downloading Astronomy cast ...'

And the object properties/functions simply as:

// access object properties/functions
var podcast = new Podcast();
podcast.title = 'The Simpsons';
console.log(podcast.toString());       // Title: The Simpsons
console.log(podcast.immutableProp());  // 123

Note that in podcast.immutableProp(), we have a closure: The reference to _somePrivateVariable is kept inside the function.

You can even define getters and setters. Take a look at this code snippet (where d is the object's prototype for which you want to declare a property, y is a private variable not visible outside of the constructor):

// getters and setters
var d = Date.prototype;
Object.defineProperty(d, "year", {
    get: function() {return this.getFullYear() },
    set: function(y) { this.setFullYear(y) }
});

It defines the property d.year via get and set functions - if you don't specify set, then the property is read-only and cannot be modified (be aware you will not get an error if you try to set it, but it has no effect). Each property has the attributes writable, configurable (allow to change after declaration) and enumerable (allow to use it as enumerator), which are per default false. You can set them via defineProperty in the 3rd parameter, e.g. enumerable: true.

What is also valid is this syntax:

// getters and setters - alternative syntax
var obj = { a: 7, 
            get b() {return this.a + 1;}, 
            set c(x) {this.a = x / 2}
        };

which defines a readable/writable property a, a readonly property b and a write-only property c, through which property a can be accessed.

Usage:

console.log(obj.a); console.log(obj.b); // output: 7, 8
obj.c=40;
console.log(obj.a); console.log(obj.b); // output: 20, 21

Notes:

To avoid unexpected behaviour in case you've forgotten the new keyword, I suggest that you add the following to the function Podcast:

// instantiation helper
function Podcast() {
    if(false === (this instanceof Podcast)) {
        return new Podcast();
    }
// [... same as above ...]
};

Now both of the following instantiations will work as expected:

var podcast = new Podcast(); // normal usage, still allowed
var podcast = Podcast();     // you can omit the new keyword because of the helper

The 'new' statement creates a new object and copies all properties and methods, i.e.

var a=new Podcast();
var b=new Podcast();
a.title="a"; b.title="An "+b.title;
console.log(a.title); // "a"
console.log(b.title); // "An Astronomy Cast"

Note also, that in some situations it can be useful to use the return statement in the constructor function Podcast to return a custom object protecting functions the class internally relies on but which need to be exposed. This is explained further in chapter 2 (Objects) of the article series.

You can say that a and b inherit from Podcast. Now, what if you want to add a method to Podcast that applies to all of them after a and b have been instanciated? In this case, use the .prototype as follows:

Podcast.prototype.titleAndLink = function() {
    return this.title + " [" + this.link + "]";
};

Now call a and b again:

console.log(a.titleAndLink()); // "a [http://www.astronomycast.com]"
console.log(b.titleAndLink()); // "An Astronomy Cast [http://www.astronomycast.com]"

You can find more details about prototypes here. If you want to do more inheritance, I suggest looking into this.


The article series I've mentioned above are highly recommended to read, they include also the following topics:

  1. Functions
  2. Objects
  3. Prototypes
  4. Enforcing New on Constructor Functions
  5. Hoisting
  6. Automatic Semicolon Insertion
  7. Static Properties and Methods

Note that the automatic semicolon insertion "feature" of JavaScript (as mentioned in 6.) is very often responsible for causing strange issues in your code. Hence, I would rather regard it as a bug than as a feature.

If you want to read more, here is a quite interesting MSDN article about these topics, some of them described there provide even more details.

What is interesting to read as well (also covering the topics mentioned above) are those articles from the MDN JavaScript Guide:

If you want to know how to emulate c# out parameters (like in DateTime.TryParse(str, out result)) in JavaScript, you can find sample code here.


Those of you who are working with IE (which has no console for JavaScript unless you open the developer tools using F12 and open the console tab) might find the following snippet useful. It allows you to use console.log(msg); as used in the examples above. Just insert it before the Podcast function.

For your convenience, here's the code above in one complete single code snippet:

_x000D_
_x000D_
let console = { log: function(msg) {  _x000D_
  let canvas = document.getElementById("log"), br = canvas.innerHTML==="" ? "" : "<br/>";_x000D_
  canvas.innerHTML += (br + (msg || "").toString());_x000D_
}};_x000D_
_x000D_
console.log('For details, see the explaining text');_x000D_
_x000D_
function Podcast() {_x000D_
_x000D_
  // with this, you can instantiate without new (see description in text)_x000D_
  if (false === (this instanceof Podcast)) {_x000D_
    return new Podcast();_x000D_
  }_x000D_
_x000D_
  // private variables_x000D_
  var _somePrivateVariable = 123;_x000D_
_x000D_
  // object properties_x000D_
  this.title = 'Astronomy Cast';_x000D_
  this.description = 'A fact-based journey through the galaxy.';_x000D_
  this.link = 'http://www.astronomycast.com';_x000D_
_x000D_
  this.immutableProp = function() {_x000D_
    return _somePrivateVariable;_x000D_
  }_x000D_
_x000D_
  // object function_x000D_
  this.toString = function() {_x000D_
    return 'Title: ' + this.title;_x000D_
  }_x000D_
};_x000D_
_x000D_
// static property_x000D_
Podcast.FILE_EXTENSION = 'mp3';_x000D_
// static function_x000D_
Podcast.download = function(podcast) {_x000D_
  console.log('Downloading ' + podcast + ' ...');_x000D_
};_x000D_
_x000D_
_x000D_
// access static properties/functions_x000D_
Podcast.FILE_EXTENSION; // 'mp3'_x000D_
Podcast.download('Astronomy cast'); // 'Downloading Astronomy cast ...'_x000D_
_x000D_
// access object properties/functions_x000D_
var podcast = new Podcast();_x000D_
podcast.title = 'The Simpsons';_x000D_
console.log(podcast.toString()); // Title: The Simpsons_x000D_
console.log(podcast.immutableProp()); // 123_x000D_
_x000D_
// getters and setters_x000D_
var d = Date.prototype;_x000D_
Object.defineProperty(d, "year", {_x000D_
  get: function() {_x000D_
    return this.getFullYear()_x000D_
  },_x000D_
  set: function(y) {_x000D_
    this.setFullYear(y)_x000D_
  }_x000D_
});_x000D_
_x000D_
// getters and setters - alternative syntax_x000D_
var obj = {_x000D_
  a: 7,_x000D_
  get b() {_x000D_
    return this.a + 1;_x000D_
  },_x000D_
  set c(x) {_x000D_
    this.a = x / 2_x000D_
  }_x000D_
};_x000D_
_x000D_
// usage:_x000D_
console.log(obj.a); console.log(obj.b); // output: 7, 8_x000D_
obj.c=40;_x000D_
console.log(obj.a); console.log(obj.b); // output: 20, 21_x000D_
_x000D_
var a=new Podcast();_x000D_
var b=new Podcast();_x000D_
a.title="a"; b.title="An "+b.title;_x000D_
console.log(a.title); // "a"_x000D_
console.log(b.title); // "An Astronomy Cast"_x000D_
_x000D_
Podcast.prototype.titleAndLink = function() {_x000D_
    return this.title + " [" + this.link + "]";_x000D_
};_x000D_
    _x000D_
console.log(a.titleAndLink()); // "a [http://www.astronomycast.com]"_x000D_
console.log(b.titleAndLink()); // "An Astronomy Cast [http://www.astronomycast.com]"
_x000D_
<div id="log"></div>
_x000D_
_x000D_
_x000D_


Notes:

  • Some good tips, hints and recommendations about JavaScript programming in general you can find here (JavaScript best practices) and there ('var' versus 'let'). Also recommended is this article about implicit typecasts (coercion).

  • A convenient way to use classes and compile them into JavaScript is TypeScript. Here is a playground where you can find some examples showing you how it works. Even if you're not using TypeScript at the moment, you can have a look because you can compare TypeScript with the JavaScript result on a side-by-side view. Most examples are simple, but there is also a Raytracer example which you can try out instantly. I recommend especially looking into the "Using Classes", "Using Inheritance" and "Using Generics" examples by selecting them in the combobox - these are nice templates you can instantly use in JavaScript. Typescript is used with Angular.

  • To achieve encapsulation of local variables, functions etc in JavaScript, I suggest to use a pattern like the following (JQuery uses the same technique):

_x000D_
_x000D_
<html>_x000D_
<head></head>_x000D_
<body><script>_x000D_
    'use strict';_x000D_
    // module pattern (self invoked function)_x000D_
    const myModule = (function(context) { _x000D_
    // to allow replacement of the function, use 'var' otherwise keep 'const'_x000D_
_x000D_
      // put variables and function with local module scope here:_x000D_
      var print = function(str) {_x000D_
        if (str !== undefined) context.document.write(str);_x000D_
        context.document.write("<br/><br/>");_x000D_
        return;_x000D_
      }_x000D_
      // ... more variables ..._x000D_
_x000D_
      // main method_x000D_
      var _main = function(title) {_x000D_
_x000D_
        if (title !== undefined) print(title);_x000D_
        print("<b>last modified:&nbsp;</b>" + context.document.lastModified + "<br/>");        _x000D_
        // ... more code ..._x000D_
      }_x000D_
_x000D_
      // public methods_x000D_
      return {_x000D_
        Main: _main_x000D_
        // ... more public methods, properties ..._x000D_
      };_x000D_
_x000D_
    })(this);_x000D_
_x000D_
    // use module_x000D_
    myModule.Main("<b>Module demo</b>");_x000D_
</script></body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Of course, you can - and should - put the script code in a separate *.js file; this is just written inline to keep the example short.

Self-invocing functions (also known as IIFE = Immediately Invoked Function Expression) are described in more detail here.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Where in memory are my variables stored in C?

I am referring to these variables only from the C perspective.

From the perspective of the C language, all that matters is extent, scope, linkage, and access; exactly how items are mapped to different memory segments is up to the individual implementation, and that will vary. The language standard doesn't talk about memory segments at all. Most modern architectures act mostly the same way; block-scope variables and function arguments will be allocated from the stack, file-scope and static variables will be allocated from a data or code segment, dynamic memory will be allocated from a heap, some constant data will be stored in read-only segments, etc.

Nodemailer with Gmail and NodeJS

Just attend those: 1- Gmail authentication for allow low level emails does not accept before you restart your client browser 2- If you want to send email with nodemailer and you wouldnt like to use xouath2 protocol there you should write as secureconnection:false like below

const routes = require('express').Router();
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');



routes.get('/test', (req, res) => {
  res.status(200).json({ message: 'test!' });
});

routes.post('/Email', (req, res) =>{

    var smtpTransport = nodemailer.createTransport({
        host: "smtp.gmail.com",
        secureConnection: false,
        port: 587,
        requiresAuth: true,
        domains: ["gmail.com", "googlemail.com"],
        auth: {
            user: "your gmail account", 
            pass: "your password*"
        }
});  

  var mailOptions = {
      from: '[email protected]',
      to:'[email protected]',
      subject: req.body.subject,
      //text: req.body.content,
      html: '<p>'+req.body.content+' </p>'
  };

  smtpTransport.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log('Error while sending mail: ' + error);
    } else {
        console.log('Message sent: %s', info.messageId);
    }
    smtpTransport.close();
});  

})

module.exports = routes;

Running npm command within Visual Studio Code

Open standard terminal ctrl+p and paste this command

npm i script-runner

Need to see this logs npm should be run outside of the node repl, in your normal shell. (Press Control-D to exit.)

(To exit, press ^C again or type .exit)

C:\DW\Examples\Ang.Crud>npm i script-runner npm WARN saveError ENOENT: no such file or directory, open 'C:\DW\Examples\Ang.Crud\package.json' npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN enoent ENOENT: no such file or directory, open 'C:\DW\Examples\Ang.Crud\package.json' npm WARN Ang.Crud No description npm WARN Ang.Crud No repository field. npm WARN Ang.Crud No README data npm WARN Ang.Crud No license field.

  • [email protected] added 7 packages from 5 contributors and audited 7 packages in 2.955s found 0 vulnerabilities

Usage: npm

where is one of: access, adduser, audit, bin, bugs, c, cache, ci, cit, completion, config, create, ddp, dedupe, deprecate, dist-tag, docs, doctor, edit, explore, get, help, help-search, hook, i, init, install, install-test, it, link, list, ln, login, logout, ls, outdated, owner, pack, ping, prefix, profile, prune, publish, rb, rebuild, repo, restart, root, run, run-script, s, se, search, set, shrinkwrap, star, stars, start, stop, t, team, test, token, tst, un, uninstall, unpublish, unstar, up, update, v, version, view, whoami

npm -h quick help on npm -l display full usage info npm help search for help on npm help npm involved overview

Specify configs in the ini-formatted file: C:\Users\fdc.npmrc or on the command line via: npm --key value Config info can be viewed via: npm help config

[email protected] C:\Program Files\nodejs\node_modules\npm

How to call a method in another class of the same package?

If it's a static method, you can call it by using the class name in place of an object.

Where are Docker images stored on the host machine?

Actually, Docker images are stored in two files as shown by following command

$ docker info

Data file: /var/lib/docker/devicemapper/devicemapper/data

Metadata file: /var/lib/docker/devicemapper/devicemapper/metadata

How can I write a regex which matches non greedy?

The ? operand makes match non-greedy. E.g. .* is greedy while .*? isn't. So you can use something like <img.*?> to match the whole tag. Or <img[^>]*>.

But remember that the whole set of HTML can't be actually parsed with regular expressions.

How to store an array into mysql?

You can use the php serialize function to store array in MySQL.

<?php

$array = array("Name"=>"Shubham","Age"=>"17","website"=>"http://mycodingtricks.com");

$string_array = serialize($array);

echo $string_array;

?>

It’s output will be :

a:3{s:4:"Name";s:7:"Shubham";s:3:"Age";s:2:"17";s:7:"website";s:25:"http://mycodingtricks.com";}

And then you can use the php unserialize function to decode the data.

I think you should visit this page on storing array in mysql.

Import SQL dump into PostgreSQL database

I had more than 100MB data, therefore I could not restore database using Pgadmin4.

I used simply postgres client, and write below command.

postgres@khan:/$ pg_restore -d database_name /home/khan/Downloads/dump.sql

It worked fine and took few seconds.You can see below link for more information. https://www.postgresql.org/docs/8.1/app-pgrestore.html

Using Panel or PlaceHolder

A panel expands to a span (or a div), with it's content within it. A placeholder is just that, a placeholder that's replaced by whatever you put in it.

Repeat a string in JavaScript a number of times

/**  
 * Repeat a string `n`-times (recursive)
 * @param {String} s - The string you want to repeat.
 * @param {Number} n - The times to repeat the string.
 * @param {String} d - A delimiter between each string.
 */

var repeat = function (s, n, d) {
    return --n ? s + (d || "") + repeat(s, n, d) : "" + s;
};

var foo = "foo";
console.log(
    "%s\n%s\n%s\n%s",

    repeat(foo),        // "foo"
    repeat(foo, 2),     // "foofoo"
    repeat(foo, "2"),   // "foofoo"
    repeat(foo, 2, "-") // "foo-foo"
);

Centering controls within a form in .NET (Winforms)?

you can put all your controls to panel and then write a code to move your panel to center of your form.

panelMain.Location = 
    new Point(ClientSize.Width / 2 - panelMain.Size.Width / 2, 
              ClientSize.Height / 2 - panelMain.Size.Height / 2);

panelMain.Anchor = AnchorStyles.None;

How do I query for all dates greater than a certain date in SQL Server?

select *  
from dbo.March2010 A 
where A.Date >= Convert(datetime, '2010-04-01' )

In your query, 2010-4-01 is treated as a mathematical expression, so in essence it read

select *  
from dbo.March2010 A 
where A.Date >= 2005; 

(2010 minus 4 minus 1 is 2005 Converting it to a proper datetime, and using single quotes will fix this issue.)

Technically, the parser might allow you to get away with

select *  
from dbo.March2010 A 
where A.Date >= '2010-04-01'

it will do the conversion for you, but in my opinion it is less readable than explicitly converting to a DateTime for the maintenance programmer that will come after you.

File Upload In Angular?

Angular 2 provides good support for uploading files. No third party library is required.

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        /** In Angular 5, including the header Content-Type can invalidate your request */
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        this.http.post(`${this.apiEndPoint}`, formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)
            )
    }
}

using @angular/core": "~2.0.0" and @angular/http: "~2.0.0"

Reading a single char in Java

You can either scan an entire line:

Scanner s = new Scanner(System.in);
String str = s.nextLine();

Or you can read a single char, given you know what encoding you're dealing with:

char c = (char) System.in.read();

SQL Delete Records within a specific Range

DELETE FROM table_name 
WHERE id BETWEEN 79 AND 296;

JPG vs. JPEG image formats

There's no difference between the file extensions, and they are used interchangeably. I guess the 3-letter version stems from the DOS era...

However, there are different "flavors" of JPEG files. Most notably the JFIF standard and the EXIF standard. Most often these just use .jpg or .jpeg as file extensions, JFIF sometimes uses .jif or .jfif.

How to change font size on part of the page in LaTeX?

To add exact fontsize you can use following. Worked for me since in my case predefined ranges (Large, tiny) are not match with the font size required to me.

\fontsize{10}{12}\selectfont This is the text you need to be in 10px

More info: https://tug.org/TUGboat/tb33-3/tb105thurnherr.pdf

Add a "sort" to a =QUERY statement in Google Spreadsheets

You can use ORDER BY clause to sort data rows by values in columns. Something like

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C, D")

If you’d like to order by some columns descending, others ascending, you can add desc/asc, ie:

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C desc, D")

Random String Generator Returning Same String

I found this to be more helpfull, since it is an extention, and it allows you to select the source of your code.

static string
    numbers = "0123456789",
    letters = "abcdefghijklmnopqrstvwxyz",
    lettersUp = letters.ToUpper(),
    codeAll = numbers + letters + lettersUp;

static Random m_rand = new Random();

public static string GenerateCode(this int size)
{
    return size.GenerateCode(CodeGeneratorType.All);
}

public static string GenerateCode(this int size, CodeGeneratorType type)
{
    string source;

    if (type == CodeGeneratorType.All)
    {
        source = codeAll;
    }
    else
    {
        StringBuilder sourceBuilder = new StringBuilder();
        if ((type & CodeGeneratorType.Letters) == CodeGeneratorType.Numbers)
            sourceBuilder.Append(numbers);
        if ((type & CodeGeneratorType.Letters) == CodeGeneratorType.Letters)
            sourceBuilder.Append(letters);
        if ((type & CodeGeneratorType.Letters) == CodeGeneratorType.LettersUpperCase)
            sourceBuilder.Append(lettersUp);

        source = sourceBuilder.ToString();
    }

    return size.GenerateCode(source);
}

public static string GenerateCode(this int size, string source)
{
    StringBuilder code = new StringBuilder();
    int maxIndex = source.Length-1;
    for (int i = 0; i < size; i++)
    {

        code.Append(source[Convert.ToInt32(Math.Round(m_rand.NextDouble() * maxIndex))]);
    }

    return code.ToString();
}

public enum CodeGeneratorType { Numbers = 1, Letters = 2, LettersUpperCase = 4, All = 16 };

Hope this helps.

How to concatenate two numbers in javascript?

Use "" + 5 + 6 to force it to strings. This works with numerical variables too:

_x000D_
_x000D_
var a = 5;_x000D_
var b = 6;_x000D_
console.log("" + a + b);
_x000D_
_x000D_
_x000D_

How to open .SQLite files

SQLite is database engine, .sqlite or .db should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.

There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index

Create a dictionary with list comprehension

Python version >= 2.7, do the below:

d = {i: True for i in [1,2,3]}

Python version < 2.7(RIP, 3 July 2010 - 31 December 2019), do the below:

d = dict((i,True) for i in [1,2,3])

How to get all elements which name starts with some string?

HTML DOM querySelectorAll() method seems apt here.

W3School Link given here

Syntax (As given in W3School)

document.querySelectorAll(CSS selectors)

So the answer.

document.querySelectorAll("[name^=q1_]")

Fiddle

Edit:

Considering FLX's suggestion adding link to MDN here

How to convert all tables in database to one collation?

Taking the answer from @Petr Stastny a step further by adding a password variable. I'd prefer if it actually took it in like a regular password rather than as an argument, but it's working for what I needed.

#!/bin/bash

# mycollate.sh <database> <password> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables

DB="$1"
PW="$2"
CHARSET="$3"
COLL="$4"

[ -n "$DB" ] || exit 1
[ -n "$PW" ]
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_bin"

PW="--password=""$PW"

echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql -u root "$PW"

echo "USE $DB; SHOW TABLES;" | mysql -s "$PW" | (
    while read TABLE; do
        echo $DB.$TABLE
        echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql "$PW" $DB
    done
)

PW="pleaseEmptyMeNow"

Enum "Inheritance"

You can achieve what you want with classes:

public class Base
{
    public const int A = 1;
    public const int B = 2;
    public const int C = 3;
}
public class Consume : Base
{
    public const int D = 4;
    public const int E = 5;
}

Now you can use these classes similar as when they were enums:

int i = Consume.B;

Update (after your update of the question):

If you assign the same int values to the constants as defined in the existing enum, then you can cast between the enum and the constants, e.g:

public enum SomeEnum // this is the existing enum (from WSDL)
{
    A = 1,
    B = 2,
    ...
}
public class Base
{
    public const int A = (int)SomeEnum.A;
    //...
}
public class Consume : Base
{
    public const int D = 4;
    public const int E = 5;
}

// where you have to use the enum, use a cast:
SomeEnum e = (SomeEnum)Consume.B;

What are the differences between Pandas and NumPy+SciPy in Python?

Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.

Use jQuery to get the file input's selected filename without the path

Get the first file from the control and then get the name of the file, it will ignore the file path on Chrome, and also will make correction of path for IE browsers. On saving the file, you have to use System.io.Path.GetFileName method to get the file name only for IE browsers

var fileUpload    = $("#ContentPlaceHolder1_FileUpload_mediaFile").get(0); 
var files         =  fileUpload.files; 
var mediafilename = ""; 

for (var i = 0; i < files.length; i++) { 
  mediafilename = files[i].name; 
} 

Get index of selected option with jQuery

You can use the .prop(propertyName) function to get a property from the first element in the jQuery object.

var savedIndex = $(selectElement).prop('selectedIndex');

This keeps your code within the jQuery realm and also avoids the other option of using a selector to find the selected option. You can then restore it using the overload:

$(selectElement).prop('selectedIndex', savedIndex);

What is ViewModel in MVC?

ViewModel is workaround that patches the conceptual clumsiness of the MVC framework. It represents the 4th layer in the 3-layer Model-View-Controller architecture. when Model (domain model) is not appropriate, too big (bigger than 2-3 fields) for the View, we create smaller ViewModel to pass it to the View.

Remove an item from a dictionary when its key is unknown

The dict.pop(key[, default]) method allows you to remove items when you know the key. It returns the value at the key if it removes the item otherwise it returns what is passed as default. See the docs.'

Example:

>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}

Removing App ID from Developer Connection

Does deleting the AppID do anything to disable versions of an Enterprise distributed app "in the wild" ??

If not, is there any way to kill off an Enterprise app before it's expiry?

how to display progress while loading a url to webview in android?

You will have to over ride onPageStarted and onPageFinished callbacks

mWebView.setWebViewClient(new WebViewClient() {

        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (progressBar!= null && progressBar.isShowing()) {
                progressBar.dismiss();
            }
            progressBar = ProgressDialog.show(WebViewActivity.this, "Application Name", "Loading...");
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);

            return true;
        }

        public void onPageFinished(WebView view, String url) {
            if (progressBar.isShowing()) {
                progressBar.dismiss();
            }
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            alertDialog.setTitle("Error");
            alertDialog.setMessage(description);
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            });
            alertDialog.show();
        }
    });

How do I print uint32_t and uint16_t variables value?

You need to include inttypes.h if you want all those nifty new format specifiers for the intN_t types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d or %u in case the sizes are different to what you think.

It includes stdint.h and extends it with quite a few other things, such as the macros that can be used for the printf/scanf family of calls. This is covered in section 7.8 of the ISO C99 standard.

For example, the following program:

#include <stdio.h>
#include <inttypes.h>
int main (void) {
    uint32_t a=1234;
    uint16_t b=5678;
    printf("%" PRIu32 "\n",a);
    printf("%" PRIu16 "\n",b);
    return 0;
}

outputs:

1234
5678

How to check if android checkbox is checked within its onClick method (declared in XML)?

@BindView(R.id.checkbox_id) // if you are using Butterknife
CheckBox yourCheckBox;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity); 
    yourCheckBox = (CheckBox)findViewById(R.id.checkbox_id);// If your are not using Butterknife (the traditional way)

    yourCheckBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            yourObject.setYourProperty(yourCheckBox.isChecked()); //yourCheckBox.isChecked() is the method to know if the checkBox is checked
            Log.d(TAG, "onClick: yourCheckBox = " + yourObject.getYourProperty() );
        }
    });
}

Obviously you have to make your XML with the id of your checkbox :

<CheckBox
    android:id="@+id/checkbox_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your label"
    />

So, the method to know if the check box is checked is : (CheckBox) yourCheckBox.isChecked() it returns true if the check box is checked.

pip not working in Python Installation in Windows 10

Make sure the path to scripts folder for the python version is added to the path environment/system variable in order to use pip command directly without the whole path to pip.exe which is inside the scripts folder.

The scripts folder would be inside the python folder for the version that you are using, which by default would be inside c drive or in c:/program files or c:/program files (x86).

Then use commands as mentioned below. You may have to run cmd as administrator to perform these tasks. You can do it by right clicking on cmd icon and selecting run as administrator.

python -m pip install packagename
python -m pip uninstall packagename
python -m pip install --upgrade packagename

In case you have more than one version of python. You may replace python with py -versionnumber for example py -2 for python 2 or you may replace it with the path to the corresponding python.exe file. For example "c:\python27\python".

Get absolute path to workspace directory in Jenkins Pipeline plugin

Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.

Example

node('label'){
    // now you are on slave labeled with 'label'
    def workspace = WORKSPACE
    // ${workspace} will now contain an absolute path to job workspace on slave

    workspace = env.WORKSPACE
    // ${workspace} will still contain an absolute path to job workspace on slave

    // When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
    echo "Current workspace is ${env.WORKSPACE}"

    // the current Jenkins instances will support the short syntax, too:
    echo "Current workspace is $WORKSPACE"

}

Checking if an Android application is running in the background

I think this question should be more clear. When? Where? What is your specific situation you want to konw if your app is in background?

I just introduce my solution in my way.
I get this done by using the field "importance" of RunningAppProcessInfo class in every activity's onStop method in my app, which can be simply achieved by providing a BaseActivity for other activities to extend which implements the onStop method to check the value of "importance". Here is the code:

public static boolean isAppRunning(Context context) {
    ActivityManager activityManager = (ActivityManager) context
        .getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager
        .getRunningAppProcesses();
    for (RunningAppProcessInfo appProcess : appProcesses) {
        if (appProcess.processName.equals(context.getPackageName())) {
            if (appProcess.importance != RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE) {
                return true;
            } 
        }
    }
    return false;
}

Difference between TCP and UDP?

This sentence is a UDP joke, but I'm not sure that you'll get it. The below conversation is a TCP/IP joke:

A: Do you want to hear a TCP/IP joke?
B: Yes, I want to hear a TCP/IP joke.
A: Ok, are you ready to hear a TCP/IP joke?
B: Yes, I'm ready to hear a TCP/IP joke.
A: Well, here is the TCP/IP joke.
A: Did you receive a TCP/IP joke?
B: Yes, I **did** receive a TCP/IP joke.

How to dismiss a Twitter Bootstrap popover by clicking outside?

Bootstrap natively supports this:

JS Bin Demo

Specific markup required for dismiss-on-next-click

For proper cross-browser and cross-platform behavior, you must use the <a> tag, not the <button> tag, and you also must include the role="button" and tabindex attributes.

Letsencrypt add domain to existing certificate

I was able to setup a SSL certificated for a domain AND multiple subdomains by using using --cert-name combined with --expand options.

See official certbot-auto documentation at https://certbot.eff.org/docs/using.html

Example:

certbot-auto certonly --cert-name mydomain.com.br \
--renew-by-default -a webroot -n --expand \
--webroot-path=/usr/share/nginx/html \
-d mydomain.com.br \
-d www.mydomain.com.br \
-d aaa1.com.br \
-d aaa2.com.br \
-d aaa3.com.br

How to convert CSV file to multiline JSON?

You can use Pandas DataFrame to achieve this, with the following Example:

import pandas as pd
csv_file = pd.DataFrame(pd.read_csv("path/to/file.csv", sep = ",", header = 0, index_col = False))
csv_file.to_json("/path/to/new/file.json", orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)

Why do I have ORA-00904 even when the column is present?

Its due to mismatch between column name defined in entity and the column name of table (in SQL db )

java.sql.SQLException: ORA-00904: "table_name"."column_name": invalid identifier e.g.java.sql.SQLException: ORA-00904: "STUDENT"."NAME": invalid identifier

issue can be like in Student.java(entity file) 
You have mentioned column name as "NAME" only.
But in STUDENT table ,column name is lets say "NMAE"

Do I use <img>, <object>, or <embed> for SVG files?

In most circumstances, I recommend using the <object> tag to display SVG images. It feels a little unnatural, but it's the most reliable method if you want to provide dynamic effects.

For images without interaction, the <img> tag or a CSS background can be used.

Inline SVGs or iframes are possible options for some projects, but it's best to avoid <embed>

But if you want to play with SVG stuff like

  • Changing colors
  • Resize path
  • rotate svg

Go with the embedded one

<svg>
    <g> 
        <path> </path>
    </g>
</svg>

Which version of C# am I using

Thanks to @fortesl and this answer

I'm using VS 2019 and it doesn't easily tell you the C# version you are using. I'm working with .Net Core 3.0, and VS 2019 using C# 8 in that environment. But "csc -langversion:?" makes this clear:

D:\>csc -langversion:?
Supported language versions:
default
1
2
3
4
5
6
7.0
7.1
7.2
7.3
8.0 (default)
latestmajor
preview
latest

Not sure what csc -version is identifying:

D:\>csc --version
Microsoft (R) Visual C# Compiler version 3.4.0-beta1-19462-14 (2f21c63b)
Copyright (C) Microsoft Corporation. All rights reserved.

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

Unable to allocate array with shape and data type

Sometimes, this error pops up because of the kernel has reached its limit. Try to restart the kernel redo the necessary steps.

Java Ordered Map

The SortedMap interface (with the implementation TreeMap) should be your friend.

The interface has the methods:

  • keySet() which returns a set of the keys in ascending order
  • values() which returns a collection of all values in the ascending order of the corresponding keys

So this interface fulfills exactly your requirements. However, the keys must have a meaningful order. Otherwise you can used the LinkedHashMap where the order is determined by the insertion order.

SQL Server: Extract Table Meta-Data (description, fields and their data types)

I just finished a .net library with a few useful queries that return strongly typed C# objects for code gen/ t4 templates.

nuget SqlMeta

Project Site

github source

/// <summary>
    ///     Get All Table Names
    /// </summary>
    /// <returns></returns>
    public List<string> GetTableNames()
    {
        var sql = @"SELECT name
                    FROM dbo.sysobjects
                    WHERE xtype = 'U' 
                    AND name <> 'sysdiagrams'
                    order by name asc";

        return databaseWrapper.Call(connection => connection.Query<string>(
            sql: sql))
            .ToList();
    }

    /// <summary>
    ///     Get table info by schema and table or null for all
    /// </summary>
    /// <param name="schema"></param>
    /// <param name="table"></param>
    /// <returns></returns>
    public List<SqlTableInfo> GetTableInfo(string schema = null, string table = null)
    {
        var result = new List<SqlTableInfo>();

        var sql = @"SELECT
                    c.TABLE_CATALOG AS [TableCatalog]
                ,   c.TABLE_SCHEMA AS [Schema]
                ,   c.TABLE_NAME AS [TableName]
                ,   c.COLUMN_NAME AS [ColumnName]
                ,   c.ORDINAL_POSITION AS [OrdinalPosition]
                ,   c.COLUMN_DEFAULT AS [ColumnDefault]
                ,   c.IS_NULLABLE AS [Nullable]
                ,   c.DATA_TYPE AS [DataType]
                ,   c.CHARACTER_MAXIMUM_LENGTH AS [CharacterMaxLength]
                ,   c.CHARACTER_OCTET_LENGTH AS [CharacterOctetLenth]
                ,   c.NUMERIC_PRECISION AS [NumericPrecision]
                ,   c.NUMERIC_PRECISION_RADIX AS [NumericPrecisionRadix]
                ,   c.NUMERIC_SCALE AS [NumericScale]
                ,   c.DATETIME_PRECISION AS [DatTimePrecision]
                ,   c.CHARACTER_SET_CATALOG AS [CharacterSetCatalog]
                ,   c.CHARACTER_SET_SCHEMA AS [CharacterSetSchema]
                ,   c.CHARACTER_SET_NAME AS [CharacterSetName]
                ,   c.COLLATION_CATALOG AS [CollationCatalog]
                ,   c.COLLATION_SCHEMA AS [CollationSchema]
                ,   c.COLLATION_NAME AS [CollationName]
                ,   c.DOMAIN_CATALOG AS [DomainCatalog]
                ,   c.DOMAIN_SCHEMA AS [DomainSchema]
                ,   c.DOMAIN_NAME AS [DomainName]
                ,   IsPrimaryKey = CONVERT(BIT, (SELECT
                            COUNT(*)
                        FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
                            ,   INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cu
                        WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
                        AND tc.CONSTRAINT_NAME = cu.CONSTRAINT_NAME
                        AND tc.TABLE_NAME = c.TABLE_NAME
                        AND cu.TABLE_SCHEMA = c.TABLE_SCHEMA
                        AND cu.COLUMN_NAME = c.COLUMN_NAME)
                    )
                ,   IsIdentity = CONVERT(BIT, (SELECT
                            COUNT(*)
                        FROM sys.objects obj
                        INNER JOIN sys.COLUMNS col
                            ON obj.object_id = col.object_id
                        WHERE obj.type = 'U'
                        AND obj.Name = c.TABLE_NAME
                        AND col.Name = c.COLUMN_NAME
                        AND col.is_identity = 1)
                    )
                FROM INFORMATION_SCHEMA.COLUMNS c
                WHERE (@Schema IS NULL
                        OR c.TABLE_SCHEMA = @Schema)
                    AND (@TableName IS NULL
                        OR c.TABLE_NAME = @TableName)
                    ";

        var columns = databaseWrapper.Call(connection => connection.Query<SqlColumnInfo>(
            sql: sql,
            param: new { Schema = schema, TableName = table },
            commandType: CommandType.Text)
            .ToList());

        var refs = this.GetReferentialConstraints(table: table, schema: schema);

        foreach (var tableName in columns.Select(info => info.TableName).Distinct())
        {
            var tableColumns = columns.Where(info => info.TableName == tableName).ToList();
            var children = refs.Where(c => c.UniqueTableName == tableName).ToList();
            var parents = refs.Where(c => c.TableName == tableName).ToList();
            result.Add(new SqlTableInfo
            {
                TableName = tableName,
                Columns = tableColumns,
                ChildConstraints = children,
                ParentConstraints = parents
            });

        }

        return result;
    }

    public List<SqlReferentialConstraint> GetReferentialConstraints(string table = null, string schema = null)
    {
        //https://technet.microsoft.com/en-us/library/aa175805%28v=sql.80%29.aspx
        //https://technet.microsoft.com/en-us/library/Aa175805.312ron1%28l=en-us,v=sql.80%29.jpg
        //https://msdn.microsoft.com/en-us/library/ms186778.aspx

        var sql = @"
                    SELECT
                        KCU1.CONSTRAINT_NAME AS [ConstraintName]
                    ,   KCU1.TABLE_NAME AS [TableName]
                    ,   KCU1.COLUMN_NAME AS [ColumnName]
                    ,   KCU2.CONSTRAINT_NAME AS [UniqueConstraintName]
                    ,   KCU2.TABLE_NAME AS [UniqueTableName]
                    ,   KCU2.COLUMN_NAME AS [UniqueColumnName]
                    ,   RC.MATCH_OPTION AS [MatchOption]
                    ,   RC.UPDATE_RULE AS [UpdateRule]
                    ,   RC.DELETE_RULE AS [DeleteRule]
                    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
                    LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU1 ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
                        AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
                        AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
                    LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU2 ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG
                        AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA
                        AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME
                    WHERE KCU1.ORDINAL_POSITION = KCU2.ORDINAL_POSITION
                            AND (@Table IS NULL
                                OR KCU1.TABLE_NAME = @Table
                                OR KCU2.TABLE_NAME = @Table)
                            AND (@Schema IS NULL
                                OR KCU1.TABLE_SCHEMA = @Schema
                                OR KCU2.TABLE_SCHEMA = @Schema)
                    ";

        return databaseWrapper.Call(connection => connection.Query<SqlReferentialConstraint>(
            sql: sql,
            param: new { Table = table, Schema = schema },
            commandType: CommandType.Text))
            .ToList();
    }

    /// <summary>
    ///     Get Primary Key Column by schema and table name
    /// </summary>
    /// <param name="schema"></param>
    /// <param name="tableName"></param>
    /// <returns></returns>
    public string GetPrimaryKeyColumnName(string schema, string tableName)
    {
        var sql = @"SELECT
                    B.COLUMN_NAME
                FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS A
                    ,   INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE B
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
                    AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
                    AND A.TABLE_NAME = @TableName
                    AND A.TABLE_SCHEMA = @Schema";

        return databaseWrapper.Call(connection => connection.Query<string>(
            sql: sql,
            param: new { TableName = tableName, Schema = schema },
            commandType: CommandType.Text))
            .SingleOrDefault();
    }

    /// <summary>
    ///     Get Identity Column by table name
    /// </summary>
    /// <param name="tableName"></param>
    /// <returns></returns>
    public string GetIdentityColumnName(string tableName)
    {
        var sql = @"SELECT
                    c.Name
                FROM sys.objects o
                INNER JOIN sys.columns c ON o.object_id = c.object_id
                WHERE o.type = 'U'
                    AND c.is_identity = 1
                    AND o.Name = @TableName";

        return databaseWrapper.Call(connection => connection.Query<string>(
            sql: sql,
            param: new { TableName = tableName },
            commandType: CommandType.Text))
            .SingleOrDefault();
    }

    /// <summary>
    ///     Get All Stored Procedures by schema
    /// </summary>
    /// <param name="schema"></param>
    /// <param name="procName"></param>
    /// <returns></returns>
    public List<SqlStoredProcedureInfo> GetStoredProcedureInfo(string schema = null, string procName = null)
    {
        var result = new List<SqlStoredProcedureInfo>();

        var sql = @"SELECT
                        SPECIFIC_NAME AS [Name]
                    ,   SPECIFIC_SCHEMA AS [Schema]
                    ,   Created AS [Created]
                    ,   LAST_ALTERED AS [LastAltered]
                    FROM INFORMATION_SCHEMA.ROUTINES
                    WHERE ROUTINE_TYPE = 'PROCEDURE'
                        AND (SPECIFIC_SCHEMA = @Schema
                            OR @Schema IS NULL)
                        AND (SPECIFIC_NAME = @ProcName
                            OR @ProcName IS NULL)
                        AND ((SPECIFIC_NAME NOT LIKE 'sp_%'
                                AND SPECIFIC_NAME NOT LIKE 'procUtils_GenerateClass'
                                AND (SPECIFIC_SCHEMA = @Schema
                                    OR @Schema IS NULL))
                            OR SPECIFIC_SCHEMA <> @Schema)";

        var sprocs = databaseWrapper.Call(connection => connection.Query<SqlStoredProcedureInfo>(
            sql: sql,
            param: new { Schema = schema, ProcName = procName },
            commandType: CommandType.Text).ToList());

        foreach (var s in sprocs)
        {
            s.Parameters = GetStoredProcedureInputParameters(sprocName: s.Name, schema: schema);
            s.ResultColumns = GetColumnInfoFromStoredProcResult(storedProcName: s.Name, schema: schema);
            result.Add(s);
        }

        return result;
    }

    /// <summary>
    ///     Get Column info from Stored procedure result set
    /// </summary>
    /// <param name="schema"></param>
    /// <param name="storedProcName"></param>
    /// <returns></returns>
    public List<DataColumn> GetColumnInfoFromStoredProcResult(string schema, string storedProcName)
    {
        //this one actually needs to use the dataset because it has the only accurate information about columns and if they can be null or not.
        var sb = new StringBuilder();
        if (!String.IsNullOrEmpty(schema))
        {
            sb.Append(String.Format("exec [{0}].[{1}] ", schema, storedProcName));
        }
        else
        {
            sb.Append(String.Format("exec [{0}] ", storedProcName));
        }

        var prms = GetStoredProcedureInputParameters(schema, storedProcName);

        var count = 1;
        foreach (var param in prms)
        {
            sb.Append(String.Format("{0}=null", param.Name));
            if (count < prms.Count)
            {
                sb.Append(", ");
            }
            count++;
        }

        var ds = new DataSet();
        using (var sqlConnection = (SqlConnection)databaseWrapper.GetOpenDbConnection())
        {
            using (var sqlAdapter = new SqlDataAdapter(sb.ToString(), sqlConnection))
            {
                if (sqlConnection.State != ConnectionState.Open) sqlConnection.Open();

                sqlAdapter.SelectCommand.ExecuteReader(CommandBehavior.SchemaOnly);

                sqlConnection.Close();

                sqlAdapter.FillSchema(ds, SchemaType.Source, "MyTable");
            }
        }

        var list = new List<DataColumn>();
        if (ds.Tables.Count > 0)
        {
            list = ds.Tables["MyTable"].Columns.Cast<DataColumn>().ToList();
        }

        return list;
    }

    /// <summary>
    ///     Get the input parameters for a stored procedure
    /// </summary>
    /// <param name="schema"></param>
    /// <param name="sprocName"></param>
    /// <returns></returns>
    public List<SqlParameterInfo> GetStoredProcedureInputParameters(string schema = null, string sprocName = null)
    {
        var sql = @"SELECT
                    SCHEMA_NAME(schema_id) AS [Schema]
                ,   P.Name AS Name
                ,   @ProcName AS ProcedureName
                ,   TYPE_NAME(P.user_type_id) AS [ParameterDataType]
                ,   P.max_length AS [MaxLength]
                ,   P.Precision AS [Precision]
                ,   P.Scale AS Scale
                ,   P.has_default_value AS HasDefaultValue
                ,   P.default_value AS DefaultValue
                ,   P.object_id AS ObjectId
                ,   P.parameter_id AS ParameterId
                ,   P.system_type_id AS SystemTypeId
                ,   P.user_type_id AS UserTypeId
                ,   P.is_output AS IsOutput
                ,   P.is_cursor_ref AS IsCursor
                ,   P.is_xml_document AS IsXmlDocument
                ,   P.xml_collection_id AS XmlCollectionId
                ,   P.is_readonly AS IsReadOnly
                FROM sys.objects AS SO
                INNER JOIN sys.parameters AS P ON SO.object_id = P.object_id
                WHERE SO.object_id IN (SELECT
                            object_id
                        FROM sys.objects
                        WHERE type IN ('P', 'FN'))
                    AND (SO.Name = @ProcName
                        OR @ProcName IS NULL)
                    AND (SCHEMA_NAME(schema_id) = @Schema
                        OR @Schema IS NULL)
                ORDER BY P.parameter_id ASC";

        var result = databaseWrapper.Call(connection => connection.Query<SqlParameterInfo>(
            sql: sql,
            param: new { Schema = schema, ProcName = sprocName },
            commandType: CommandType.Text))
            .ToList();

        return result;
    }

Foreign Key Metadata

Do I need to compile the header files in a C program?

Okay, let's understand the difference between active and passive code.

The active code is the implementation of functions, procedures, methods, i.e. the pieces of code that should be compiled to executable machine code. We store it in .c files and sure we need to compile it.

The passive code is not being execute itself, but it needed to explain the different modules how to communicate with each other. Usually, .h files contains only prototypes (function headers), structures.

An exception are macros, that formally can contain an active pieces, but you should understand that they are using at the very early stage of building (preprocessing) with simple substitution. At the compile time macros already are substituted to your .c file.

Another exception are C++ templates, that should be implemented in .h files. But here is the story similar to macros: they are substituted on the early stage (instantiation) and formally, each other instantiation is another type.

In conclusion, I think, if the modules formed properly, we should never compile the header files.

Change font-weight of FontAwesome icons?

.star-light::after {
    content: "\f005";
    font-family: "FontAwesome";
    font-size: 3.2rem;
    color: #fff;
    font-weight: 900;
    background-color: red;
}

Convert string to number and add one

Have you tried flip-flopping it a bit?

var newcurrentpageTemp = parseInt($(this).attr("id"));
newcurrentpageTemp++;
alert(newcurrentpageTemp));

Absolute Positioning & Text Alignment

The div doesn't take up all the available horizontal space when absolutely positioned. Explicitly setting the width to 100% will solve the problem:

HTML

<div id="my-div">I want to be centered</div>?

CSS

#my-div {
   position: absolute;
   bottom: 15px;
   text-align: center;
   width: 100%;
}

?

jquery save json data object in cookie

use JSON.stringify(userData) to coverty json object to string.

var dataStore = $.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));

and for getting back from cookie use JSON.parse()

var data=JSON.parse($.cookie("basket-data"))

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

How do I remove a CLOSE_WAIT socket connection

It is also worth noting that if your program spawns a new process, that process may inherit all your opened handles. Even after your own program closs, those inherited handles can still be alive via the orphaned child process. And they don't necessarily show up quite the same in netstat. But all the same, the socket will hang around in CLOSE_WAIT while this child process is alive.

I had a case where I was running ADB. ADB itself spawns a server process if its not already running. This inherited all my handles initially, but did not show up as owning any of them when I was investigating (the same was true for both macOS and Windows - not sure about Linux).

How do you add an image?

In order to add attributes, XSL wants

<xsl:element name="img">
     (attributes)
</xsl:element>

instead of just

<img>
     (attributes)
</img>

Although, yes, if you're just copying the element as-is, you don't need any of that.

MySql export schema without data

Dumping without using output.

mysqldump --no-data <database name> --result-file=schema.sql

What is the difference between baud rate and bit rate?

Serial Data Speed:

Data rate (bps) = 1/Tb Tb is the time duration of 1 bit If the bit duration is 2ms then data rate is 1/2x10-3 , which is about 500 bps.

Baud rate:

Baud rate is defined as no. of signalling elements(symbols) in a given unit of time (say 1 sec) or it means number of time signal changes its state.When the signal is binary then baud rate and bit rate are same.

Bit rate:- Bit rate is nothing but number of bits transmitted per second.For example if Bit rate is 1000 bps then 1000 bits are i.e. 0s or 1s transmitted per second.

There are few other terms similar to this (i.e serial speed, bit rate, baud rate, USB transfer rate),and i guess(?) the values that are printed on serial monitor relates to serial speed, baud rate and USB transfer rate. Bit rate isn't an another term, please correct me if i am wrong, because serial monitor prints some values at an interval of time and value is definitely a set of bits. so if one value is printed i can say no of bits present in the respective value which gets printed on serial monitor per unit time will be the bit rate.

bundle install fails with SSL certificate verification error

If you're using rails-assets

If you were using https://rails-assets.org/ to manage your assets, no answers will help you. Even converting to http won't help.

The simplest fix is using this source instead, http://insecure.rails-assets.org. This has been mentioned in their homepage.

When to use If-else if-else over switch statements and vice versa

If you are switching on the value of a single variable then I'd use a switch every time, it's what the construct was made for.

Otherwise, stick with multiple if-else statements.

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

I had in PATH:

C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Java\jdk1.8.0_92\bin;<others omitted>

I removed:

C:\ProgramData\Oracle\Java\javapath;

and that fixed the issue for me. java -version now gives details about the Java version, etc.

Remove characters from a string

You can use replace function.

str.replace(regexp|substr, newSubstr|function)

How does createOrReplaceTempView work in Spark?

createOrReplaceTempView creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a hive table in Spark SQL. It does not persist to memory unless you cache the dataset that underpins the view.

scala> val s = Seq(1,2,3).toDF("num")
s: org.apache.spark.sql.DataFrame = [num: int]

scala> s.createOrReplaceTempView("nums")

scala> spark.table("nums")
res22: org.apache.spark.sql.DataFrame = [num: int]

scala> spark.table("nums").cache
res23: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [num: int]

scala> spark.table("nums").count
res24: Long = 3

The data is cached fully only after the .count call. Here's proof it's been cached:

Cached nums temp view/table

Related SO: spark createOrReplaceTempView vs createGlobalTempView

Relevant quote (comparing to persistent table): "Unlike the createOrReplaceTempView command, saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the Hive metastore." from https://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables

Note : createOrReplaceTempView was formerly registerTempTable

Select method of Range class failed via VBA

This is how you get around that in an easy non-complicated way.
Instead of using sheet(x).range use Activesheet.range("range").select

How do I Set Background image in Flutter?

You can use Stack to make the image stretch to the full screen.

Stack(
        children: <Widget>
        [
          Positioned.fill(  //
            child: Image(
              image: AssetImage('assets/placeholder.png'),
              fit : BoxFit.fill,
           ),
          ), 
          ...... // other children widgets of Stack
          ..........
          .............
         ]
 );

Note: Optionally if are using a Scaffold, you can put the Stack inside the Scaffold with or without AppBar according to your needs.

What is a "slug" in Django?

The term 'slug' comes from the world of newspaper production.

It's an informal name given to a story during the production process. As the story winds its path from the beat reporter (assuming these even exist any more?) through to editor through to the "printing presses", this is the name it is referenced by, e.g., "Have you fixed those errors in the 'kate-and-william' story?".

Some systems (such as Django) use the slug as part of the URL to locate the story, an example being www.mysite.com/archives/kate-and-william.

Even Stack Overflow itself does this, with the GEB-ish(a) self-referential https://stackoverflow.com/questions/427102/what-is-a-slug-in-django/427201#427201, although you can replace the slug with blahblah and it will still find it okay.

It may even date back earlier than that, since screenplays had "slug lines" at the start of each scene, which basically sets the background for that scene (where, when, and so on). It's very similar in that it's a precis or preamble of what follows.

On a Linotype machine, a slug was a single line piece of metal which was created from the individual letter forms. By making a single slug for the whole line, this greatly improved on the old character-by-character compositing.

Although the following is pure conjecture, an early meaning of slug was for a counterfeit coin (which would have to be pressed somehow). I could envisage that usage being transformed to the printing term (since the slug had to be pressed using the original characters) and from there, changing from the 'piece of metal' definition to the 'story summary' definition. From there, it's a short step from proper printing to the online world.


(a) "Godel Escher, Bach", by one Douglas Hofstadter, which I (at least) consider one of the great modern intellectual works. You should also check out his other work, "Metamagical Themas".

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

Most probably you may have not installed maven correctly. use this to download maven. Download the latest (Binary tar.gz) file.It worked for me.

How to convert AAR to JAR

For those, who want to do it automatically, I have wrote a little two-lines bash script which does next two things:

  1. Looks for all *.aar files and extracts classes.jar from them
  2. Renames extracted classes.jar to be like the aar but with a new extension

    find . -name '*.aar' -exec sh -c 'unzip -d `dirname {}` {} classes.jar' \;
    find . -name '*.aar' -exec sh -c 'mv `dirname {}`/classes.jar `echo {} | sed s/aar/jar/g`' \;
    

That's it!

Downloading and unzipping a .zip file without writing to disk

Vishal's example, however great, confuses when it comes to the file name, and I do not see the merit of redefing 'zipfile'.

Here is my example that downloads a zip that contains some files, one of which is a csv file that I subsequently read into a pandas DataFrame:

from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen
import pandas

url = urlopen("https://www.federalreserve.gov/apps/mdrm/pdf/MDRM.zip")
zf = ZipFile(StringIO(url.read()))
for item in zf.namelist():
    print("File in zip: "+  item)
# find the first matching csv file in the zip:
match = [s for s in zf.namelist() if ".csv" in s][0]
# the first line of the file contains a string - that line shall de ignored, hence skiprows
df = pandas.read_csv(zf.open(match), low_memory=False, skiprows=[0])

(Note, I use Python 2.7.13)

This is the exact solution that worked for me. I just tweaked it a little bit for Python 3 version by removing StringIO and adding IO library

Python 3 Version

from io import BytesIO
from zipfile import ZipFile
import pandas
import requests

url = "https://www.nseindia.com/content/indices/mcwb_jun19.zip"
content = requests.get(url)
zf = ZipFile(BytesIO(content.content))

for item in zf.namelist():
    print("File in zip: "+  item)

# find the first matching csv file in the zip:
match = [s for s in zf.namelist() if ".csv" in s][0]
# the first line of the file contains a string - that line shall de     ignored, hence skiprows
df = pandas.read_csv(zf.open(match), low_memory=False, skiprows=[0])

how to use python2.7 pip instead of default pip

An alternative is to call the pip module by using python2.7, as below:

python2.7 -m pip <commands>

For example, you could run python2.7 -m pip install <package> to install your favorite python modules. Here is a reference: https://stackoverflow.com/a/50017310/4256346.

In case the pip module has not yet been installed for this version of python, you can run the following:

python2.7 -m ensurepip

Running this command will "bootstrap the pip installer". Note that running this may require administrative privileges (i.e. sudo). Here is a reference: https://docs.python.org/2.7/library/ensurepip.html and another reference https://stackoverflow.com/a/46631019/4256346.

Error QApplication: no such file or directory

For QT 5

Step1: .pro (in pro file, add these 2 lines)

QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

Step2: In main.cpp replace code:

#include <QtGui/QApplication> 

with:

#include <QApplication>

How to run vi on docker container?

If you need to change a file just once. You should prefer making the change locally and build a new docker image with this file.

Say in a docker image, you need to change a file named myFile.xml under /path/to/docker/image/. So, you need to do.

  1. Copy myFile.xml in your local filesystem and make necessary changes.
  2. Create a file named 'Dockerfile' with the following content-
FROM docker-repo:tag
ADD myFile.xml /path/to/docker/image/

Then build your own docker image with docker build -t docker-repo:v-x.x.x .

Then use your newly build docker image.

Block direct access to a file over http but allow php script access

The safest way is to put the files you want kept to yourself outside of the web root directory, like Damien suggested. This works because the web server follows local file system privileges, not its own privileges.

However, there are a lot of hosting companies that only give you access to the web root. To still prevent HTTP requests to the files, put them into a directory by themselves with a .htaccess file that blocks all communication. For example,

Order deny,allow
Deny from all

Your web server, and therefore your server side language, will still be able to read them because the directory's local permissions allow the web server to read and execute the files.

Remove white space above and below large text in an inline-block element

If its text that has to scale proportionally to the screenwidth, you can also use the font as an svg, you can just export it from something like illustrator. I had to do this in my case, because I wanted to align the top of left and right border with the font's top |TEXT| . Using line-height, the text will jump up and down when scaling the window.

Using NSLog for debugging

Use NSLog() like this:

NSLog(@"The code runs through here!");

Or like this - with placeholders:

float aFloat = 5.34245;
NSLog(@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat);

In NSLog() you can use it like + (id)stringWithFormat:(NSString *)format, ...

float aFloat = 5.34245;
NSString *aString = [NSString stringWithFormat:@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat];

You can add other placeholders, too:

float aFloat = 5.34245;
int aInteger = 3;
NSString *aString = @"A string";
NSLog(@"This is my float: %f \n\nAnd here is my integer: %i \n\nAnd finally my string: %@", aFloat, aInteger, aString);

Declaring a boolean in JavaScript using just var

The variable will become what ever type you assign it. Initially it is undefined. If you assign it 'true' it will become a string, if you assign it true it will become a boolean, if you assign it 1 it will become a number. Subsequent assignments may change the type of the variable later.

How to convert a Bitmap to Drawable in android?

Try this it converts a Bitmap type image to Drawable

Drawable d = new BitmapDrawable(getResources(), bitmap);

Getting a map() to return a list in Python 3.x

list(map(chr, [66, 53, 0, 94]))

map(func, *iterables) --> map object Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

"Make an iterator"

means it will return an iterator.

"that computes the function using arguments from each of the iterables"

means that the next() function of the iterator will take one value of each iterables and pass each of them to one positional parameter of the function.

So you get an iterator from the map() funtion and jsut pass it to the list() builtin function or use list comprehensions.

Remove all non-"word characters" from a String in Java, leaving accented characters?

You might want to remove the accents and diacritic signs first, then on each character position check if the "simplified" string is an ascii letter - if it is, the original position shall contain word characters, if not, it can be removed.

Vim: How to insert in visual block mode?

  1. press ctrl and v // start select
  2. press shift and i // then type in any text
  3. press esc esc // press esc twice

Save modifications in place with awk

following won't work

echo $(awk '{awk code}' file) > file

this should work

echo "$(awk '{awk code}' file)" > file

How do I iterate through table rows and cells in JavaScript?

Using a single for loop:

var table = document.getElementById('tableID');  
var count = table.rows.length;  
for(var i=0; i<count; i++) {    
    console.log(table.rows[i]);    
}

How to append to a file in Node?

fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')
fs.writeSync(fd, 'contents to append')
fs.closeSync(fd)

Writing Unicode text to a text file?

How to print unicode characters into a file:

Save this to file: foo.py:

#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys 
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')

Run it and pipe output to file:

python foo.py > tmp.txt

Open tmp.txt and look inside, you see this:

el@apollo:~$ cat tmp.txt 
e with obfuscation: é

Thus you have saved unicode e with a obfuscation mark on it to a file.

find first sequence item that matches a criterion

a=[100,200,300,400,500]
def search(b):
 try:
  k=a.index(b)
  return a[k] 
 except ValueError:
    return 'not found'
print(search(500))

it'll return the object if found else it'll return "not found"

How to clear all input fields in bootstrap modal when clicking data-dismiss button?

enclose your modal body inside a form with an id="myform"

and then

 $("#activatesimModal").on("hidden.bs.modal",function(){
        myform.reset();
});

should do the trick

Setting a property by reflection with a string value

Using Convert.ChangeType and getting the type to convert from the PropertyInfo.PropertyType.

propertyInfo.SetValue( ship,
                       Convert.ChangeType( value, propertyInfo.PropertyType ),
                       null );

Fit background image to div

background-position-x: center;
background-position-y: center;

Render HTML in React Native

I found this component. https://github.com/jsdf/react-native-htmlview

This component takes HTML content and renders it as native views, with customisable style and handling of links, etc.

int object is not iterable?

You can try to change for i in inp: into for i in range(1,inp): Iteration doesn't work with a single int. Instead, you need provide a range for it to run.

.NET Excel Library that can read/write .xls files

I'd recommend NPOI. NPOI is FREE and works exclusively with .XLS files. It has helped me a lot.

Detail: you don't need to have Microsoft Office installed on your machine to work with .XLS files if you use NPOI.

Check these blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C#

NPOI with Excel Table and dynamic Chart

[UPDATE]

NPOI 2.0 added support for XLSX and DOCX.

You can read more about it here:

NPOI 2.0 series of posts scheduled

Formatting code snippets for blogging on Blogger

I rolled my own in F# (see this question), but it still isn't perfect (I just do regexps, so I don't recognise classes or method names etc.).

Basically, from what I can tell, the blogger editor will sometimes eat your angle brackets if you switch between Compose and HTML mode. So you have to paste into HTML mode then save directly. (I may be wrong on this, just tried now and it seems to work - browser dependent?)

It's horrible when you have generics!

URL rewriting with PHP

If you only want to change the route for picture.php then adding rewrite rule in .htaccess will serve your needs, but, if you want the URL rewriting as in Wordpress then PHP is the way. Here is simple example to begin with.

Folder structure

There are two files that are needed in the root folder, .htaccess and index.php, and it would be good to place the rest of the .php files in separate folder, like inc/.

root/
  inc/
  .htaccess
  index.php

.htaccess

RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

This file has four directives:

  1. RewriteEngine - enable the rewriting engine
  2. RewriteRule - deny access to all files in inc/ folder, redirect any call to that folder to index.php
  3. RewriteCond - allow direct access to all other files ( like images, css or scripts )
  4. RewriteRule - redirect anything else to index.php

index.php

Because everything is now redirected to index.php, there will be determined if the url is correct, all parameters are present, and if the type of parameters are correct.

To test the url we need to have a set of rules, and the best tool for that is a regular expression. By using regular expressions we will kill two flies with one blow. Url, to pass this test must have all the required parameters that are tested on allowed characters. Here are some examples of rules.

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'
);

Next is to prepare the request uri.

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

Now that we have the request uri, the final step is to test uri on regular expression rules.

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        /* now you know the action and parameters so you can 
         * include appropriate template file ( or proceed in some other way )
         */
    }
}

Successful match will, since we use named subpatterns in regex, fill the $params array almost the same as PHP fills the $_GET array. However, when using a dynamic url, $_GET array is populated without any checks of the parameters.

    /picture/some+text/51

    Array
    (
        [0] => /picture/some text/51
        [text] => some text
        [1] => some text
        [id] => 51
        [2] => 51
    )

    picture.php?text=some+text&id=51

    Array
    (
        [text] => some text
        [id] => 51
    )

These few lines of code and a basic knowing of regular expressions is enough to start building a solid routing system.

Complete source

define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'
);

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        /* now you know the action and parameters so you can 
         * include appropriate template file ( or proceed in some other way )
         */
        include( INCLUDE_DIR . $action . '.php' );

        // exit to avoid the 404 message 
        exit();
    }
}

// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );

Center align with table-cell

This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.

DEMO

here's the gist of the demo

.container{

  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;

}

html

<div class="container">
  <div class='content'> //you can size this anyway you want
    put anything you want here,
  </div>
</div>

enter image description here

What is the best way to repeatedly execute a function every x seconds?

e.g., Display current local time

import datetime
import glib
import logger

def get_local_time():
    current_time = datetime.datetime.now().strftime("%H:%M")
    logger.info("get_local_time(): %s",current_time)
    return str(current_time)

def display_local_time():
    logger.info("Current time is: %s", get_local_time())
    return True

# call every minute
glib.timeout_add(60*1000, display_local_time)

How to use java.net.URLConnection to fire and handle HTTP requests?

You can also use JdkRequest from jcabi-http (I'm a developer), which does all this work for you, decorating HttpURLConnection, firing HTTP requests and parsing responses, for example:

String html = new JdkRequest("http://www.google.com").fetch().body();

Check this blog post for more info: http://www.yegor256.com/2014/04/11/jcabi-http-intro.html

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

For me worked this one:

ALTER TABLE tablename MODIFY fieldname VARCHAR(128) NOT NULL;

IntelliJ: Never use wildcard imports

This applies to "IntelliJ IDEA-2019.2.4" on Mac.

  1. Navigate to "IntelliJ IDEA->Preferences->Editor->Code Style->Kotlin".
  2. The "Packages to use Import with '' section on the screen will list "import java.util."

Before

  1. Click anywhere in that box and clear that entry.
  2. Hit Apply and OK.

After

java get file size efficiently

All the test cases in this post are flawed as they access the same file for each method tested. So disk caching kicks in which tests 2 and 3 benefit from. To prove my point I took test case provided by GHAD and changed the order of enumeration and below are the results.

Looking at result I think File.length() is the winner really.

Order of test is the order of output. You can even see the time taken on my machine varied between executions but File.Length() when not first, and incurring first disk access won.

---
LENGTH sum: 1163351, per Iteration: 4653.404
CHANNEL sum: 1094598, per Iteration: 4378.392
URL sum: 739691, per Iteration: 2958.764

---
CHANNEL sum: 845804, per Iteration: 3383.216
URL sum: 531334, per Iteration: 2125.336
LENGTH sum: 318413, per Iteration: 1273.652

--- 
URL sum: 137368, per Iteration: 549.472
LENGTH sum: 18677, per Iteration: 74.708
CHANNEL sum: 142125, per Iteration: 568.5

string encoding and decoding?

That's because your input string can’t be converted according to the encoding rules (strict by default).

I don't know, but I always encoded using directly unicode() constructor, at least that's the ways at the official documentation:

unicode(your_str, errors="ignore")

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

I've seen this error occur due to 'comments' in the bundle generated by webpack. Using 'pathinfo'= true in webpack.config.js can cause this issue:

webpack.config.js

module.exports = {
  output: {
    pathinfo: true,
  }
}

'pathinfo' defaults to true in development and false in production mode. https://webpack.js.org/configuration/output/#outputpathinfo Try setting this value to false to resolve the issue.

This can also happen if you are not using a plugin to strip the comments from the build output. Try using UglifyJs (https://www.npmjs.com/package/uglifyjs-webpack-plugin/v/1.3.0):

webpack.config.js

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

module.exports = {
  ...
  optimization: {
    minimizer: [new UglifyJsPlugin(
      new UglifyJsPlugin({
        uglifyOptions: {
          output: {
            comments: false
          }
        }
      }),
    )],
  }
}

Select the top N values by group

There are at least 4 ways to do this thing, however,each has some difference. We using u_id to group and using lift value to order/sort

1 dplyr traditional way

library(dplyr)
top10_final_subset1 = final_subset %>% arrange(desc(lift)) %>% group_by(u_id) %>% slice(1:10)

and if you switch the order of arrange(desc(lift)) and group_by(u_id) the result is essential the same.And if there is tie for equal lift value,it will slice to make sure each group has no more than 10 values, if you only have 5 lift value in the group, it will only gives you 5 results for that group.

2 dplyr topN way

library(dplyr)
top10_final_subset2 = final_subset %>% group_by(u_id) %>% top_n(10,lift)

this one if you have tie in lift value, say 15 same lift for the same u_id, you will got all 15 observations

3 data.table tail way

library(data.table)
final_subset = data.table(final_subset,key = "lift")
top10_final_subset3 = final_subset[,tail(.SD,10),,by = c("u_id")]

It has the same row numbers as the first way, however, there are some rows are different, I guess they are using diff random algorithm dealing with tie.

4 data.table .SD way

library(data.table)
top10_final_subset4 = final_subset[,.SD[order(lift,decreasing = TRUE),][1:10],by = "u_id"]

This way is the most "uniform" way,if in a group there are only 5 observation it will repeat value to make it to 10 observations and if there are ties it will still slice and only hold for 10 observations.

pip3: command not found but python3-pip is already installed

I had a similar issue. In my case, I had to uninstall and then reinstall pip3:

sudo apt-get remove python3-pip
sudo apt-get install python3-pip

Parse json string using JSON.NET

If your keys are dynamic I would suggest deserializing directly into a DataTable:

    class SampleData
    {
        [JsonProperty(PropertyName = "items")]
        public System.Data.DataTable Items { get; set; }
    }

    public void DerializeTable()
    {
        const string json = @"{items:["
            + @"{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
            + @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
            + @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]}";
        var sampleData = JsonConvert.DeserializeObject<SampleData>(json);
        var table = sampleData.Items;

        // write tab delimited table without knowing column names
        var line = string.Empty;
        foreach (DataColumn column in table.Columns)            
            line += column.ColumnName + "\t";                       
        Console.WriteLine(line);

        foreach (DataRow row in table.Rows)
        {
            line = string.Empty;
            foreach (DataColumn column in table.Columns)                
                line += row[column] + "\t";                                   
            Console.WriteLine(line);
        }

        // Name   Age   Job    
        // AAA    22    PPP    
        // BBB    25    QQQ    
        // CCC    38    RRR    
    }

You can determine the DataTable column names and types dynamically once deserialized.

Using ConfigurationManager to load config from an arbitrary location

I provided the configuration values to word hosted .nET Compoent as follows.

A .NET Class Library component being called/hosted in MS Word. To provide configuration values to my component, I created winword.exe.config in C:\Program Files\Microsoft Office\OFFICE11 folder. You should be able to read configurations values like You do in Traditional .NET.

string sMsg = System.Configuration.ConfigurationManager.AppSettings["WSURL"];

What's the best way to store Phone number in Django models

This solution worked for me:

First install django-phone-field

command: pip install django-phone-field

then on models.py

from phone_field import PhoneField
...

class Client(models.Model):
    ...
    phone_number = PhoneField(blank=True, help_text='Contact phone number')

and on settings.py

INSTALLED_APPS = [...,
                  'phone_field'
]

It looks like this in the end

phone in form

how to query LIST using linq

Since you haven't given any indication to what you want, here is a link to 101 LINQ samples that use all the different LINQ methods: 101 LINQ Samples

Also, you should really really really change your List into a strongly typed list (List<T>), properly define T, and add instances of T to your list. It will really make the queries much easier since you won't have to cast everything all the time.

Get a list of URLs from a site

I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.

How to display an IFRAME inside a jQuery UI dialog

Although this is a old post, I have spent 3 hours to fix my issue and I think this might help someone in future.

Here is my jquery-dialog hack to show html content inside an <iframe> :

let modalProperties = {autoOpen: true, width: 900, height: 600, modal: true, title: 'Modal Title'};
let modalHtmlContent = '<div>My Content First div</div><div>My Content Second div</div>';

// create wrapper iframe
let wrapperIframe = $('<iframe src="" frameborder="0" style="width:100%; height:100%;"></iframe>');

// create jquery dialog by a 'div' with 'iframe' appended
$("<div></div>").append(wrapperIframe).dialog(modalProperties);

// insert html content to iframe 'body'
let wrapperIframeDocument = wrapperIframe[0].contentDocument;
let wrapperIframeBody = $('body', wrapperIframeDocument);
wrapperIframeBody.html(modalHtmlContent);

jsfiddle demo

How to list all available Kafka brokers in a cluster?

To use zookeeper commands with shell script try

zookeeper/bin/zkCli.sh -server localhost:2181 <<< "ls /brokers/ids" | tail -n 1. The last line usually has the response details

How do I make Visual Studio pause after executing a console application in debug mode?

Do a readline at the end (it's the "forma cochina", like we say in Colombia, but it works):

static void Main(string[] args)
{
    .
    .
    .
    String temp = Console.ReadLine();
}

java.util.NoSuchElementException: No line found

You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html

LoDash: Get an array of values from an array of object properties

In the new lodash release v4.0.0 _.pluck has removed in favor of _.map

Then you can use this:

_.map(users, 'id'); // [12, 14, 16, 18]

You can see in Github Changelog

How to compile and run C files from within Notepad++ using NppExec plugin?

You can actually compile and run C code even without the use of nppexec plugins. If you use MingW32 C compiler, use g++ for C++ language and gcc for C language.

Paste this code into the notepad++ run section

cmd /k cd $(CURRENT_DIRECTORY) && gcc $(FILE_NAME) -o $(NAME_PART).exe  && $(NAME_PART).exe && pause

It will compile your C code into exe and run it immediately. It's like a build and run feature in CodeBlock. All these are done with some cmd knowledge.

Explanation:

  1. cmd /k is used for testing.
  2. cd $(CURRENT_DIRECTORY)
    • change directory to where file is located
  3. && operators
    • to chain your commands in a single line
  4. gcc $(FILE_NAME)
    • use GCC to compile File with its file extension.
  5. -o $(NAME_PART).exe
    • this flag allow you to choose your output filename. $(NAME_PART) does not include file extension.
  6. $(NAME_PART).exe
    • this alone runs your program
  7. pause
    • this command is used to keep your console open after file has been executed.

For more info on notepad++ commands, go to

http://docs.notepad-plus-plus.org/index.php/External_Programs

Relation between CommonJS, AMD and RequireJS?

Quoting

AMD:

  • One browser-first approach
  • Opting for asynchronous behavior and simplified backwards compatibility
  • It doesn't have any concept of File I/O.
  • It supports objects, functions, constructors, strings, JSON and many other types of modules.

CommonJS:

  • One server-first approach
  • Assuming synchronous behavior
  • Cover a broader set of concerns such as I/O, File system, Promises and more.
  • Supports unwrapped modules, it can feel a little more close to the ES.next/Harmony specifications, freeing you of the define() wrapper that AMD enforces.
  • Only support objects as modules.

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

It's was great if delete return the delete pair of the hash. I'm doing this:

hash = {a: 1, b: 2, c: 3}
{b: hash.delete(:b)} # => {:b=>2}
hash  # => {:a=>1, :c=>3} 

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

if you set your context model as code first based on exist database so you have to for set migration:

Add-Migration InitialCreate –IgnoreChanges
Update-database -force

and then change your context model and set:

Add-migration RemoveIspositive
Update-database -force

How do I kill all the processes in Mysql "show processlist"?

If you are using laravel then this is for you:

$query = "SHOW FULL PROCESSLIST";
    $results = DB::select(DB::raw($query));

    foreach($results as $result){
        if($result->Command == "Sleep"){
            $sql="KILL ". $result->Id;
            DB::select(DB::raw($sql));
        }
    }

Of-course, you should use this use Illuminate\Support\Facades\DB; after your namespace.

Using only CSS, show div on hover over <a>

Don't forget. if you are trying to hover around an image, you have to put it around a container. css:

.brand:hover + .brand-sales {
    display: block;
}

.brand-sales {
    display: none;
}

If you hover on this:

<span className="brand">
   <img src="https://murmure.me/wp-content/uploads/2017/10/nike-square-1900x1900.jpg" 
     alt"some image class="product-card-place-logo"/>
</span>

This will show:

<div class="product-card-sales-container brand-sales">
    <div class="product-card-">Message from the business goes here. They can talk alot or not</div>
</div>

Show animated GIF

Using swing you could simply use a JLabel

 public static void main(String[] args) throws MalformedURLException {

        URL url = new URL("<URL to your Animated GIF>");
        Icon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);

        JFrame f = new JFrame("Animation");
        f.getContentPane().add(label);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

How to pass ArrayList<CustomeObject> from one activity to another?

You can pass an ArrayList<E> the same way, if the E type is Serializable.

You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

Example:

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

Undo a particular commit in Git that's been pushed to remote repos

Identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes. In a way, git revert is the converse of git cherry-pick -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.

Difference between using gradlew and gradle

gradlew is a wrapper(w - character) that uses gradle.

Under the hood gradlew performs three main things:

  • Download and install the correct gradle version
  • Parse the arguments
  • Call a gradle task

Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.

To create a wrapper run:

gradle wrapper

This command generate:

gradle-wrapper.properties will contain the information about the Gradle distribution

*./ Is used on Unix to specify the current directory

Angular 2.0 router not working on reloading the browser

If you want to be able to enter urls in browser without configuring your AppServer to handle all requests to index.html, you must use HashLocationStrategy.

The easiest way to configure is using:

RouterModule.forRoot(routes, { useHash: true })

Instead of:

RouterModule.forRoot(routes)

With HashLocationStrategy your urls gonna be like:

http://server:port/#/path

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

Had a similar problem and was getting the following errors depending on what app I used and if we bypassed the firewall / load balancer or not:

HTTPS handshake to [blah] (for #136) failed. System.IO.IOException Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

and

ReadResponse() failed: The server did not return a complete response for this request. Server returned 0 bytes.

The problem turned out to be that the SSL Server Certificate got missed and wasn't installed on a couple servers.

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

You have two options for displaying the Map

  1. Use Maps Library for Android to render the Map
  2. Use Maps API V3 inside a web view

For showing local POIs around a Lat, Long use Places APIs

Command to open file with git

I found a workaround for this via this link. In a nutshell, you have to:

  1. Create a file named subl (or any name you'd like for the command to call for Sublime Text) without extension
  2. Put this command inside the above file(Replace the path for executable if necessary):

    #!/bin/sh
    "C:\Program Files\Sublime Text 2\sublime_text.exe" $1 &
    
  3. Place that subl file inside the adequate command directory according to your OS and Sublime Text version (If you have doubts, check the above link comments section). In my case, I'm using Sublime Text 3 with Windows 10 64bit so I placed it in:

    C:\Program Files (x86)\Git\usr\bin
    
  4. Now, in order for you to open the desired file, in git bash use (within file folder)

    subl filename
    

`ui-router` $stateParams vs. $state.params

EDIT: This answer is correct for version 0.2.10. As @Alexander Vasilyev pointed out it doesn't work in version 0.2.14.

Another reason to use $state.params is when you need to extract query parameters like this:

$stateProvider.state('a', {
  url: 'path/:id/:anotherParam/?yetAnotherParam',
  controller: 'ACtrl',
});

module.controller('ACtrl', function($stateParams, $state) {
  $state.params; // has id, anotherParam, and yetAnotherParam
  $stateParams;  // has id and anotherParam
}

How to configure WAMP (localhost) to send email using Gmail?

It's quite simple. (Adapt syntax for your convenience)

public $smtp = array(
    'transport' => 'Smtp',
    'from' => '[email protected]',
    'host' => 'ssl://smtp.gmail.com',
    'port' => 465,
    'timeout' => 30,
    'username' => '[email protected]',
    'password' => '*****'
)

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

I had same issue in Angular7 when I create dynamic components. There are two components(TreatListComponent, MyTreatComponent) that needs to be loaded dynamically. I just added entryComponents array in to my app.module.ts file.

    entryComponents: [
    TreatListComponent,
    MyTreatComponent
  ],

server error:405 - HTTP verb used to access this page is not allowed

Try renaming the default file. In my case, a recent move to IIS7.5 gave the 405 error. I changed index.aspx to default.aspx and it worked immediately for me.

How do I unload (reload) a Python module?

Other option. See that Python default importlib.reload will just reimport the library passed as an argument. It won't reload the libraries that your lib import. If you changed a lot of files and have a somewhat complex package to import, you must do a deep reload.

If you have IPython or Jupyter installed, you can use a function to deep reload all libs:

from IPython.lib.deepreload import reload as dreload
dreload(foo)

If you don't have Jupyter, install it with this command in your shell:

pip3 install jupyter

Console logging for react?

Here are some more console logging "pro tips":

console.table

var animals = [
    { animal: 'Horse', name: 'Henry', age: 43 },
    { animal: 'Dog', name: 'Fred', age: 13 },
    { animal: 'Cat', name: 'Frodo', age: 18 }
];

console.table(animals);

console.table

console.trace

Shows you the call stack for leading up to the console.

console.trace

You can even customise your consoles to make them stand out

console.todo = function(msg) {
    console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}

console.important = function(msg) {
    console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}

console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);

console.todo

If you really want to level up don't limit your self to the console statement.

Here is a great post on how you can integrate a chrome debugger right into your code editor!

https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037

Download file from web in Python 3

Here we can use urllib's Legacy interface in Python3:

The following functions and classes are ported from the Python 2 module urllib (as opposed to urllib2). They might become deprecated at some point in the future.

Example (2 lines code):

import urllib.request

url = 'https://www.python.org/static/img/python-logo.png'
urllib.request.urlretrieve(url, "logo.png")

Git Remote: Error: fatal: protocol error: bad line length character: Unab

The error transformed in: fatal: protocol error: bad line length character: fata

after adding the location of git-upload-pack to the system path.

The problem seem to be an apostrophe added around the repository name: Looking with a tool like Process Monitor (from sys internals), that were added by the git client. It seems to be a git specific windows problem.

I tried the same command line in the prompt of the server: the full error was "fatal: not a given repository (or any of the parent directories): .git"

In conclusion, to me it seems like a software bug. Be advised that I am not a git expert, it is first time I use git, i come from subversion and perforce.

Maven: The packaging for this project did not assign a file to the build artifact

This reply is on a very old question to help others facing this issue.

I face this failed error while I were working on my Java project using IntelliJ IDEA IDE.

Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-cli) on project getpassword: The packaging for this project did not assign a file to the build artifact

this failed happens, when I choose install:install under Plugins - install, as pointed with red arrow in below image.

Choose Wrong Selection

Once I run the selected install under Lifecycle as illustrated above, the issue gone, and my maven install compile build successfully.

Execute bash script from URL

The best way to do it is

curl http://domain/path/to/script.sh | bash -s arg1 arg2

which is a slight change of answer by @user77115

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

ImportError: No module named scipy

This may be too basic (and perhaps assumable), but -

Fedora users can use:

sudo dnf install python-scipy

and then (For python3.x):

pip3 install scipy

or (For python2.7):

pip2 install scipy

How to remove the first and the last character of a string

You can use substring method

s = s.substring(0, s.length - 1) //removes last character

another alternative is slice method

MySQL direct INSERT INTO with WHERE clause

If I understand the goal is to insert a new record to a table but if the data is already on the table: skip it! Here is my answer:

INSERT INTO tbl_member 
(Field1,Field2,Field3,...) 
SELECT a.Field1,a.Field2,a.Field3,... 
FROM (SELECT Field1 = [NewValueField1], Field2 = [NewValueField2], Field3 = [NewValueField3], ...) AS a 
LEFT JOIN tbl_member AS b 
ON a.Field1 = b.Field1 
WHERE b.Field1 IS NULL

The record to be inserted is in the new value fields.

How can I check if a View exists in a Database?

You can check the availability of the view in various ways

FOR SQL SERVER

use sys.objects

IF EXISTS(
   SELECT 1
   FROM   sys.objects
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
          AND Type_Desc = 'VIEW'
)
BEGIN
    PRINT 'View Exists'
END

use sysobjects

IF NOT EXISTS (
   SELECT 1
   FROM   sysobjects
   WHERE  NAME = '[schemaName].[ViewName]'
          AND xtype = 'V'
)
BEGIN
    PRINT 'View Exists'
END

use sys.views

IF EXISTS (
   SELECT 1
   FROM sys.views
   WHERE OBJECT_ID = OBJECT_ID(N'[schemaName].[ViewName]')
)
BEGIN
    PRINT 'View Exists'
END

use INFORMATION_SCHEMA.VIEWS

IF EXISTS (
   SELECT 1
   FROM   INFORMATION_SCHEMA.VIEWS
   WHERE  table_name = 'ViewName'
          AND table_schema = 'schemaName'
)
BEGIN
    PRINT 'View Exists'
END

use OBJECT_ID

IF EXISTS(
   SELECT OBJECT_ID('ViewName', 'V')
)
BEGIN
    PRINT 'View Exists'
END

use sys.sql_modules

IF EXISTS (
   SELECT 1
   FROM   sys.sql_modules
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
)
BEGIN
   PRINT 'View Exists'
END

Attempt to write a readonly database - Django w/ SELinux error

You can change the owner of your database file and it's folder to django:

chown django:django /home/django/mysite
chown django:django /home/django/mysite/my_db.sqlite3

This work for DigitalOcean's 1-Click Django Droplet

TypeError: $(...).on is not a function

I tried the solution of Oskar (and many others) but for me it finaly only worked with:

jQuery(function($){
   // Your jQuery code here, using the $
});

See: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

Sizing elements to percentage of screen width/height

FractionallySizedBox may also be useful. You can also read the screen width directly out of MediaQuery.of(context).size and create a sized box based on that

MediaQuery.of(context).size.width * 0.65

if you really want to size as a fraction of the screen regardless of what the layout is.

Why is width: 100% not working on div {display: table-cell}?

Welcome to 2017 these days will using vW and vH do the trick

_x000D_
_x000D_
html, body {_x000D_
    margin: 0; padding: 0;_x000D_
    width: 100%; height: 100%;_x000D_
}_x000D_
_x000D_
ul {_x000D_
    background: #CCC;_x000D_
    height: 100%;_x000D_
    width: 100%;_x000D_
    list-style-position: outside;_x000D_
    margin: 0; padding: 0;_x000D_
}_x000D_
_x000D_
li {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
}_x000D_
_x000D_
img {_x000D_
    width: 100%;_x000D_
    height: 410px;_x000D_
}_x000D_
_x000D_
.outer-wrapper {_x000D_
    position: absolute;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    top: 0;_x000D_
    margin: 0; padding: 0;_x000D_
}_x000D_
_x000D_
.inner-wrapper {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    text-align: center;_x000D_
    width: 100vw; /* only change is here "%" to "vw" ! */_x000D_
    height: 100vh; /* only change is here "%" to "vh" ! */_x000D_
}
_x000D_
<ul>_x000D_
    <li>_x000D_
        <img src="#">_x000D_
        <div class="outer-wrapper">_x000D_
            <div class="inner-wrapper">_x000D_
                <h1>My Title</h1>_x000D_
                <h5>Subtitle</h5>_x000D_
            </div>_x000D_
        </div>_x000D_
    </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

member names cannot be the same as their enclosing type C#

just remove this because constructor don't have a return type like void it will be like this :

private Flow()
    {
        X = x;
        Y = y;
    }  

Where does Java's String constant pool live, the heap or the stack?

String literals are not stored on the stack. Never. In fact, no objects are stored on the stack.

String literals (or more accurately, the String objects that represent them) are were historically stored in a Heap called the "permgen" heap. (Permgen is short for permanent generation.)

Under normal circumstances, String literals and much of the other stuff in the permgen heap are "permanently" reachable, and are not garbage collected. (For instance, String literals are always reachable from the code objects that use them.) However, you can configure a JVM to attempt to find and collect dynamically loaded classes that are no longer needed, and this may cause String literals to be garbage collected.

CLARIFICATION #1 - I'm not saying that Permgen doesn't get GC'ed. It does, typically when the JVM decides to run a Full GC. My point is that String literals will be reachable as long as the code that uses them is reachable, and the code will be reachable as long as the code's classloader is reachable, and for the default classloaders, that means "for ever".

CLARIFICATION #2 - In fact, Java 7 and later uses the regular heap to hold the string pool. Thus, String objects that represent String literals and intern'd strings are actually in the regular heap. (See @assylias's Answer for details.)


But I am still trying to find out thin line between storage of string literal and string created with new.

There is no "thin line". It is really very simple:

  • String objects that represent / correspond to string literals are held in the string pool.
  • String objects that were created by a String::intern call are held in the string pool.
  • All other String objects are NOT held in the string pool.

Then there is the separate question of where the string pool is "stored". Prior to Java 7 it was the permgen heap. From Java 7 onwards it is the main heap.

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

Difference between single and double quotes in Bash

Others explained very well and just want to give with simple examples.

Single quotes can be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.

$ echo 'All sorts of things are ignored in single quotes, like $ & * ; |.' 

It will give this:

All sorts of things are ignored in single quotes, like $ & * ; |.

The only thing that cannot be put within single quotes is a single quote.

Double quotes act similarly to single quotes, except double quotes still allow the shell to interpret dollar signs, back quotes and backslashes. It is already known that backslashes prevent a single special character from being interpreted. This can be useful within double quotes if a dollar sign needs to be used as text instead of for a variable. It also allows double quotes to be escaped so they are not interpreted as the end of a quoted string.

$ echo "Here's how we can use single ' and double \" quotes within double quotes"

It will give this:

Here's how we can use single ' and double " quotes within double quotes

It may also be noticed that the apostrophe, which would otherwise be interpreted as the beginning of a quoted string, is ignored within double quotes. Variables, however, are interpreted and substituted with their values within double quotes.

$ echo "The current Oracle SID is $ORACLE_SID"

It will give this:

The current Oracle SID is test

Back quotes are wholly unlike single or double quotes. Instead of being used to prevent the interpretation of special characters, back quotes actually force the execution of the commands they enclose. After the enclosed commands are executed, their output is substituted in place of the back quotes in the original line. This will be clearer with an example.

$ today=`date '+%A, %B %d, %Y'`
$ echo $today 

It will give this:

Monday, September 28, 2015 

how to increase the limit for max.print in R

Use the options command, e.g. options(max.print=1000000).

See ?options:

 ‘max.print’: integer, defaulting to ‘99999’.  ‘print’ or ‘show’
      methods can make use of this option, to limit the amount of
      information that is printed, to something in the order of
      (and typically slightly less than) ‘max.print’ _entries_.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

try this code it might be useful -

<%# ((DataBinder.Eval(Container.DataItem,"ImageFilename").ToString()=="") ? "" :"<a
 href="+DataBinder.Eval(Container.DataItem, "link")+"><img
 src='/Images/Products/"+DataBinder.Eval(Container.DataItem,
 "ImageFilename")+"' border='0' /></a>")%>

How do I concatenate two arrays in C#?

Here's my answer:

int[] z = new List<string>()
    .Concat(a)
    .Concat(b)
    .Concat(c)
    .ToArray();

This method can be used at initialization level, for example to define a static concatenation of static arrays:

public static int[] a = new int [] { 1, 2, 3, 4, 5 };
public static int[] b = new int [] { 6, 7, 8 };
public static int[] c = new int [] { 9, 10 };

public static int[] z = new List<string>()
    .Concat(a)
    .Concat(b)
    .Concat(c)
    .ToArray();

However, it comes with two caveats that you need to consider:

  • The Concat method creates an iterator over both arrays: it does not create a new array, thus being efficient in terms of memory used: however, the subsequent ToArray  will negate such advantage, since it will actually create a new array and take up the memory for the new array.
  • As @Jodrell said, Concat would be rather inefficient for large arrays: it should only be used for medium-sized arrays.

If aiming for performance is a must, the following method can be used instead:

/// <summary>
/// Concatenates two or more arrays into a single one.
/// </summary>
public static T[] Concat<T>(params T[][] arrays)
{
    // return (from array in arrays from arr in array select arr).ToArray();

    var result = new T[arrays.Sum(a => a.Length)];
    int offset = 0;
    for (int x = 0; x < arrays.Length; x++)
    {
        arrays[x].CopyTo(result, offset);
        offset += arrays[x].Length;
    }
    return result;
}

Or (for one-liners fans):

int[] z = (from arrays in new[] { a, b, c } from arr in arrays select arr).ToArray();

Although the latter method is much more elegant, the former one is definitely better for performance.

For additional info, please refer to this post on my blog.

Javascript getElementsByName.value not working

document.getElementsByName("name") will get several elements called by same name . document.getElementsByName("name")[Number] will get one of them. document.getElementsByName("name")[Number].value will get the value of paticular element.

The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.

Executing a batch file in a remote machine through PsExec

You have an extra -c you need to get rid of:

psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"

Text File Parsing with Python

I would use a for loop to iterate over the lines in the text file:

for line in my_text:
    outputfile.writelines(data_parser(line, reps))

If you want to read the file line-by-line instead of loading the whole thing at the start of the script you could do something like this:

inputfile = open('test.dat')
outputfile = open('test.csv', 'w')

# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'

# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }

for i in range(4): inputfile.next() # skip first four lines
for line in inputfile:
    outputfile.writelines(data_parser(line, reps))

inputfile.close()
outputfile.close()

Elasticsearch difference between MUST and SHOULD bool query

Since this is a popular question, I would like to add that in Elasticsearch version 2 things changed a bit.

Instead of filtered query, one should use bool query in the top level.

If you don't care about the score of must parts, then put those parts into filter key. No scoring means faster search. Also, Elasticsearch will automatically figure out, whether to cache them, etc. must_not is equally valid for caching.

Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

Also, mind that "gte": "now" cannot be cached, because of millisecond granularity. Use two ranges in a must clause: one with now/1h and another with now so that the first can be cached for a while and the second for precise filtering accelerated on a smaller result set.

Convert base class to derived class

I have found one solution to this, not saying it's the best one, but it feels clean to me and doesn't require any major changes to my code. My code looked similar to yours until I realized it didn't work.

My Base Class

public class MyBaseClass
{
   public string BaseProperty1 { get; set; }
   public string BaseProperty2 { get; set; }
   public string BaseProperty3 { get; set; }
   public string BaseProperty4 { get; set; }
   public string BaseProperty5 { get; set; }
}

My Derived Class

public class MyDerivedClass : MyBaseClass
{
   public string DerivedProperty1 { get; set; }
   public string DerivedProperty2 { get; set; }
   public string DerivedProperty3 { get; set; }
}

Previous method to get a populated base class

public MyBaseClass GetPopulatedBaseClass()
{
   var myBaseClass = new MyBaseClass();

   myBaseClass.BaseProperty1 = "Something"
   myBaseClass.BaseProperty2 = "Something else"
   myBaseClass.BaseProperty3 = "Something more"
   //etc...

   return myBaseClass;
}

Before I was trying this, which gave me a unable to cast error

public MyDerivedClass GetPopulatedDerivedClass()
{
   var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();

   newDerivedClass.UniqueProperty1 = "Some One";
   newDerivedClass.UniqueProperty2 = "Some Thing";
   newDerivedClass.UniqueProperty3 = "Some Thing Else";

   return newDerivedClass;
}

I changed my code as follows bellow and it seems to work and makes more sense now:

Old

public MyBaseClass GetPopulatedBaseClass()
{
   var myBaseClass = new MyBaseClass();

   myBaseClass.BaseProperty1 = "Something"
   myBaseClass.BaseProperty2 = "Something else"
   myBaseClass.BaseProperty3 = "Something more"
   //etc...

   return myBaseClass;
}

New

public void FillBaseClass(MyBaseClass myBaseClass)
{
   myBaseClass.BaseProperty1 = "Something"
   myBaseClass.BaseProperty2 = "Something else"
   myBaseClass.BaseProperty3 = "Something more"
   //etc...
}

Old

public MyDerivedClass GetPopulatedDerivedClass()
{
   var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();

   newDerivedClass.UniqueProperty1 = "Some One";
   newDerivedClass.UniqueProperty2 = "Some Thing";
   newDerivedClass.UniqueProperty3 = "Some Thing Else";

   return newDerivedClass;
}

New

public MyDerivedClass GetPopulatedDerivedClass()
{
   var newDerivedClass = new MyDerivedClass();

   FillBaseClass(newDerivedClass);

   newDerivedClass.UniqueProperty1 = "Some One";
   newDerivedClass.UniqueProperty2 = "Some Thing";
   newDerivedClass.UniqueProperty3 = "Some Thing Else";

   return newDerivedClass;
}

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

Column names must be unique in the table. You cannot have two columns named asd in the same table.

Appending a line break to an output file in a shell script

Try

echo -en "`date` User `whoami` started the script.\n" >> output.log

Try issuing this multiple times. I hope you are looking for the same output.

What is difference between INNER join and OUTER join

INNER JOIN: Returns all rows when there is at least one match in BOTH tables

LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

FULL JOIN: Return all rows when there is a match in ONE of the tables

Find a value in DataTable

this question asked in 2009 but i want to share my codes:

    Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable

    Dim x As Integer
    Dim y As Integer

    Dim bln As Boolean

    Dim dttable2 As New DataTable
    For x = 0 To dttable.Columns.Count - 1
        dttable2.Columns.Add(dttable.Columns(x).ColumnName)
    Next

    For x = 0 To dttable.Rows.Count - 1
        For y = 0 To searchcolumns.Length - 1
            If String.IsNullOrEmpty(searchcolumns(y)) = False Then
                If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
                    bln = True
                Else
                    bln = False
                    Exit For
                End If
            End If
        Next
        If bln = True Then
            dttable2.Rows.Add(dttable.Rows(x).ItemArray)
        End If
    Next

    Return dttable2


End Function

Check which element has been clicked with jQuery

The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:

http://api.jquery.com/category/selectors/

However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.

Java: how do I initialize an array size if it's unknown?

String line=sc.nextLine();
    int counter=1;
    for(int i=0;i<line.length();i++) {
        if(line.charAt(i)==' ') {
            counter++;
        }
    }
    long[] numbers=new long[counter];
    counter=0;
    for(int i=0;i<line.length();i++){
        int j=i;
        while(true) {
            if(j>=line.length() || line.charAt(j)==' ') {
                break;
            }
            j++;
        }
        numbers[counter]=Integer.parseInt(line.substring(i,j));
        i=j;
        counter++;  
    }
    for(int i=0;i<counter;i++) {
        System.out.println(numbers[i]);
    }    

I always use this code for situations like this. beside you can recognize two or three or more digit numbers.

Broadcast Receiver within a Service

The better pattern is to create a standalone BroadcastReceiver. This insures that your app can respond to the broadcast, whether or not the Service is running. In fact, using this pattern may remove the need for a constant-running Service altogether.

Register the BroadcastReceiver in your Manifest, and create a separate class/file for it.

Eg:

<receiver android:name=".FooReceiver" >
    <intent-filter >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

When the receiver runs, you simply pass an Intent (Bundle) to the Service, and respond to it in onStartCommand().

Eg:

public class FooReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do your work quickly!
        // then call context.startService();
    }   
}

What is the HTML5 equivalent to the align attribute in table cells?

you can use this code as replacement for table align

table 
{
    margin:auto;
}

How to change the background colour's opacity in CSS

Use rgba as most of the commonly used browsers supports it..

.social img:hover {
 background-color: rgba(0, 0, 0, .5)
}

Show two digits after decimal point in c++

cout << fixed << setprecision(2) << total;

setprecision specifies the minimum precision. So

cout << setprecision (2) << 1.2; 

will print 1.2

fixed says that there will be a fixed number of decimal digits after the decimal point

cout << setprecision (2) << fixed << 1.2;

will print 1.20

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

Passing a URL with brackets to curl

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

There is no wheel (prebuilt package) for Python 3.7 on Windows (there is one for Python 2.7 and 3.4 up to 3.6) so you need to prepare build environment on your PC to use this package. Easier would be finding the wheel for 3.7 as some packages are quite hard to build on Windows.

Christoph Gohlke (University of California) hosts Windows wheels for most popular packages for nearly all modern Python versions, including latest PyAudio. You can find it here: https://www.lfd.uci.edu/~gohlke/pythonlibs/ (download can be quite slow). After download, just type pip install <downloaded file here>.

There is no difference between python -m pip install, and pip install as long as you're using default installation settings and single python installation. python pip actually tries to run file pip in the current directory.

Edit. See the pipwin comment for automated way of using Mr Goblke's libs . Note that I've not used it myself and I'm not sure about selecting different package flavors like vanilla and mkl versions of numpy.

Named placeholders in string formatting

I tried in just a quick way

public static void main(String[] args) 
{
    String rowString = "replace the value ${var1} with ${var2}";
    
    Map<String,String> mappedValues = new HashMap<>();
    
    mappedValues.put("var1", "Value 1");
    mappedValues.put("var2", "Value 2");
    
    System.out.println(replaceOccurence(rowString, mappedValues));
}

private static  String replaceOccurence(String baseStr ,Map<String,String> mappedValues)
{
    for(String key :mappedValues.keySet())
    {
        baseStr = baseStr.replace("${"+key+"}", mappedValues.get(key));
    }
    
    return baseStr;
}

Find (and kill) process locking port 3000 on Mac

You can try this

netstat -vanp tcp | grep 3000

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

What does "static" mean in C?

There is one more use not covered here, and that is as part of an array type declaration as an argument to a function:

int someFunction(char arg[static 10])
{
    ...
}

In this context, this specifies that arguments passed to this function must be an array of type char with at least 10 elements in it. For more info see my question here.

How do I display an alert dialog on Android?

You can use this code:

AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
    AlertDialogActivity.this);

// Setting Dialog Title
alertDialog2.setTitle("Confirm Delete...");

// Setting Dialog Message
alertDialog2.setMessage("Are you sure you want delete this file?");

// Setting Icon to Dialog
alertDialog2.setIcon(R.drawable.delete);

// Setting Positive "Yes" Btn
alertDialog2.setPositiveButton("YES",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // Write your code here to execute after dialog
            Toast.makeText(getApplicationContext(),
                           "You clicked on YES", Toast.LENGTH_SHORT)
                    .show();
        }
    });

// Setting Negative "NO" Btn
alertDialog2.setNegativeButton("NO",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // Write your code here to execute after dialog
            Toast.makeText(getApplicationContext(),
                           "You clicked on NO", Toast.LENGTH_SHORT)
                    .show();
            dialog.cancel();
        }
    });

// Showing Alert Dialog
alertDialog2.show();

Remove Item in Dictionary based on Value

Are you trying to remove a single value or all matching values?

If you are trying to remove a single value, how do you define the value you wish to remove?

The reason you don't get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.

If you wish to remove all matching instances of the same value, you can do this:

foreach(var item in dic.Where(kvp => kvp.Value == value).ToList())
{
    dic.Remove(item.Key);
}

And if you wish to remove the first matching instance, you can query to find the first item and just remove that:

var item = dic.First(kvp => kvp.Value == value);

dic.Remove(item.Key);

Note: The ToList() call is necessary to copy the values to a new collection. If the call is not made, the loop will be modifying the collection it is iterating over, causing an exception to be thrown on the next attempt to iterate after the first value is removed.

What exactly does an #if 0 ..... #endif block do?

Lines beginning with a # are preprocessor directives. #if 0 [...] #endif blocks do not make it to the compiler and will generate no machine code.

You can demonstrate what happens with the preprocessor with a source file ifdef.cxx:

#if 0
This code will not be compiled
#else
int i = 0;
#endif

Running gcc -E ifdef.cxx will show you what gets compiled.

You may choose to use this mechanism to prevent a block of code being compiled during the development cycle, but you would probably not want to check it in to your source control as it just adds cruft to your code and reduces readability. If it's a historical piece of code that has been commented out, then it should be removed: source control contains the history, right?

Also, the answer may be the same for both C and C++ but there is no language called C/C++ and it's not a good habit to refer to such a language.

Android Fragments and animation

As for me, i need the view diraction:

in -> swipe from right

out -> swipe to left

Here works for me code:

slide_in_right.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="50%p" android:toXDelta="0"
            android:duration="@android:integer/config_mediumAnimTime"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
            android:duration="@android:integer/config_mediumAnimTime" />
</set>

slide_out_left.xml

 <set xmlns:android="http://schemas.android.com/apk/res/android">
        <translate android:fromXDelta="0" android:toXDelta="-50%p"
                android:duration="@android:integer/config_mediumAnimTime"/>
        <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
                android:duration="@android:integer/config_mediumAnimTime" />
    </set>

transaction code:

inline fun FragmentActivity.setContentFragment(
        containerViewId: Int,
        backStack: Boolean = false,
        isAnimate: Boolean = false,
        f: () -> Fragment

): Fragment? {
    val manager = supportFragmentManager
    return f().apply {
        manager.beginTransaction().let {
            if (isAnimate)
                it.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)

            if (backStack) {
                it.replace(containerViewId, this, "Fr").addToBackStack("Fr").commit()
            } else {
                it.replace(containerViewId, this, "Fr").commit()
            }
        }
    }
}

Force IE9 to emulate IE8. Possible?

On the client side you can add and remove websites to be displayed in Compatibility View from Compatibility View Settings window of IE:

Tools-> Compatibility View Settings