Programs & Examples On #Shared secret

SQL Server - Create a copy of a database table and place it in the same database?

Use SELECT ... INTO:

SELECT *
INTO ABC_1
FROM ABC;

This will create a new table ABC_1 that has the same column structure as ABC and contains the same data. Constraints (e.g. keys, default values), however, are -not- copied.

You can run this query multiple times with a different table name each time.


If you don't need to copy the data, only to create a new empty table with the same column structure, add a WHERE clause with a falsy expression:

SELECT *
INTO ABC_1
FROM ABC
WHERE 1 <> 1;

Remove git mapping in Visual Studio 2015

download the extension from microsoft and install to remove GIT extension from Visual studio and SSMS.

https://marketplace.visualstudio.com/items?itemName=MarkRendle.NoGit

SSMS: Edit the ssms.pkgundef file found at C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\ssms.pkgundef and remove all git related entries

Javascript/DOM: How to remove all events of a DOM object?

angular has a polyfill for this issue, you can check. I did not understand much but maybe it can help.

const REMOVE_ALL_LISTENERS_EVENT_LISTENER = 'removeAllListeners';

    proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
        const target = this || _global;
        const eventName = arguments[0];
        if (!eventName) {
            const keys = Object.keys(target);
            for (let i = 0; i < keys.length; i++) {
                const prop = keys[i];
                const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
                let evtName = match && match[1];
                // in nodejs EventEmitter, removeListener event is
                // used for monitoring the removeListener call,
                // so just keep removeListener eventListener until
                // all other eventListeners are removed
                if (evtName && evtName !== 'removeListener') {
                    this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
                }
            }
            // remove removeListener listener finally
            this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
        }
        else {
            const symbolEventNames = zoneSymbolEventNames$1[eventName];
            if (symbolEventNames) {
                const symbolEventName = symbolEventNames[FALSE_STR];
                const symbolCaptureEventName = symbolEventNames[TRUE_STR];
                const tasks = target[symbolEventName];
                const captureTasks = target[symbolCaptureEventName];
                if (tasks) {
                    const removeTasks = tasks.slice();
                    for (let i = 0; i < removeTasks.length; i++) {
                        const task = removeTasks[i];
                        let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
                        this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
                    }
                }
                if (captureTasks) {
                    const removeTasks = captureTasks.slice();
                    for (let i = 0; i < removeTasks.length; i++) {
                        const task = removeTasks[i];
                        let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
                        this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
                    }
                }
            }
        }
        if (returnTarget) {
            return this;
        }
    };

....

Editing the date formatting of x-axis tick labels in matplotlib

While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.

So for everyone in need here is a full working example:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()

How do I set hostname in docker-compose?

As of docker-compose version 3 and later, you can just use the hostname key:

version: '3'
services:
  dns:
    hostname: 'your-name'

SQL: How to to SUM two values from different tables

you can also try this in sql-server !!

select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city 

demo

or try using sum,union

select sum(total)  as mytotal,city
from
(
    select * from cash union
    select * from cheque
) as vij
group by city 

Ascii/Hex convert in bash

jcomeau@aspire:~$ echo -n The quick brown fox jumps over the lazy dog | python -c "print raw_input().encode('hex'),"
54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67
jcomeau@aspire:~$ echo -n The quick brown fox jumps over the lazy dog | python -c "print raw_input().encode('hex')," | python -c "print raw_input().decode('hex'),"
The quick brown fox jumps over the lazy dog

it could be done with Python3 as well, but differently, and I'm a lazy dog.

How to check if ping responded or not in a batch file

I hope this helps someone. I use this bit of logic to verify if network shares are responsive before checking the individual paths. It should handle DNS names and IP addresses

A valid path in the text file would be \192.168.1.2\'folder' or \NAS\'folder'

@echo off
title Network Folder Check

pushd "%~dp0"
:00
cls

for /f "delims=\\" %%A in (Files-to-Check.txt) do set Server=%%A
    setlocal EnableDelayedExpansion
        ping -n 1 %Server% | findstr TTL= >nul 
            if %errorlevel%==1 ( 
                ping -n 1 %Server% | findstr "Reply from" | findstr "time" >nul
                    if !errorlevel!==1 (echo Network Asset %Server% Not Found & pause & goto EOF)
            )
:EOF

getting the difference between date in days in java

Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:

private static void dateDiff() {

    System.out.println("Calculate difference between two dates");
    System.out.println("=================================================================");

    DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    System.out.println("  Difference between " + endDate);
    System.out.println("  and " + startDate + " is " + days + " days.");

  }

Xcode couldn't find any provisioning profiles matching

What fixed it for me was plugging my iPhone and allowing it as a simulator destination. Doing so required my to register my iPhone in Apple Dev account and once that was done and I ran my project from Xcode on my iPhone everything fixed itself.

  1. Connect your iPhone to your Mac
  2. Xcode>Window>Devices & Simulators
  3. Add new under Devices and make sure "show are run destination" is ticked
  4. Build project and run it on your iPhone

How to measure time taken by a function to execute

Using performance.now():

var t0 = performance.now()

doSomething()   // <---- The function you're measuring time for 

var t1 = performance.now()
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

NodeJs: it is required to import the performance class


Using console.time: (non-standard) (living standard)

console.time('someFunction')

someFunction() // Whatever is timed goes between the two "console.time"

console.timeEnd('someFunction')

Note:
The string being pass to the time() and timeEnd() methods must match
(for the timer to finish as expected).

console.time() documentations:

  1. NodeJS documentation regarding
  2. MDN (client-side) documentation

Double precision floating values in Python?

May be you need Decimal

>>> from decimal import Decimal    
>>> Decimal(2.675)
Decimal('2.67499999999999982236431605997495353221893310546875')

Floating Point Arithmetic

Bootstrap get div to align in the center

In bootstrap you can use .text-centerto align center. also add .row and .col-md-* to your code.

align= is deprecated,

Added .col-xs-* for demo

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
  <div class="container">
    <div class="row">
      <div class="col-xs-4">
        <p>Hello there</p>
      </div>
      <div class="col-xs-4 text-center">
        <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
        <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
      </div>
      <div class="col-xs-4 text-right">
        <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
        <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
        <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
      </div>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

UPDATE(OCT 2017)

For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
  <div class="d-flex justify-content-between">
    <div class="p-1">
      <p>Hello there</p>
    </div>
    <div class="p-1">
      <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
      <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
    </div>
    <div class="p-1">
      <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
      <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
      <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to quickly and conveniently disable all console.log statements in my code?

This a hybrid of answers from SolutionYogi and Chris S. It maintains the console.log line numbers and file name. Example jsFiddle.

// Avoid global functions via a self calling anonymous one (uses jQuery)
(function(MYAPP, $, undefined) {
    // Prevent errors in browsers without console.log
    if (!window.console) window.console = {};
    if (!window.console.log) window.console.log = function(){};

    //Private var
    var console_log = console.log;  

    //Public methods
    MYAPP.enableLog = function enableLogger() { console.log = console_log; };   
    MYAPP.disableLog = function disableLogger() { console.log = function() {}; };

}(window.MYAPP = window.MYAPP || {}, jQuery));


// Example Usage:
$(function() {    
    MYAPP.disableLog();    
    console.log('this should not show');

    MYAPP.enableLog();
    console.log('This will show');
});

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

I was getting that exact message whenever my requests took more than 2 minutes to finish. The browser would disconnect from the request, but the request on the backend continued until it was finished. The server (ASP.NET Web API in my case) wouldn't detect the disconnect.

After an entire day searching, I finally found this answer, explaining that if you use the proxy config, it has a default timeout of 120 seconds (or 2 minutes).

So, you can edit your proxy configuration and set it to whatever you need:

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false,
    "timeout": 6000000
  }
}

Now, I was using agentkeepalive to make it work with NTLM authentication, and didn't know that the agent's timeout has nothing to do with the proxy's timeout, so both have to be set. It took me a while to realize that, so here's an example:

const Agent = require('agentkeepalive');

module.exports = {
    '/api/': {
        target: 'http://localhost:3000',
        secure: false,
        timeout: 6000000,          // <-- this is needed as well
        agent: new Agent({
            maxSockets: 100,
            keepAlive: true,
            maxFreeSockets: 10,
            keepAliveMsecs: 100000,
            timeout: 6000000,      // <-- this is for the agentkeepalive
            freeSocketTimeout: 90000
        }),
        onProxyRes: proxyRes => {
            let key = 'www-authenticate';
            proxyRes.headers[key] = proxyRes.headers[key] &&
                proxyRes.headers[key].split(',');
        }
    }
};

How to modify JsonNode in Java?

Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):

Exception in thread "main" java.lang.ClassCastException: 
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode

The solution is to get the 'parent' node, and perform a put, effectively replacing the entire node, regardless of original node type.

If you need to "modify" the node using the existing value of the node:

  1. get the value/array of the JsonNode
  2. Perform your modification on that value/array
  3. Proceed to call put on the parent.

Code, where the goal is to modify subfield, which is the child node of NodeA and Node1:

JsonNode nodeParent = someNode.get("NodeA")
                .get("Node1");

// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");

Credits:

I got this inspiration from here, thanks to wassgreen@

How do you add UI inside cells in a google spreadsheet using app script?

The apps UI only works for panels.

The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.

Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.

Alternatively you can also draw the button somewhere else and insert it as an image.

More info: https://developers.google.com/apps-script/guides/menus

enter image description here enter image description here enter image description here

ASP.NET 4.5 has not been registered on the Web server

I have the same issue when using Visual Studio 2012. By turn on the IIS feature just not working, because I still received the error. Try the method but no lucky.

My solution is:

  • Download the hotfix.
  • At the command line, Restart IIS by typing iisreset /noforce YourComputerName, and press ENTER.

Fastest way(s) to move the cursor on a terminal command line?

I tend to prefer vi editing mode (since those keystrokes are embedded into my spinal cord now (the brain's not used at all), along with the CTRL-K, CTRL-X from WordStar 3.3 :-). You can use the command line set -o vi to activate it (and set -o emacs to revert).

In Vi, it would be (ESC-K to get the line up first of course) "f5;;B" (without the double quotes).

Of course, you have to understand what's on the line to get away with this. Basically, it's

f5 to find the first occurrence of "5" (in --option5).
;  to find the next one (in --option15).
;  to find the next one (in --option25).
B  to back up to the start of the word.

Let's see if the emacs aficionados can come up with a better solution, less than 5 keystrokes (although I don't want to start a religious war).

Have you thought about whether you'd maybe like to put this horrendously long command into a script? :-)

Actually, I can go one better than that: "3f5B" to find the third occurrence of "5" then back up to the start of the word.

Amazon Linux: apt-get: command not found

This is one of the command which you can run to install apt-get:

wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.4_amd64.deb

How do you remove the title text from the Android ActionBar?

I think this is the right answer:

<style name="AppTheme" parent="Theme.Sherlock.Light.DarkActionBar">
    <item name="actionBarStyle">@style/Widget.Styled.ActionBar</item>
    <item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item>
</style>

<style name="Widget.Styled.ActionBar" parent="Widget.Sherlock.Light.ActionBar.Solid.Inverse">
    <item name="android:displayOptions">showHome|useLogo</item>
    <item name="displayOptions">showHome|useLogo</item>
</style>

Autoplay an audio with HTML5 embed tag while the player is invisible

<div id="music">
<audio autoplay>
  <source src="kooche.mp3" type="audio/mpeg">
  <p>If you can read this, your browser does not support the audio element.</p>
</audio>
</div>

And the css:

#music {
  display:none;
}

Like suggested above, you probably should have the controls available in some form. Maybe use a toggle link/checkbox that slides the controls in via jquery.

Source: HTML5 Audio Autoplay

How do you check in python whether a string contains only numbers?

You can also use the regex,

import re

eg:-1) word = "3487954"

re.match('^[0-9]*$',word)

eg:-2) word = "3487.954"

re.match('^[0-9\.]*$',word)

eg:-3) word = "3487.954 328"

re.match('^[0-9\.\ ]*$',word)

As you can see all 3 eg means that there is only no in your string. So you can follow the respective solutions given with them.

How to use comparison operators like >, =, < on BigDecimal

This thread has plenty of answers stating that the BigDecimal.compareTo(BigDecimal) method is the one to use to compare BigDecimal instances. I just wanted to add for anymore not experienced with using the BigDecimal.compareTo(BigDecimal) method to be careful with how you are creating your BigDecimal instances. So, for example...

  • new BigDecimal(0.8) will create a BigDecimal instance with a value which is not exactly 0.8 and which has a scale of 50+,
  • new BigDecimal("0.8") will create a BigDecimal instance with a value which is exactly 0.8 and which has a scale of 1

... and the two will be deemed to be unequal according to the BigDecimal.compareTo(BigDecimal) method because their values are unequal when the scale is not limited to a few decimal places.

First of all, be careful to create your BigDecimal instances with the BigDecimal(String val) constructor or the BigDecimal.valueOf(double val) method rather than the BigDecimal(double val) constructor. Secondly, note that you can limit the scale of BigDecimal instances prior to comparing them by means of the BigDecimal.setScale(int newScale, RoundingMode roundingMode) method.

Bootstrap select dropdown list placeholder

  1. in bootstrap-select.js Find title: null, and remove it.
  2. add title="YOUR TEXT" in <select> element.
  3. Fine :)

Example:

<select title="Please Choose one item">
    <option value="">A</option>
    <option value="">B</option>
    <option value="">C</option>
</select>

Drag and drop elements from list into separate blocks

_x000D_
_x000D_
 function dragStart(event) {_x000D_
            event.dataTransfer.setData("Text", event.target.id);_x000D_
        }_x000D_
_x000D_
        function allowDrop(event) {_x000D_
            event.preventDefault();_x000D_
        }_x000D_
_x000D_
        function drop(event) {_x000D_
            $("#maincontainer").append("<br/><table style='border:1px solid black; font-size:20px;'><tr><th>Name</th><th>Country</th><th>Experience</th><th>Technologies</th></tr><tr><td>  Bhanu Pratap   </td><td> India </td><td>  3 years   </td><td>  Javascript,Jquery,AngularJS,ASP.NET C#, XML,HTML,CSS,Telerik,XSLT,AJAX,etc...</td></tr></table>");_x000D_
        }
_x000D_
 .droptarget {_x000D_
            float: left;_x000D_
            min-height: 100px;_x000D_
            min-width: 200px;_x000D_
            border: 1px solid black;_x000D_
            margin: 15px;_x000D_
            padding: 10px;_x000D_
            border: 1px solid #aaaaaa;_x000D_
        }_x000D_
_x000D_
        [contentEditable=true]:empty:not(:focus):before {_x000D_
            content: attr(data-text);_x000D_
        }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
<div class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)">_x000D_
        <p ondragstart="dragStart(event)" draggable="true" id="dragtarget">Drag Table</p>_x000D_
    </div>_x000D_
_x000D_
    <div id="maincontainer" contenteditable=true data-text="Drop here..." class="droptarget" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
_x000D_
_x000D_
_x000D_

  1. this is just simple here i'm appending html table into a div at the end
  2. we can achieve this or any thing with a simple concept of calling a JavaScript function when we want (here on drop.)
  3. In this example you can drag & drop any number of tables, new table will be added below the last table exists in the div other wise it will be the first table in the div.
  4. here we can add text between tables or we can say the section where we drop tables is editable we can type text between tables. enter image description here

Thanks... :)

SQL Server Script to create a new user

CREATE LOGIN AdminLOGIN WITH PASSWORD = 'pass'
GO


Use MyDatabase;
GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'AdminLOGIN')
BEGIN
    CREATE USER [AdminLOGIN] FOR LOGIN [AdminLOGIN]
    EXEC sp_addrolemember N'db_owner', N'AdminLOGIN'
    EXEC master..sp_addsrvrolemember @loginame = N'adminlogin', @rolename = N'sysadmin'
END;
GO

this full help you for network using:

1- Right-click on SQL Server instance at root of Object Explorer, click on Properties
Select Security from the left pane.

2- Select the SQL Server and Windows Authentication mode radio button, and click OK.

3- Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).

4- Close sql server application and reopen it

5- open 'SQL Server Configuration Manager' and tcp enabled for network

6-Double-click the TCP/IP protocol, go to the IP Addresses tab and scroll down to the IPAll section.

7-Specify the 1433 in the TCP Port field (or another port if 1433 is used by another MSSQL Server) and press the OK 

8-Open in Sql Server: Security And Login  And Right Click on Login Name And Select Peroperties And Select Server Roles And 
  Checked The Sysadmin And Bulkadmin then Ok.
9-firewall: Open cmd as administrator and type: 
      netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT

How to display a JSON representation and not [Object Object] on the screen

<li *ngFor="let obj of myArray">{{obj | json}}</li>

What is the difference between ELF files and bin files?

some resources:

  1. ELF for the ARM architecture
    http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
  2. ELF from wiki
    http://en.wikipedia.org/wiki/Executable_and_Linkable_Format

ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:

  arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]

or using fromELF utility(built in most IDEs such as ADS though):

 fromelf -bin -o [binary-output-file] [elf-input-file]

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

How to write a file with C in Linux?

First of all, the code you wrote isn't portable, even if you get it to work. Why use OS-specific functions when there is a perfectly platform-independent way of doing it? Here's a version that uses just a single header file and is portable to any platform that implements the C standard library.

#include <stdio.h>

int main(int argc, char **argv)
{
    FILE* sourceFile;
    FILE* destFile;
    char buf[50];
    int numBytes;

    if(argc!=3)
    {
        printf("Usage: fcopy source destination\n");
        return 1;
    }

    sourceFile = fopen(argv[1], "rb");
    destFile = fopen(argv[2], "wb");

    if(sourceFile==NULL)
    {
        printf("Could not open source file\n");
        return 2;
    }
    if(destFile==NULL)
    {
        printf("Could not open destination file\n");
        return 3;
    }

    while(numBytes=fread(buf, 1, 50, sourceFile))
    {
        fwrite(buf, 1, numBytes, destFile);
    }

    fclose(sourceFile);
    fclose(destFile);

    return 0;
}

EDIT: The glibc reference has this to say:

In general, you should stick with using streams rather than file descriptors, unless there is some specific operation you want to do that can only be done on a file descriptor. If you are a beginning programmer and aren't sure what functions to use, we suggest that you concentrate on the formatted input functions (see Formatted Input) and formatted output functions (see Formatted Output).

If you are concerned about portability of your programs to systems other than GNU, you should also be aware that file descriptors are not as portable as streams. You can expect any system running ISO C to support streams, but non-GNU systems may not support file descriptors at all, or may only implement a subset of the GNU functions that operate on file descriptors. Most of the file descriptor functions in the GNU library are included in the POSIX.1 standard, however.

Combining the results of two SQL queries as separate columns

how to club the 4 query's as a single query

show below query

  1. total number of cases pending + 2.cases filed during this month ( base on sysdate) + total number of cases (1+2) + no. cases disposed where nse= disposed + no. of cases pending (other than nse <> disposed)

nsc = nature of case

report is taken on 06th of every month

( monthly report will be counted from 05th previous month to 05th present of present month)

Is it possible to get a list of files under a directory of a website? How?

If a website's directory does NOT have an "index...." file, AND .htaccess has NOT been used to block access to the directory itself, then Apache will create an "index of" page for that directory. You can save that page, and its icons, using "Save page as..." along with the "Web page, complete" option (Firefox example). If you own the website, temporarily rename any "index...." file, and reference the directory locally. Then restore your "index...." file.

How to get the text node of an element?

ES6 version that return the first #text node content

const extract = (node) => {
  const text = [...node.childNodes].find(child => child.nodeType === Node.TEXT_NODE);
  return text && text.textContent.trim();
}

Best dynamic JavaScript/JQuery Grid

My suggestion for dynamic JQuery Grid are below.

http://reconstrukt.com/ingrid/

https://github.com/mleibman/SlickGrid

http://www.datatables.net/index

Best one is :

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.

Variable length pagination

On-the-fly filtering

Multi-column sorting with data type detection

Smart handling of column widths

Display data from almost any data source

DOM, Javascript array, Ajax file and server-side processing (PHP, C#, Perl, Ruby, AIR, Gears etc)

Scrolling options for table viewport

Fully internationalisable

jQuery UI ThemeRoller support

Rock solid - backed by a suite of 2600+ unit tests

Wide variety of plug-ins inc. TableTools, FixedColumns, KeyTable and more

Dynamic creation of tables

Ajax auto loading of data

Custom DOM positioning

Single column filtering

Alternative pagination types

Non-destructive DOM interaction

Sorting column(s) highlighting

Advanced data source options

Extensive plug-in support

Sorting, type detection, API functions, pagination and filtering

Fully themeable by CSS

Solid documentation

110+ pre-built examples

Full support for Adobe AIR

How many concurrent requests does a single Flask process receive?

Currently there is a far simpler solution than the ones already provided. When running your application you just have to pass along the threaded=True parameter to the app.run() call, like:

app.run(host="your.host", port=4321, threaded=True)

Another option as per what we can see in the werkzeug docs, is to use the processes parameter, which receives a number > 1 indicating the maximum number of concurrent processes to handle:

  • threaded – should the process handle each request in a separate thread?
  • processes – if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes.

Something like:

app.run(host="your.host", port=4321, processes=3) #up to 3 processes

More info on the run() method here, and the blog post that led me to find the solution and api references.


Note: on the Flask docs on the run() methods it's indicated that using it in a Production Environment is discouraged because (quote): "While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well."

However, they do point to their Deployment Options page for the recommended ways to do this when going for production.

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Increasing number of max-connections will not solve the problem.

We were experiencing the same situation on our servers. This is what happens

User open a page/view, that connect to the database, query the database, still query(queries) were not finished and user leave the page or move to some other page. So the connection that was open, will remains open, and keep increasing number of connections, if there are more users connecting with the db and doing something similar.

You can set interactive_timeout MySQL, bydefault it is 28800 (8hours) to 1 hour

SET interactive_timeout=3600

PHP's array_map including keys

I'd do something like this:

<?php

/**
 * array_map_kv()
 *   An array mapping function to map with both keys and values.
 *
 * @param $callback callable
 *   A callback function($key, $value) for mapping values.
 * @param $array array
 *   An array for mapping.
 */
function array_map_kv(callable $callback, array $array) {
  return array_map(
    function ($key) use ($callback, $array) {
      return $callback($key, $array[$key]); // $callback($key, $value)
    },
    array_keys($array)
  );
}

// use it
var_dump(array_map_kv(function ($key, $value) {
  return "{$key} loves {$value}";
}, array(
  "first_key" => "first_value",
  "second_key" => "second_value",
)));

?>

Results:

array(2) {
  [0]=>
  string(27) "first_key loves first_value"
  [1]=>
  string(29) "second_key loves second_value"
}

Deep cloning objects

Simple extension method to copy all the public properties. Works for any objects and does not require class to be [Serializable]. Can be extended for other access level.

public static void CopyTo( this object S, object T )
{
    foreach( var pS in S.GetType().GetProperties() )
    {
        foreach( var pT in T.GetType().GetProperties() )
        {
            if( pT.Name != pS.Name ) continue;
            ( pT.GetSetMethod() ).Invoke( T, new object[] 
            { pS.GetGetMethod().Invoke( S, null ) } );
        }
    };
}

Write to file, but overwrite it if it exists

The >> redirection operator will append lines to the end of the specified file, where-as the single greater than > will empty and overwrite the file.

echo "text" > 'Users/Name/Desktop/TheAccount.txt'

How to install a python library manually

You need to install it in a directory in your home folder, and somehow manipulate the PYTHONPATH so that directory is included.

The best and easiest is to use virtualenv. But that requires installation, causing a catch 22. :) But check if virtualenv is installed. If it is installed you can do this:

$ cd /tmp
$ virtualenv foo
$ cd foo
$ ./bin/python

Then you can just run the installation as usual, with /tmp/foo/python setup.py install. (Obviously you need to make the virtual environment in your a folder in your home directory, not in /tmp/foo. ;) )

If there is no virtualenv, you can install your own local Python. But that may not be allowed either. Then you can install the package in a local directory for packages:

$ wget http://pypi.python.org/packages/source/s/six/six-1.0b1.tar.gz#md5=cbfcc64af1f27162a6a6b5510e262c9d
$ tar xvf six-1.0b1.tar.gz 
$ cd six-1.0b1/
$ pythonX.X setup.py   install --install-dir=/tmp/frotz

Now you need to add /tmp/frotz/pythonX.X/site-packages to your PYTHONPATH, and you should be up and running!

Bash script to check running process

I need to do this from time to time and end up hacking the command line until it works.

For example, here I want to see if I have any SSH connections, (the 8th column returned by "ps" is the running "path-to-procname" and is filtered by "awk":

ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g'

Then I put it in a shell-script, ("eval"-ing the command line inside of backticks), like this:

#!/bin/bash

VNC_STRING=`ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g'`

if [ ! -z "$VNC_STRING" ]; then
    echo "The VNC STRING is not empty, therefore your process is running."
fi

The "sed" part trims the path to the exact token and might not be necessary for your needs.

Here's my example I used to get your answer. I wrote it to automatically create 2 SSH tunnels and launch a VNC client for each.

I run it from my Cygwin shell to do admin to my backend from my windows workstation, so I can jump to UNIX/LINUX-land with one command, (this also assumes the client rsa keys have already been "ssh-copy-id"-ed and are known to the remote host).

It's idempotent in that each proc/command only fires when their $VAR eval's to an empty string.

It appends " | wc -l" to store the number of running procs that match, (i.e., number of lines found), instead of proc-name for each $VAR to suit my needs. I keep the "echo" statements so I can re-run and diagnose the state of both connections.

#!/bin/bash

SSH_COUNT=`eval ps | awk -e '{ print $8 }' | grep ssh | sed -e 's/.*\///g' | wc -l`
VNC_COUNT=`eval ps | awk -e '{ print $8 }' | grep vnc | sed -e 's/.*\///g' | wc -l`

if  [ $SSH_COUNT = "2" ]; then
    echo "There are already 2 SSH tunnels."
elif  [ $SSH_COUNT = "1" ]; then
    echo "There is only 1 SSH tunnel."
elif [ $SSH_COUNT = "0" ]; then
    echo "connecting 2 SSH tunnels."
    ssh -L 5901:localhost:5901 -f -l USER1 HOST1 sleep 10;
    ssh -L 5904:localhost:5904 -f -l USER2 HOST2 sleep 10;
fi

if  [ $VNC_COUNT = "2" ]; then
    echo "There are already 2 VNC sessions."
elif  [ $VNC_COUNT = "1" ]; then
    echo "There is only 1 VNC session."
elif [ $VNC_COUNT = "0" ]; then
    echo "launching 2 vnc sessions."
    vncviewer.exe localhost:1 &
    vncviewer.exe localhost:4 &
fi

This is very perl-like to me and possibly more unix utils than true shell scripting. I know there are lots of "MAGIC" numbers and cheezy hard-coded values but it works, (I think I'm also in poor taste for using so much UPPERCASE too). Flexibility can be added with some cmd-line args to make this more versatile but I wanted to share what worked for me. Please improve and share. Cheers.

How to sort a list of lists by a specific index of the inner list?

I think lambda function can solve your problem.

old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]

#let's assume we want to sort lists by last value ( old_list[2] )
new_list = sorted(old_list, key=lambda x: x[2])

#Resulst of new_list will be:

[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]

Rails where condition using NOT NIL

It's not a bug in ARel, it's a bug in your logic.

What you want here is:

Foo.includes(:bar).where(Bar.arel_table[:id].not_eq(nil))

Set IDENTITY_INSERT ON is not working

You might be just missing the column list, as the message says

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] ON

INSERT INTO [MyDB].[dbo].[Equipment]
            (COL1,
             COL2)
SELECT COL1,
       COL2
FROM   [MyDBQA].[dbo].[Equipment]

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] OFF 

How to insert an item into an array at a specific index (JavaScript)?

I tried this and it is working fine!

var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);

Index is the position where you want to insert or delete the element. 0 i.e. the second parameters defines the number of element from the index to be removed item are the new entries which you want to make in array. It can be one or more than one.

initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");

store and retrieve a class object in shared preference

Yes we can do this using Gson

Download Working code from GitHub

SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);

For save

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

For get

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Update1

The latest version of GSON can be downloaded from github.com/google/gson.

Update2

If you are using Gradle/Android Studio just put following in build.gradle dependencies section -

implementation 'com.google.code.gson:gson:2.6.2'

How to dismiss the dialog with click on outside of the dialog?

Call dialog.setCancelable(false); from your activity/fragment.

Compiler error "archive for required library could not be read" - Spring Tool Suite

When I got an error saying "archive for required library could not be read," I solved it by removing the JARS in question from the Build Path of the project, and then using "Add External Jars" to add them back in again (navigating to the same folder that they were in). Using the "Add Jars" button wouldn't work, and the error would still be there. But using "Add External Jars" worked.

Responsive table handling in Twitter Bootstrap

Bootstrap 3 now has Responsive tables out of the box. Hooray! :)

You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive

Add a <div class="table-responsive"> surrounding your table and you should be good to go:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

To make it work on all layouts you can do this:

.table-responsive
{
    overflow-x: auto;
}

Access Https Rest Service using Spring RestTemplate

You need to configure a raw HttpClient with SSL support, something like this:

@Test
public void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() 
throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient
      = HttpClients.custom()
        .setSSLHostnameVerifier(new NoopHostnameVerifier())
        .build();
    HttpComponentsClientHttpRequestFactory requestFactory 
      = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    ResponseEntity<String> response 
      = new RestTemplate(requestFactory).exchange(
      urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}

font: Baeldung

How to fix HTTP 404 on Github Pages?

Go to settings section of your repository and choose master branch at the Source section and click save button after that refresh the page and you will be able to see the link of your page!.

Find an element by class name, from a known parent element

You were close. You can do:

var element = $("#parentDiv").find(".myClassNameOfInterest");

Alternatively, you can do:

var element = $(".myClassNameOfInterest", "#parentDiv");

...which sets the context of the jQuery object to the #parentDiv.

EDIT:

Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest instead of just .myClassNameOfInterest.

How to convert currentTimeMillis to a date in Java?

You can try java.time api;

        Instant date = Instant.ofEpochMilli(1549362600000l);
        LocalDateTime utc = LocalDateTime.ofInstant(date, ZoneOffset.UTC);

What is __stdcall?

I agree that all the answers so far are correct, but here is the reason. Microsoft's C and C++ compilers provide various calling conventions for (intended) speed of function calls within an application's C and C++ functions. In each case, the caller and callee must agree on which calling convention to use. Now, Windows itself provides functions (APIs), and those have already been compiled, so when you call them you must conform to them. Any calls to Windows APIs, and callbacks from Windows APIs, must use the __stdcall convention.

What is the difference between .*? and .* regular expressions?

Let's say you have:

<a></a>

<(.*)> would match a></a where as <(.*?)> would match a. The latter stops after the first match of >. It checks for one or 0 matches of .* followed by the next expression.

The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

How to store array or multiple values in one column

Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:

create table foo (
  bar  int[] default '{}'
);

select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]

create index on foo using gin (bar); -- allows to use an index in the above query

But as the prior answer suggests, it will be better to normalize properly.

Rename specific column(s) in pandas

There are at least five different ways to rename specific columns in pandas, and I have listed them below along with links to the original answers. I also timed these methods and found them to perform about the same (though YMMV depending on your data set and scenario). The test case below is to rename columns A M N Z to A2 M2 N2 Z2 in a dataframe with columns A to Z containing a million rows.

# Import required modules
import numpy as np
import pandas as pd
import timeit

# Create sample data
df = pd.DataFrame(np.random.randint(0,9999,size=(1000000, 26)), columns=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))

# Standard way - https://stackoverflow.com/a/19758398/452587
def method_1():
    df_renamed = df.rename(columns={'A': 'A2', 'M': 'M2', 'N': 'N2', 'Z': 'Z2'})

# Lambda function - https://stackoverflow.com/a/16770353/452587
def method_2():
    df_renamed = df.rename(columns=lambda x: x + '2' if x in ['A', 'M', 'N', 'Z'] else x)

# Mapping function - https://stackoverflow.com/a/19758398/452587
def rename_some(x):
    if x=='A' or x=='M' or x=='N' or x=='Z':
        return x + '2'
    return x
def method_3():
    df_renamed = df.rename(columns=rename_some)

# Dictionary comprehension - https://stackoverflow.com/a/58143182/452587
def method_4():
    df_renamed = df.rename(columns={col: col + '2' for col in df.columns[
        np.asarray([i for i, col in enumerate(df.columns) if 'A' in col or 'M' in col or 'N' in col or 'Z' in col])
    ]})

# Dictionary comprehension - https://stackoverflow.com/a/38101084/452587
def method_5():
    df_renamed = df.rename(columns=dict(zip(df[['A', 'M', 'N', 'Z']], ['A2', 'M2', 'N2', 'Z2'])))

print('Method 1:', timeit.timeit(method_1, number=10))
print('Method 2:', timeit.timeit(method_2, number=10))
print('Method 3:', timeit.timeit(method_3, number=10))
print('Method 4:', timeit.timeit(method_4, number=10))
print('Method 5:', timeit.timeit(method_5, number=10))

Output:

Method 1: 3.650640267
Method 2: 3.163998427
Method 3: 2.998530871
Method 4: 2.9918436889999995
Method 5: 3.2436501520000007

Use the method that is most intuitive to you and easiest for you to implement in your application.

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

I had a similar problem, trying to capture a 'shift+click' but since I was using a third party control with a callback rather than the standard click handler, I didn't have access to the event object and its associated e.shiftKey.

I ended up handling the mouse down event to record the shift-ness and then using it later in my callback.

    var shiftHeld = false;
    $('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });

Posted just in case someone else ends up here searching for a solution to this problem.

Extracting Nupkg files using command line

did the same thing like this:

clear
cd PACKAGE_DIRECTORY

function Expand-ZIPFile($file, $destination)
{
    $shell = New-Object -ComObject Shell.Application
    $zip = $shell.NameSpace($file)
    foreach($item in $zip.items())
    {
        $shell.Namespace($destination).copyhere($item)
    }
}

Dir *.nupkg | rename-item -newname {  $_.name  -replace ".nupkg",".zip"  }

Expand-ZIPFile "Package.1.0.0.zip" “DESTINATION_PATH”

get next and previous day with PHP

always make sure to have set your default timezone

date_default_timezone_set('Europe/Berlin');

create DateTime instance, holding the current datetime

$datetime = new DateTime();

create one day interval

$interval = new DateInterval('P1D');

modify the DateTime instance

$datetime->sub($interval);

display the result, or print_r($datetime); for more insight

echo $datetime->format('Y-m-d');

TIP:

If you don't want to change the default timezone, use the DateTimeZone class instead.

$myTimezone = new DateTimeZone('Europe/Berlin');
$datetime->setTimezone($myTimezone); 

or just include it inside the constructor in this form new DateTime("now", $myTimezone);

How to perform mouseover function in Selenium WebDriver using Java?

Check this example how we could implement this.

enter image description here

public class HoverableDropdownTest {

    private WebDriver driver;
    private Actions action;

    //Edit: there may have been a typo in the '- >' expression (I don't really want to add this comment but SO insist on ">6 chars edit"...
    Consumer < By > hover = (By by) -> {
        action.moveToElement(driver.findElement(by))
              .perform();
    };

    @Test
    public void hoverTest() {
        driver.get("https://www.bootply.com/render/6FC76YQ4Nh");

        hover.accept(By.linkText("Dropdown"));
        hover.accept(By.linkText("Dropdown Link 5"));
        hover.accept(By.linkText("Dropdown Submenu Link 5.4"));
        hover.accept(By.linkText("Dropdown Submenu Link 5.4.1"));
    }

    @BeforeTest
    public void setupDriver() {
        driver = new FirefoxDriver();
        action = new Actions(driver);
    }

    @AfterTest
    public void teardownDriver() {
        driver.quit();
    }

}

For detailed answer, check here - http://www.testautomationguru.com/selenium-webdriver-automating-hoverable-multilevel-dropdowns/

How to do constructor chaining in C#

You use standard syntax (using this like a method) to pick the overload, inside the class:

class Foo 
{
    private int id;
    private string name;

    public Foo() : this(0, "") 
    {
    }

    public Foo(int id, string name) 
    {
        this.id = id;
        this.name = name;
    }

    public Foo(int id) : this(id, "") 
    {
    }

    public Foo(string name) : this(0, name) 
    {
    }
}

then:

Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");

Note also:

  • you can chain to constructors on the base-type using base(...)
  • you can put extra code into each constructor
  • the default (if you don't specify anything) is base()

For "why?":

  • code reduction (always a good thing)
  • necessary to call a non-default base-constructor, for example:

    SomeBaseType(int id) : base(id) {...}
    

Note that you can also use object initializers in a similar way, though (without needing to write anything):

SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
         z = new SomeType { DoB = DateTime.Today };

Config Error: This configuration section cannot be used at this path

Browse to “C:\Windows\System32\inetsrv\config” (you will need administrator rights here) Open applicationHost.config

Note: In IISExpress and Visual Studio 2015 the applicationHost.config is stored in $(solutionDir).vs\config\applicationhost.config

Find the section that showed up in the “config source” part of the error message page. For me this has typically been “modules” or “handlers”

Change the overrideModeDefault attribute to be Allow

So the whole line now looks like:

<section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Allow" />

After saving the file, the page loaded up fine in my browser.

Warning: Editing applicationHost.config on 64-bit Windows

box-shadow on bootstrap 3 container

For those wanting the box-shadow on the col-* container itself and not on the .container, you can add another div just inside the col-* element, and add the shadow to that. This element will not have the padding, and therefor not interfere.

The first image has the box-shadow on the col-* element. Because of the 15px padding on the col element, the shadow is pushed to the outside of the div element rather than on the visual edges of it.

box-shadow on col-* element

<div class="col-md-4" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
    <div class="thumbnail">
        {!! HTML::image('images/sampleImage.png') !!}
    </div>
</div>

The second image has a wrapper div with the box-shadow on it. This will place the box-shadow on the visual edges of the element.

box-shadow on wrapper div

<div class="col-md-4">
    <div id="wrapper-div" style="box-shadow: 0px 2px 25px rgba(0, 0, 0, .25);">
        <div class="thumbnail">
            {!! HTML::image('images/sampleImage.png') !!}
        </div>
    </div>
</div>

Format string to a 3 digit number

(Can't comment yet with enough reputation , let me add a sidenote)

Just in case your output need to be fixed length of 3-digit , i.e. for number run up to 1000 or more (reserved fixed length), don't forget to add mod 1000 on it .

yourNumber=1001;
yourString= yourNumber.ToString("D3");        // "1001" 
yourString= (yourNumber%1000).ToString("D3"); // "001" truncated to 3-digit as expected

Trail sample on Fiddler https://dotnetfiddle.net/qLrePt

matplotlib colorbar in each subplot

Please have a look at this matplotlib example page. There it is shown how to get the following plot with four individual colorbars for each subplot: enter image description here

I hope this helps.
You can further have a look here, where you can find a lot of what you can do with matplotlib.

Make Adobe fonts work with CSS3 @font-face in IE9

As a Mac user, I was unable to use the MS-DOS and Windows command line tools that were mentioned to fix the font embedding permission. However, I found out that you can fix this using FontLab to set the permission to 'Everything is allowed'. I hope this recipe on how to set the font permission to Installable on Mac OS X is useful for others as well.

Calculating Time Difference

from time import time

start_time = time()
...

end_time = time()
seconds_elapsed = end_time - start_time

hours, rest = divmod(seconds_elapsed, 3600)
minutes, seconds = divmod(rest, 60)

Can't create handler inside thread which has not called Looper.prepare()

The error is self-explanatory... doInBackground() runs on a background thread which, since it is not intended to loop, is not connected to a Looper.

You most likely don't want to directly instantiate a Handler at all... whatever data your doInBackground() implementation returns will be passed to onPostExecute() which runs on the UI thread.

   mActivity = ThisActivity.this; 

    mActivity.runOnUiThread(new Runnable() {
     public void run() {
     new asyncCreateText().execute();
     }
   });

ADDED FOLLOWING THE STACKTRACE APPEARING IN QUESTION:

Looks like you're trying to start an AsyncTask from a GL rendering thread... don't do that cos they won't ever Looper.loop() either. AsyncTasks are really designed to be run from the UI thread only.

The least disruptive fix would probably be to call Activity.runOnUiThread() with a Runnable that kicks off your AsyncTask.

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

c# how to add byte to byte array

As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:

var mahByteArray = new ArrayList<byte>();

If you have a byte array from elsewhere, you can use the AddRange function.

mahByteArray.AddRange(mahOldByteArray);

Then you can use Add() and Insert() to add elements.

mahByteArray.Add(0x00); // Adds 0x00 to the end.
mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.

Need it back in an array? .ToArray() has you covered!

mahOldByteArray = mahByteArray.ToArray();

Write to custom log file from a Bash script

logger logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:

local7.*   -/var/log/mycustomlog

and restart syslog. Then you can log like this:

logger -p local7.info "information message"
logger -p local7.err "error message"

and the messages will appear in the desired logfile with the correct log level.

Without making changes to the syslog configuration you could use logger like this:

logger -s "foo bar" >> /var/log/mycustomlog

That would instruct logger to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice).

'AND' vs '&&' as operator

Precedence differs between && and and (&& has higher precedence than and), something that causes confusion when combined with a ternary operator. For instance,

$predA && $predB ? "foo" : "bar"

will return a string whereas

$predA and $predB ? "foo" : "bar"

will return a boolean.

Bundling data files with PyInstaller (--onefile)

Using the excellent answer from Max and This post about adding extra data files like images or sound & my own research/testing, I've figured out what I believe is the easiest way to add such files.

If you would like to see a live example, my repository is here on GitHub.

Note: this is for compiling using the --onefile or -F command with pyinstaller.

My environment is as follows.


Solving the problem in 2 steps

To solve the issue we need to specifically tell Pyinstaller that we have extra files that need to be "bundled" with the application.

We also need to be using a 'relative' path, so the application can run properly when it's running as a Python Script or a Frozen EXE.

With that being said we need a function that allows us to have relative paths. Using the function that Max Posted we can easily solve the relative pathing.

def img_resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

We would use the above function like this so the application icon shows up when the app is running as either a Script OR Frozen EXE.

icon_path = img_resource_path("app/img/app_icon.ico")
root.wm_iconbitmap(icon_path)

The next step is that we need to instruct Pyinstaller on where to find the extra files when it's compiling so that when the application is run, they get created in the temp directory.

We can solve this issue two ways as shown in the documentation, but I personally prefer managing my own .spec file so that's how we're going to do it.

First, you must already have a .spec file. In my case, I was able to create what I needed by running pyinstaller with extra args, you can find extra args here. Because of this, my spec file may look a little different than yours but I'm posting all of it for reference after I explain the important bits.

added_files is essentially a List containing Tuple's, in my case I'm only wanting to add a SINGLE image, but you can add multiple ico's, png's or jpg's using ('app/img/*.ico', 'app/img') You may also create another tuple like soadded_files = [ (), (), ()] to have multiple imports

The first part of the tuple defines what file or what type of file's you would like to add as well as where to find them. Think of this as CTRL+C

The second part of the tuple tells Pyinstaller, to make the path 'app/img/' and place the files in that directory RELATIVE to whatever temp directory gets created when you run the .exe. Think of this as CTRL+V

Under a = Analysis([main..., I've set datas=added_files, originally it used to be datas=[] but we want out the list of imports to be, well, imported so we pass in our custom imports.

You don't need to do this unless you want a specific icon for the EXE, at the bottom of the spec file I'm telling Pyinstaller to set my application icon for the exe with the option icon='app\\img\\app_icon.ico'.

added_files = [
    ('app/img/app_icon.ico','app/img/')
]
a = Analysis(['main.py'],
             pathex=['D:\\Github Repos\\Processes-Killer\\Process Killer'],
             binaries=[],
             datas=added_files,
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='Process Killer',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=True , uac_admin=True, icon='app\\img\\app_icon.ico')

Compiling to EXE

I'm very lazy; I don't like typing things more than I have to. I've created a .bat file that I can just click. You don't have to do this, this code will run in a command prompt shell just fine without it.

Since the .spec file contains all of our compiling settings & args (aka options) we just have to give that .spec file to Pyinstaller.

pyinstaller.exe "Process Killer.spec"

How do I delete an exported environment variable?

As mentioned in the above answers, unset GNUPLOT_DRIVER_DIR should work if you have used export to set the variable. If you have set it permanently in ~/.bashrc or ~/.zshrc then simply removing it from there will work.

How do I move to end of line in Vim?

I can't see hotkey for macbook for use vim in standard terminal. Hope it will help someone. For macOS users (tested on macbook pro 2018):

fn + ? - move to beginning line

fn + ? - move to end line

fn + ? - move page up

fn + ? - move page down

fn + g - move the cursor to the beginning of the document

fn + shift + g - move the cursor to the end of the document

For the last two commands sometime needs to tap twice.

Python urllib2 Basic Auth Problem

(copy-paste/adapted from https://stackoverflow.com/a/24048772/1733117).

First you can subclass urllib2.BaseHandler or urllib2.HTTPBasicAuthHandler, and implement http_request so that each request has the appropriate Authorization header.

import urllib2
import base64

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

Then if you are lazy like me, install the handler globally

api_url = "http://api.foursquare.com/"
api_username = "johndoe"
api_password = "some-cryptic-value"

auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(
    realm=None, # default realm.
    uri=api_url,
    user=api_username,
    passwd=api_password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)

How to give a Blob uploaded as FormData a file name?

Since you're getting the data pasted to clipboard, there is no reliable way of knowing the origin of the file and its properties (including name).

Your best bet is to come up with a file naming scheme of your own and send along with the blob.

form.append("filename",getFileName());
form.append("blob",blob);

function getFileName() {
 // logic to generate file names
}

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

I had the same problem, but I understand the VMware service is the problem. VMware host service and Apache service conflict together.

To Solve it » Run your task manager » in services tab find VMwareHostd » then right click and stop it » every thing have been solved.

Angularjs on page load call function

    var someVr= element[0].querySelector('#showSelector');
        myfunction(){
        alert("hi");
        }   
        angular.element(someVr).ready(function () {
           myfunction();
            });

This will do the job.

How to create a new branch from a tag?

I have resolve the problem as below 1. Get the tag from your branch 2. Write below command

Example: git branch <Hotfix branch> <TAG>
    git branch hotfix_4.4.3 v4.4.3
    git checkout hotfix_4.4.3

or you can do with other command

git checkout -b <Hotfix branch> <TAG>
-b stands for creating new branch to local 

once you ready with your hotfix branch, It's time to move that branch to github, you can do so by writing below command

git push --set-upstream origin hotfix_4.4.3

How to change the text on the action bar

Kotlin

You can do it programmatically in Kotlin this way. You just ignore it if "supportActionBar" is null:

    supportActionBar?.setTitle(R.string.my_text)
    supportActionBar?.title = "My text"

Or this way. It throws an exception if "supportActionBar" is null.

    supportActionBar!!.setTitle(R.string.my_text)
    supportActionBar!!.title = "My text"

How to check if a map contains a key in Go?

    var d map[string]string
    value, ok := d["key"]
    if ok {
        fmt.Println("Key Present ", value)
    } else {
        fmt.Println(" Key Not Present ")
    }

How do I check what version of Python is running my script?

I like sys.hexversion for stuff like this.

>>> import sys
>>> sys.hexversion
33883376
>>> '%x' % sys.hexversion
'20504f0'
>>> sys.hexversion < 0x02060000
True

Filtering a data frame by values in a column

Thought I'd update this with a dplyr solution

library(dplyr)    
filter(studentdata, Drink == "water")

find filenames NOT ending in specific extensions on Unix?

Or without ( and the need to escape it:

find . -not -name "*.exe" -not -name "*.dll"

and to also exclude the listing of directories

find . -not -name "*.exe" -not -name "*.dll" -not -type d

or in positive logic ;-)

find . -not -name "*.exe" -not -name "*.dll" -type f

The term "Add-Migration" is not recognized

It's so simple.

Just install Microsoft.EntityFrameworkCore.Tools package from nuget:

Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.5

You can also use this link to install the latest version: Nuget package link

.NET CLI command:

dotnet add package Microsoft.EntityFrameworkCore.Tools

What is an attribute in Java?

An abstract class is a type of class that can only be used as a base class for another class; such thus cannot be instantiated. To make a class abstract, the keyword abstract is used. Abstract classes may have one or more abstract methods that only have a header line (no method body). The method header line ends with a semicolon (;). Any class that is derived from the base class can define the method body in a way that is consistent with the header line using all the designated parameters and returning the correct data type (if the return type is not void). An abstract method acts as a place holder; all derived classes are expected to override and complete the method.

Example in Java

abstract public class Shape

{

double area;

public abstract double getArea();

}

How to convert NSData to byte array in iPhone?

That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).

The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:

[data getBytes:&byteData length:len];

Which fills the array you have allocated with data from the NSData object.

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Don't know if this will be everybody's answer, but after some digging, here's what we came up with.

The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent

After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).

The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.

So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.

Excel VBA Run Time Error '424' object required

Private Sub CommandButton1_Click()

    Workbooks("Textfile_Receiving").Sheets("menu").Range("g1").Value = PROV.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g2").Value = MUN.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g3").Value = CAT.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g4").Value = Label5.Caption

    Me.Hide

    Run "filename"

End Sub

Private Sub MUN_Change()
    Dim r As Integer
    r = 2

    While Range("m" & CStr(r)).Value <> ""
        If Range("m" & CStr(r)).Value = MUN.Text Then
        Label5.Caption = Range("n" & CStr(r)).Value
        End If
        r = r + 1
    Wend

End Sub

Private Sub PROV_Change()
    If PROV.Text = "LAGUNA" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M26:M56"
    ElseIf PROV.Text = "CAVITE" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M2:M25"
    ElseIf PROV.Text = "QUEZON" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M57:M97"
    End If
End Sub

C char array initialization

Interestingly enough, it is possible to initialize arrays in any way at any time in the program, provided they are members of a struct or union.

Example program:

#include <stdio.h>

struct ccont
{
  char array[32];
};

struct icont
{
  int array[32];
};

int main()
{
  int  cnt;
  char carray[32] = { 'A', 66, 6*11+1 };    // 'A', 'B', 'C', '\0', '\0', ...
  int  iarray[32] = { 67, 42, 25 };

  struct ccont cc = { 0 };
  struct icont ic = { 0 };

  /*  these don't work
  carray = { [0]=1 };           // expected expression before '{' token
  carray = { [0 ... 31]=1 };    // (likewise)
  carray = (char[32]){ [0]=3 }; // incompatible types when assigning to type 'char[32]' from type 'char *'
  iarray = (int[32]){ 1 };      // (likewise, but s/char/int/g)
  */

  // but these perfectly work...
  cc = (struct ccont){ .array='a' };        // 'a', '\0', '\0', '\0', ...
  // the following is a gcc extension, 
  cc = (struct ccont){ .array={ [0 ... 2]='a' } };  // 'a', 'a', 'a', '\0', '\0', ...
  ic = (struct icont){ .array={ 42,67 } };      // 42, 67, 0, 0, 0, ...
  // index ranges can overlap, the latter override the former
  // (no compiler warning with -Wall -Wextra)
  ic = (struct icont){ .array={ [0 ... 1]=42, [1 ... 2]=67 } }; // 42, 67, 67, 0, 0, ...

  for (cnt=0; cnt<5; cnt++)
    printf("%2d %c %2d %c\n",iarray[cnt], carray[cnt],ic.array[cnt],cc.array[cnt]);

  return 0;
}

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

simplest options ls :

dict  = {'A':a,'B':b}
df = pd.DataFrame(dict, index = np.arange(1) )

anaconda/conda - install a specific package version

There is no version 1.3.0 for rope. 1.3.0 refers to the package cached-property. The highest available version of rope is 0.9.4.

You can install different versions with conda install package=version. But in this case there is only one version of rope so you don't need that.

The reason you see the cached-property in this listing is because it contains the string "rope": "cached-p rope erty"

py35_0 means that you need python version 3.5 for this specific version. If you only have python3.4 and the package is only for version 3.5 you cannot install it with conda.

I am not quite sure on the defaults either. It should be an indication that this package is inside the default conda channel.

Is CSS Turing complete?

The fundamental issue here is that any machine written in HTML+CSS cannot evaluate infinitely many steps (i.e there can be no "real" recursion) unless the code is infinitely long. And the question will this machine reach configuration H in n steps or less is always answerable if n is finite.

How to send a message to a particular client with socket.io

In a project of our company we are using "rooms" approach and it's name is a combination of user ids of all users in a conversation as a unique identifier (our implementation is more like facebook messenger), example:

|id | name |1 | Scott |2 | Susan

"room" name will be "1-2" (ids are ordered Asc.) and on disconnect socket.io automatically cleans up the room

this way you send messages just to that room and only to online (connected) users (less packages sent throughout the server).

Make selected block of text uppercase

At Sep 19 2018, these lines worked for me:

File-> Preferences -> Keyboard Shortcuts.

An editor will appear with keybindings.json file. Place the following JSON in there and save.

// Place your key bindings in this file to overwrite the defaults
[
    {
        "key": "ctrl+shift+u",
        "command": "editor.action.transformToUppercase",
        "when": "editorTextFocus"
    },
    {
        "key": "ctrl+shift+l",
        "command": "editor.action.transformToLowercase",
        "when": "editorTextFocus"
    },

]

How can I call a WordPress shortcode within a template?

Make sure to enable the use of shortcodes in text widgets.

// To enable the use, add this in your *functions.php* file:
add_filter( 'widget_text', 'do_shortcode' );

// and then you can use it in any PHP file:  
<?php echo do_shortcode('[YOUR-SHORTCODE-NAME/TAG]'); ?>

Check the documentation for more.

How to print Two-Dimensional Array like table

You need to print a new line after each row... System.out.print("\n"), or use println, etc. As it stands you are just printing nothing - System.out.print(""), replace print with println or "" with "\n".

How to compare data between two table in different databases using Sql Server 2008?

I'v done things like this using the Checksum(*) function

In essance it creates a row level checksum on all the columns data, you could then compare the checksum of each row for each table to each other, use a left join, to find rows that are different.

Hope that made sense...

Better with an example....

select *
from 
( select checksum(*) as chk, userid as k from UserAccounts) as t1
left join 
( select checksum(*) as chk, userid as k from UserAccounts) as t2 on t1.k = t2.k
where t1.chk <> t2.chk 

jQuery Datepicker localization

datepicker in Finnish (Käännös suomeksi)

$.datepicker.regional['fi'] = {
  closeText: "Valmis", // Display text for close link
  prevText: "Edel", // Display text for previous month link
  nextText: "Seur", // Display text for next month link
  currentText: "Tänään", // Display text for current month link
  monthNames: [ "Tammikuu","Helmikuu","Maaliskuu","Huhtikuu","Toukokuu","Kesäkuu",
  "Heinäkuu","Elokuu","Syyskuu","Lokakuu","Marraskuu","Joulukuu" ], // Names of months for drop-down and formatting
  monthNamesShort: [ "Tam", "Hel", "Maa", "Huh", "Tou", "Kes", "Hei", "Elo", "Syy", "Lok", "Mar", "Jou" ], // For formatting
  dayNames: [ "Sunnuntai", "Maanantai", "Tiistai", "Keskiviikko", "Torstai", "Perjantai", "Lauantai" ], // For formatting
  dayNamesShort: [ "Sun", "Maa", "Tii", "Kes", "Tor", "Per", "Lau" ], // For formatting
  dayNamesMin: [ "Su","Ma","Ti","Ke","To","Pe","La" ], // Column headings for days starting at Sunday
  weekHeader: "Vk", // Column header for week of the year
  dateFormat: "mm/dd/yy", // See format options on parseDate
  firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
  isRTL: false, // True if right-to-left language, false if left-to-right
  showMonthAfterYear: false, // True if the year select precedes month, false for month then year
  yearSuffix: "" // Additional text to append to the year in the month headers
  };

What is the use of "object sender" and "EventArgs e" parameters?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.

Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Example:

protected void btn_Click (object sender, EventArgs e){
   Button btn = sender as Button;
   btn.Text = "clicked!";
}

Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked

ImportError: No module named scipy

Try to install it as a python package using pip as follows

$ sudo apt-get install python-scipy

If you want to run a python 3.x script, install scipy by:

$ pip3 install scipy
Otherwise install it by:
$ pip install scipy

How to return a dictionary | Python

def prepare_table_row(row):
    lst = [i.text for i in row if i != u'\n']
    return dict(rank = int(lst[0]),
                grade = str(lst[1]),
                channel=str(lst[2])),
                videos = float(lst[3].replace(",", " ")),
                subscribers = float(lst[4].replace(",", "")),
                views = float(lst[5].replace(",", "")))

Insertion Sort vs. Selection Sort

Both insertion sort and selection sort have an outer loop (over every index), and an inner loop (over a subset of indices). Each pass of the inner loop expands the sorted region by one element, at the expense of the unsorted region, until it runs out of unsorted elements.

The difference is in what the inner loop does:

  • In selection sort, the inner loop is over the unsorted elements. Each pass selects one element, and moves it to its final location (at the current end of the sorted region).

  • In insertion sort, each pass of the inner loop iterates over the sorted elements. Sorted elements are displaced until the loop finds the correct place to insert the next unsorted element.

So, in a selection sort, sorted elements are found in output order, and stay put once they are found. Conversely, in an insertion sort, the unsorted elements stay put until consumed in input order, while elements of the sorted region keep getting moved around.

As far as swapping is concerned: selection sort does one swap per pass of the inner loop. Insertion sort typically saves the element to be inserted as temp before the inner loop, leaving room for the inner loop to shift sorted elements up by one, then copies temp to the insertion point afterwards.

Swift 3 - Comparing Date objects

SWIFT 3: Don't know if this is what you're looking for. But I compare a string to a current timestamp to see if my string is older that now.

func checkTimeStamp(date: String!) -> Bool {
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.locale = Locale(identifier:"en_US_POSIX")
        let datecomponents = dateFormatter.date(from: date)

        let now = Date()

        if (datecomponents! >= now) {
            return true
        } else {
            return false
        }
    }

To use it:

if (checkTimeStamp(date:"2016-11-21 12:00:00") == false) {
    // Do something
}

How to use Bootstrap modal using the anchor tag for Register?

Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp

Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:

I hope that helps

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

PHP header(Location: ...): Force URL change in address bar

Are you sure the page you are redirecting too doesn't have a redirection within that if no session data is found? That could be your problem

Also yes always add whitespace like @Peter O suggested.

How to include css files in Vue 2

If you want to append this css file to header you can do it using mounted() function of the vue file. See the example.
Note: Assume you can access the css file as http://www.yoursite/assets/styles/vendor.css in the browser.

mounted() {
        let style = document.createElement('link');
        style.type = "text/css";
        style.rel = "stylesheet";
        style.href = '/assets/styles/vendor.css';
        document.head.appendChild(style);
    }

mysql is not recognised as an internal or external command,operable program or batch

MYSQL_HOME variable value:C:\Program Files\MySQL\MySQL Server 5.0\bin %MYSQL_HOME%\bin

See the problem? This resolves to a path of C:\Program Files\MySQL\MySQL Server 5.0\bin\bin

Get loop counter/index using for…of syntax in JavaScript

In ES6, it is good to use for - of loop. You can get index in for of like this

for (let [index, val] of array.entries()) {
        // your code goes here    
}

Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

How to safely call an async method in C# without await

You should first consider making GetStringData an async method and have it await the task returned from MyAsyncMethod.

If you're absolutely sure that you don't need to handle exceptions from MyAsyncMethod or know when it completes, then you can do this:

public string GetStringData()
{
  var _ = MyAsyncMethod();
  return "hello world";
}

BTW, this is not a "common problem". It's very rare to want to execute some code and not care whether it completes and not care whether it completes successfully.

Update:

Since you're on ASP.NET and wanting to return early, you may find my blog post on the subject useful. However, ASP.NET was not designed for this, and there's no guarantee that your code will run after the response is returned. ASP.NET will do its best to let it run, but it can't guarantee it.

So, this is a fine solution for something simple like tossing an event into a log where it doesn't really matter if you lose a few here and there. It's not a good solution for any kind of business-critical operations. In those situations, you must adopt a more complex architecture, with a persistent way to save the operations (e.g., Azure Queues, MSMQ) and a separate background process (e.g., Azure Worker Role, Win32 Service) to process them.

Combine [NgStyle] With Condition (if..else)

Use:

[ngStyle]="{'background-image': 'url(' +1=1 ? ../../assets/img/emp-user.png : ../../assets/img/emp-default.jpg + ')'}"

excel formula to subtract number of days from a date

Say the 1st date is in A1 cell & the 2nd date is in B1 cell

Make sure that the cell type of both A1 & B1 is DATE.
Then simply put the following formula in C1:

=A1-B1

The result of this formula may look funny to you. Then Change the Cell type of C1 to GENERAL.

It will give you the difference in Days.

You can also use this formula to get the remaining days of year or change the formula as you need:

=365-(A1-B1)

Numpy array dimensions

rows = a.shape[0] # 2 
cols = a.shape[1] # 2
a.shape #(2,2)
a.size # rows * cols = 4

Why is visible="false" not working for a plain html table?

For a similar post a long time ago there seems to be issues with making table visibility hidden.

You have two options, one is to use the display:none attribute.

Or two wrap the table in a div and make the div hidden.

<div id="wrapper" style="visibility:hidden">
    <table>
        <tr>
            <td>
            Content
            </td>
        </tr>
    </table>
</div>

Self-references in object literals / initializers

Well, the only thing that I can tell you about are getter:

_x000D_
_x000D_
var foo = {_x000D_
  a: 5,_x000D_
  b: 6,_x000D_
  get c() {_x000D_
    return this.a + this.b;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(foo.c) // 11
_x000D_
_x000D_
_x000D_

This is a syntactic extension introduced by the ECMAScript 5th Edition Specification, the syntax is supported by most modern browsers (including IE9).

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

This could happen if you are not running the command prompt in administrator mode. If you are using windows 7, you can go to run, type cmd and hit Ctrl+Shift+enter. This will open the command prompt in administrator mode. If not, you can also go to start -> all programs -> accessories -> right click command prompt and click 'run as administrator'.

JSON parsing using Gson for Java

    JsonParser parser = new JsonParser();
    JsonObject jo = (JsonObject) parser.parse(data);
    JsonElement je = jo.get("some_array");

    //Parsing back the string as Array
    JsonArray ja = (JsonArray) parser.parse(o.get("some_array").getAsString());
    for (JsonElement jo : ja) {
    JsonObject j = (JsonObject) jo;
        // Your Code, Access json elements as j.get("some_element")
    }

A simple example to parse a JSON like this

{ "some_array" : "[\"some_element\":1,\"some_more_element\":2]" , "some_other_element" : 3 }

C++ STL Vectors: Get iterator from index?

Actutally std::vector are meant to be used as C tab when needed. (C++ standard requests that for vector implementation , as far as I know - replacement for array in Wikipedia) For instance it is perfectly legal to do this folowing, according to me:

int main()
{

void foo(const char *);

sdt::vector<char> vec;
vec.push_back('h');
vec.push_back('e');
vec.push_back('l');
vec.push_back('l');
vec.push_back('o');
vec.push_back('/0');

foo(&vec[0]);
}

Of course, either foo must not copy the address passed as a parameter and store it somewhere, or you should ensure in your program to never push any new item in vec, or requesting to change its capacity. Or risk segmentation fault...

Therefore in your exemple it leads to

vector.insert(pos, &vec[first_index], &vec[last_index]);

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

Spring cannot find bean xml configuration file when it does exist

Beans.xml or file.XML is not placed under proper path. You should add the XML file under the resource folder, if you have a Maven project. src -> main -> java -> resources

Setting a log file name to include current date in Log4j

this example will be creating logger for each minute, if you want to change for each day change the DatePattern value.

<appender name="ASYNC" class="org.apache.log4j.DailyRollingFileAppender">
   <param name="File" value="./applogs/logger.log" />
   <param name="Append" value="true" />
   <param name="Threshold" value="debug" />
   <appendToFile value="true" />
   <param name="DatePattern" value="'.'yyyy_MM_dd_HH_mm"/>
   <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
      <param name="fileNamePattern" value="./applogs/logger_%d{ddMMMyyyy HH:mm:ss}.log"/>
      <param name="rollOver" value="TRUE"/>
   </rollingPolicy>
   <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{ddMMMyyyy HH:mm:ss,SSS}^[%X{l4j_mdc_key}]^[%c{1}]^ %-5p %m%n" />
   </layout>
</appender>
<root>
   <level value="info" />
   <appender-ref ref="ASYNC" />
</root>

Yahoo Finance All Currencies quote API Documentation


| ATTENTION !!! |

| SERVICE SUSPENDED BY YAHOO, solution no longer valid. |

Get from Yahoo a JSON or XML that you can parse from a REST query.

You can exchange from any to any currency and even get the date and time of the query using the YQL (Yahoo Query Language).

https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fd%2Fquotes.csv%3Fe%3D.csv%26f%3Dnl1d1t1%26s%3Dusdeur%3DX%22%3B&format=json&callback=

This will bring an example like below:

{
 "query": {
  "count": 1,
  "created": "2016-02-12T07:07:30Z",
  "lang": "en-US",
  "results": {
   "row": {
    "col0": "USD/EUR",
    "col1": "0.8835",
    "col2": "2/12/2016",
    "col3": "7:07am"
   }
  }
 }
}

You can try the console

I think this does not break any Term of Service as it is a 100% yahoo solution.

problem with <select> and :after with CSS in WebKit

To my experience it simply does not work, unless you are willing to wrap your <select> in some wrapper. But what you can do instead is to use background image SVG. E.g.

    .archive .options select.opt {
    -moz-appearance: none;
    -webkit-appearance: none;
    padding-right: 1.25EM;
    appearance: none;
    position: relative;
    background-color: transparent;
    background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1.1' height='10px' width='15px'%3E%3Ctext x='0' y='10' fill='gray'%3E%E2%96%BE%3C/text%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-size: 1.5EM 1EM;
    background-position: right center;
    background-clip: border-box;
    -moz-background-clip: border-box;
    -webkit-background-clip: border-box;
}

    .archive .options select.opt::-ms-expand {
        display: none;
    }

Just be careful with proper URL-encoding because of IE. You must use charset=utf8 (not just utf8), don't use double-quotes (") to delimit SVG attribute values, use apostrophes (') instead to simplify your life. URL-encode s (%3E). In case you havee to print any non-ASCII characters you have to obtain their UTF-8 representation (e.g. BabelMap can help you with that) and then provide that representation in URL-encoded form - e.g. for ? (U+25BE BLACK DOWN-POINTING SMALL TRIANGLE) UTF-8 representation is \xE2\x96\xBE which is %E2%96%BE when URL-encoded.

How to get DataGridView cell value in messagebox?

You can use the DataGridViewCell.Value Property to retrieve the value stored in a particular cell.

So to retrieve the value of the 'first' selected Cell and display in a MessageBox, you can:

MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());

The above probably isn't exactly what you need to do. If you provide more details we can provide better help.

git remote prune – didn't show as many pruned branches as I expected

When you use git push origin :staleStuff, it automatically removes origin/staleStuff, so when you ran git remote prune origin, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune to get rid of branches you have removed.


So what exactly git remote prune does? Main idea: local branches (not tracking branches) are not touched by git remote prune command and should be removed manually.

Now, a real-world example for better understanding:

You have a remote repository with 2 branches: master and feature. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):

  • refs/heads/master (short name master)
  • refs/heads/feature (short name feature)
  • refs/remotes/origin/master (short name origin/master)
  • refs/remotes/origin/feature (short name origin/feature)

Now, a typical scenario:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including refs/heads/feature, because git remote prune does not remove any refs/heads/* references.

It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge configuration parameter. This parameter is not really required for anything to work (probably except git pull), so it might be missing.

(updated with example & useful info from comments)

HTTP Basic: Access denied fatal: Authentication failed

For my case, I initially tried with

git config --system --unset credential.helper

But I was getting error

error: could not lock config file C:/Program Files/Git/etc/gitconfig: Permission denied

Then tried with

git config --global --unset credential.helper

No error, but still got access denied error while git pulling.

Then went to Control Panel -> Credentials Manager > Windows Credential and deleted git account.

After that when I tried git pull again, it asked for the credentials and a new git account added in Credentails manager.

How to easily consume a web service from PHP

In PHP 5 you can use SoapClient on the WSDL to call the web service functions. For example:

$client = new SoapClient("some.wsdl");

and $client is now an object which has class methods as defined in some.wsdl. So if there was a method called getTime in the WSDL then you would just call:

$result = $client->getTime();

And the result of that would (obviously) be in the $result variable. You can use the __getFunctions method to return a list of all the available methods.

What does "static" mean in C?

If you declare this in a mytest.c file:

static int my_variable;

Then this variable can only be seen from this file. The variable cannot be exported anywhere else.

If you declare inside a function the value of the variable will keep its value each time the function is called.

A static function cannot be exported from outside the file. So in a *.c file, you are hiding the functions and the variables if you declare them static.

convert month from name to number

I know this might seem a simple solution, but why not just use something like this

<select name="month">
  <option value="01">January</option>
  <option value="02">February</option>
  <option selected value="03">March</option>
</select>

The user sees February, but 02 is posted to the database

DBMS_OUTPUT.PUT_LINE not printing

What is "it" in the statement "it just says the procedure is completed"?

By default, most tools do not configure a buffer for dbms_output to write to and do not attempt to read from that buffer after code executes. Most tools, on the other hand, have the ability to do so. In SQL*Plus, you'd need to use the command set serveroutput on [size N|unlimited]. So you'd do something like

SQL> set serveroutput on size 30000;
SQL> exec print_actor_quotes( <<some value>> );

In SQL Developer, you'd go to View | DBMS Output to enable the DBMS Output window, then push the green plus icon to enable DBMS Output for a particular session.

Additionally, assuming that you don't want to print the literal "a.firstNamea.lastName" for every row, you probably want

FOR row IN quote_recs
LOOP
  DBMS_OUTPUT.PUT_LINE( row.firstName || ' ' || row.lastName );
END LOOP;

How could others, on a local network, access my NodeJS app while it's running on my machine?

I had the same question and solved the problem. In my case, the Windows Firewall (not the router) was blocking the V8 machine I/O on the hosting machine.

  1. Go to windows button
  2. Search "Firewall"
  3. Choose "Allow programs to communicate through Firewall"
  4. Click Change Setup
  5. Tick all of "Evented I/O for V8 Javascript" OR "Node.js: Server-side Javascript"

My guess is that "Evented I/O for V8 Javascript" is the I/O process that node.js communicates to outside world and we need to free it before it can send packets outside of the local computer. After enabling this program to communicate over Windows firewall, I could use any port numbers to listen.

Run JavaScript when an element loses focus

From w3schools.com: Made compatible with Firefox Sept, 2016

<input type="text" onfocusout="myFunction()">

Enabling/installing GD extension? --without-gd

In my case (php 5.6, Ubuntu 14.04) the following command worked for me:

sudo apt-get install php5.6-gd

According to php version we need to change the php5.x-gd

PHP Function with Optional Parameters

In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

Example Using ... to access variable arguments

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

The above example will output:

10

Variable-length argument lists PHP Documentation

Undo a merge by pull request?

There is a better answer to this problem, though I could just break this down step-by-step.

You will need to fetch and checkout the latest upstream changes like so, e.g.:

git fetch upstream
git checkout upstream/master -b revert/john/foo_and_bar

Taking a look at the commit log, you should find something similar to this:

commit b76a5f1f5d3b323679e466a1a1d5f93c8828b269
Merge: 9271e6e a507888
Author: Tim Tom <[email protected]>
Date:   Mon Apr 29 06:12:38 2013 -0700

    Merge pull request #123 from john/foo_and_bar

    Add foo and bar

commit a507888e9fcc9e08b658c0b25414d1aeb1eef45e
Author: John Doe <[email protected]>
Date:   Mon Apr 29 12:13:29 2013 +0000

    Add bar

commit 470ee0f407198057d5cb1d6427bb8371eab6157e
Author: John Doe <[email protected]>
Date:   Mon Apr 29 10:29:10 2013 +0000

    Add foo

Now you want to revert the entire pull request with the ability to unrevert later. To do so, you will need to take the ID of the merge commit.

In the above example the merge commit is the top one where it says "Merged pull request #123...".

Do this to revert the both changes ("Add bar" and "Add foo") and you will end up with in one commit reverting the entire pull request which you can unrevert later on and keep the history of changes clean:

git revert -m 1 b76a5f1f5d3b323679e466a1a1d5f93c8828b269

C# how to create a Guid value?

Guid.NewGuid() creates a new random guid.

How can I create a temp file with a specific extension with .NET?

The MSDN documentation for C++'s GetTempFileName discusses your concern and answers it:

GetTempFileName is not able to guarantee that the file name is unique.

Only the lower 16 bits of the uUnique parameter are used. This limits GetTempFileName to a maximum of 65,535 unique file names if the lpPathName and lpPrefixString parameters remain the same.

Due to the algorithm used to generate file names, GetTempFileName can perform poorly when creating a large number of files with the same prefix. In such cases, it is recommended that you construct unique file names based on GUIDs.

Java array reflection: isArray vs. instanceof

There is no difference in behavior that I can find between the two (other than the obvious null-case). As for which version to prefer, I would go with the second. It is the standard way of doing this in Java.

If it confuses readers of your code (because String[] instanceof Object[] is true), you may want to use the first to be more explicit if code reviewers keep asking about it.

Twitter Bootstrap inline input with dropdown

Search for the "datalist" tag.

<input list="texto_pronto" name="input_normal">
<datalist id="texto_pronto">
    <option value="texto A">
    <option value="texto B">
</datalist>

What is the difference between a URI, a URL and a URN?

Identity = Name with Location

Every URL(Uniform Resource Locator) is a URI(Uniform Resource Identifier), abstractly speaking, but every URI is not a URL. There is another subcategory of URI is URN (Uniform Resource Name), which is a named resource but do not specify how to locate them, like mailto, news, ISBN is URIs. Source

enter image description here

URN:

  • URN Format : urn:[namespace identifier]:[namespace specific string]
  • urn: and : stand for themselves.
  • Examples:
    • urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66
    • urn:ISSN:0167-6423
    • urn:isbn:096139210x
    • Amazon Resource Names (ARNs) is a uniquely identify AWS resources.
      • ARN Format : arn:partition:service:region:account-id:resource

URL:

  • URL Format : [scheme]://[Domain][Port]/[path]?[queryString]#[fragmentId]
  • :,//,? and # stand for themselves.
  • schemes are https,ftp,gopher,mailto,news,telnet,file,man,info,whatis,ldap...
  • Examples:

Analogy:
To reach a person: Driving(protocol others SMS, email, phone), Address(hostname other phone-number, emailid) and person name(object name with a relative path).

ModelState.AddModelError - How can I add an error that isn't for a property?

I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:

ModelState.AddModelError(string key, string errorMessage);

but use an empty string for the key:

ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");

The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.

Which is the best IDE for Python For Windows

U can use eclipse. but u need to download pydev addon for that.

What are bitwise shift (bit-shift) operators and how do they work?

I am writing tips and tricks only. It may be useful in tests and exams.

  1. n = n*2: n = n<<1
  2. n = n/2: n = n>>1
  3. Checking if n is power of 2 (1,2,4,8,...): check !(n & (n-1))
  4. Getting xth bit of n: n |= (1 << x)
  5. Checking if x is even or odd: x&1 == 0 (even)
  6. Toggle the nth bit of x: x ^ (1<<n)

Subset and ggplot2

Use subset within ggplot

ggplot(data = subset(df, ID == "P1" | ID == "P2") +
   aes(Value1, Value2, group=ID, colour=ID) +
   geom_line()

Can I use CASE statement in a JOIN condition?

Took DonkeyKong's example.

The issue is I needed to use a declared variable. This allows for stating your left and right-hand side of what you need to compare. This is for supporting an SSRS report where different fields must be linked based on the selection by the user.

The initial case sets the field choice based on the selection and then I can set the field I need to match on for the join.

A second case statement could be added for the right-hand side if the variable is needed to choose from different fields

LEFT OUTER JOIN Dashboard_Group_Level_Matching ON
       case
         when @Level  = 'lvl1' then  cw.Lvl1
         when @Level  = 'lvl2' then  cw.Lvl2
         when @Level  = 'lvl3' then  cw.Lvl3
       end
    = Dashboard_Group_Level_Matching.Dashboard_Level_Name

jQuery UI Dialog Box - does not open after being closed

I solved it.

I used destroy instead close function (it doesn't make any sense), but it worked.

$(document).ready(function() {
$('#showTerms').click(function()
{
    $('#terms').css('display','inline');
    $('#terms').dialog({resizable: false,
        modal: true,
        width: 400,
        height: 450,
        overlay: { backgroundColor: "#000", opacity: 0.5 },
        buttons:{ "Close": function() { $(this).dialog('**destroy**'); } },
        close: function(ev, ui) { $(this).close(); },
    });         
});   
$('#form1 input#calendarTEST').datepicker({ dateFormat: 'MM d, yy' });
});

MySQL: selecting rows where a column is null

Had the same issue where query:

SELECT * FROM 'column' WHERE 'column' IS NULL; 

returned no values. Seems to be an issue with MyISAM and the same query on the data in InnoDB returned expected results.

Went with:

SELECT * FROM 'column' WHERE 'column' = ' '; 

Returned all expected results.

Label on the left side instead above an input field

I think this is what you want, from the bootstrap documentation "Horizontal form Use Bootstrap's predefined grid classes to align labels and groups of form controls in a horizontal layout by adding .form-horizontal to the form. Doing so changes .form-groups to behave as grid rows, so no need for .row". So:

<form class="form-horizontal" role="form">
<div class="form-group">
  <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
  <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group">
  <label for="inputPassword3" class="col-sm-2 control-label">Password</label>
  <div class="col-sm-10">
    <input type="password" class="form-control" id="inputPassword3" placeholder="Password">
  </div>
</div>
<div class="form-group">
  <div class="col-sm-offset-2 col-sm-10">
    <div class="checkbox">
      <label>
        <input type="checkbox"> Remember me
      </label>
    </div>
  </div>
</div>
<div class="form-group">
  <div class="col-sm-offset-2 col-sm-10">
    <button type="submit" class="btn btn-default">Sign in</button>
  </div>
</div>
</form>

Fiddle: http://jsfiddle.net/beewayne/B9jj2/29/

Custom Date/Time formatting in SQL Server

Not answering your question specifically, but isn't that something that should be handled by the presentation layer of your application. Doing it the way you describe creates extra processing on the database end as well as adding extra network traffic (assuming the database exists on a different machine than the application), for something that could be easily computed on the application side, with more rich date processing libraries, as well as being more language agnostic, especially in the case of your first example which contains the abbreviated month name. Anyway the answers others give you should point you in the right direction if you still decide to go this route.

css width: calc(100% -100px); alternative using jquery

100%-100px is the same

div.thediv {
  width: auto;
  margin-right:100px;
}

With jQuery:

$(window).resize(function(){
  $('.thediv').each(function(){
    $(this).css('width', $(this).parent().width()-100);
  })
});

Similar way is to use jQuery resize plugin

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

You could try this.

In windows go to Administrative Tools->Services And see scroll down to where it says Oracle[instanceNameHere] and see if the listener and the service itself are running. You might have to start it. You can also set it to start automatically when you right-click on it and go to properties.

Could not find an implementation of the query pattern

Make sure these references are included:

  • System.Data.Linq
  • System.Data.Entity

Then add the using statement

using System.Linq;

Java URLConnection Timeout

You can manually force disconnection by a Thread sleep. This is an example:

URLConnection con = url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
new Thread(new InterruptThread(con)).start();

then

public class InterruptThread implements Runnable {

    HttpURLConnection con;
    public InterruptThread(HttpURLConnection con) {
        this.con = con;
    }

    public void run() {
        try {
            Thread.sleep(5000); // or Thread.sleep(con.getConnectTimeout())
        } catch (InterruptedException e) {

        }
        con.disconnect();
        System.out.println("Timer thread forcing to quit connection");
    }
}

How to get json key and value in javascript?

var data = {"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}

var parsedData = JSON.parse(data);
alert(parsedData.name);
alert(parsedData.skills);
alert(parsedData.jobtitel);
alert(parsedData.res_linkedin);

How do I use floating-point division in bash?

As an alternative to bc, you can use awk within your script.

For example:

echo "$IMG_WIDTH $IMG2_WIDTH" | awk '{printf "%.2f \n", $1/$2}'

In the above, " %.2f " tells the printf function to return a floating point number with two digits after the decimal place. I used echo to pipe in the variables as fields since awk operates properly on them. " $1 " and " $2 " refer to the first and second fields input into awk.

And you can store the result as some other variable using:

RESULT = `echo ...`

Visual Studio Code pylint: Unable to import 'protorpc'

I was still getting these errors even after confirming that the correct python and pylint were being used from my virtual env.

Eventually I figured out that in Visual Studio Code I was A) opening my project directory, which is B) where my Python virtual environment was, but I was C) running my main Python program from two levels deeper. Those three things need to be in sync for everything to work.

Here's what I would recommend:

  1. In Visual Studio Code, open the directory containing your main Python program. (This may or may not be the top level of the project directory.)

  2. Select Terminal menu > New Terminal, and create an virtual environment directly inside the same directory.

    python3 -m venv env
    
  3. Install pylint in the virtual environment. If you select any Python file in the sidebar, Visual Studio Code will offer to do this for you. Alternatively, source env/bin/activate then pip install pylint.

  4. In the blue bottom bar of the editor window, choose the Python interpreter env/bin/python. Alternatively, go to Settings and set "Python: Python Path." This sets python.pythonPath in Settings.json.

Progress during large file copy (Copy-Item & Write-Progress?)

Hate to be the one to bump an old subject, but I found this post extremely useful. After running performance tests on the snippets by stej and it's refinement by Graham Gold, plus the BITS suggestion by Nacht, I have decuded that:

  1. I really liked Graham's command with time estimations and speed readings.
  2. I also really liked the significant speed increase of using BITS as my transfer method.

Faced with the decision between the two... I found that Start-BitsTransfer supported Asynchronous mode. So here is the result of my merging the two.

function Copy-File {
    # ref: https://stackoverflow.com/a/55527732/3626361
    param([string]$From, [string]$To)

    try {
        $job = Start-BitsTransfer -Source $From -Destination $To `
            -Description "Moving: $From => $To" `
            -DisplayName "Backup" -Asynchronous

        # Start stopwatch
        $sw = [System.Diagnostics.Stopwatch]::StartNew()
        Write-Progress -Activity "Connecting..."

        while ($job.JobState.ToString() -ne "Transferred") {
            switch ($job.JobState.ToString()) {
                "Connecting" {
                    break
                }
                "Transferring" {
                    $pctcomp = ($job.BytesTransferred / $job.BytesTotal) * 100
                    $elapsed = ($sw.elapsedmilliseconds.ToString()) / 1000

                    if ($elapsed -eq 0) {
                        $xferrate = 0.0
                    }
                    else {
                        $xferrate = (($job.BytesTransferred / $elapsed) / 1mb);
                    }

                    if ($job.BytesTransferred % 1mb -eq 0) {
                        if ($pctcomp -gt 0) {
                            $secsleft = ((($elapsed / $pctcomp) * 100) - $elapsed)
                        }
                        else {
                            $secsleft = 0
                        }

                        Write-Progress -Activity ("Copying file '" + ($From.Split("\") | Select-Object -last 1) + "' @ " + "{0:n2}" -f $xferrate + "MB/s") `
                            -PercentComplete $pctcomp `
                            -SecondsRemaining $secsleft
                    }
                    break
                }
                "Transferred" {
                    break
                }
                Default {
                    throw $job.JobState.ToString() + " unexpected BITS state."
                }
            }
        }

        $sw.Stop()
        $sw.Reset()
    }
    finally {
        Complete-BitsTransfer -BitsJob $job
        Write-Progress -Activity "Completed" -Completed
    }
}

XML Parsing - Read a Simple XML File and Retrieve Values

Easy way to parse the xml is to use the LINQ to XML

for example you have the following xml file

<library>
    <track id="1" genre="Rap" time="3:24">
        <name>Who We Be RMX (feat. 2Pac)</name>
        <artist>DMX</artist>
        <album>The Dogz Mixtape: Who's Next?!</album>
    </track>
    <track id="2" genre="Rap" time="5:06">
        <name>Angel (ft. Regina Bell)</name>
        <artist>DMX</artist>
        <album>...And Then There Was X</album>
    </track>
    <track id="3" genre="Break Beat" time="6:16">
        <name>Dreaming Your Dreams</name>
        <artist>Hybrid</artist>
        <album>Wide Angle</album>
    </track>
    <track id="4" genre="Break Beat" time="9:38">
        <name>Finished Symphony</name>
        <artist>Hybrid</artist>
        <album>Wide Angle</album>
    </track>
<library>

For reading this file, you can use the following code:

public void Read(string  fileName)
{
    XDocument doc = XDocument.Load(fileName);

    foreach (XElement el in doc.Root.Elements())
    {
        Console.WriteLine("{0} {1}", el.Name, el.Attribute("id").Value);
        Console.WriteLine("  Attributes:");
        foreach (XAttribute attr in el.Attributes())
            Console.WriteLine("    {0}", attr);
        Console.WriteLine("  Elements:");

        foreach (XElement element in el.Elements())
            Console.WriteLine("    {0}: {1}", element.Name, element.Value);
    }
}

Show percent % instead of counts in charts of categorical variables

Since this was answered there have been some meaningful changes to the ggplot syntax. Summing up the discussion in the comments above:

 require(ggplot2)
 require(scales)

 p <- ggplot(mydataf, aes(x = foo)) +  
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        ## version 3.0.0
        scale_y_continuous(labels=percent)

Here's a reproducible example using mtcars:

 ggplot(mtcars, aes(x = factor(hp))) +  
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        scale_y_continuous(labels = percent) ## version 3.0.0

enter image description here

This question is currently the #1 hit on google for 'ggplot count vs percentage histogram' so hopefully this helps distill all the information currently housed in comments on the accepted answer.

Remark: If hp is not set as a factor, ggplot returns:

enter image description here

Excel SUMIF between dates

You haven't got your SUMIF in the correct order - it needs to be range, criteria, sum range. Try:

=SUMIF(A:A,">="&DATE(2012,1,1),B:B)

How to ALTER multiple columns at once in SQL Server

This is not possible. You will need to do this one by one. You could:

  1. Create a Temporary Table with your modified columns in
  2. Copy the data across
  3. Drop your original table (Double check before!)
  4. Rename your Temporary Table to your original name

How to generate a Dockerfile from an image?

A bash solution :

docker history --no-trunc $argv  | tac | tr -s ' ' | cut -d " " -f 5- | sed 's,^/bin/sh -c #(nop) ,,g' | sed 's,^/bin/sh -c,RUN,g' | sed 's, && ,\n  & ,g' | sed 's,\s*[0-9]*[\.]*[0-9]*\s*[kMG]*B\s*$,,g' | head -n -1

Step by step explanations:

tac : reverse the file
tr -s ' '                                       trim multiple whitespaces into 1
cut -d " " -f 5-                                remove the first fields (until X months/years ago)
sed 's,^/bin/sh -c #(nop) ,,g'                  remove /bin/sh calls for ENV,LABEL...
sed 's,^/bin/sh -c,RUN,g'                       remove /bin/sh calls for RUN
sed 's, && ,\n  & ,g'                           pretty print multi command lines following Docker best practices
sed 's,\s*[0-9]*[\.]*[0-9]*\s*[kMG]*B\s*$,,g'      remove layer size information
head -n -1                                      remove last line ("SIZE COMMENT" in this case)

Example:

 ~ ? dih ubuntu:18.04
ADD file:28c0771e44ff530dba3f237024acc38e8ec9293d60f0e44c8c78536c12f13a0b in /
RUN set -xe
   &&  echo '#!/bin/sh' > /usr/sbin/policy-rc.d
   &&  echo 'exit 101' >> /usr/sbin/policy-rc.d
   &&  chmod +x /usr/sbin/policy-rc.d
   &&  dpkg-divert --local --rename --add /sbin/initctl
   &&  cp -a /usr/sbin/policy-rc.d /sbin/initctl
   &&  sed -i 's/^exit.*/exit 0/' /sbin/initctl
   &&  echo 'force-unsafe-io' > /etc/dpkg/dpkg.cfg.d/docker-apt-speedup
   &&  echo 'DPkg::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' > /etc/apt/apt.conf.d/docker-clean
   &&  echo 'APT::Update::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' >> /etc/apt/apt.conf.d/docker-clean
   &&  echo 'Dir::Cache::pkgcache ""; Dir::Cache::srcpkgcache "";' >> /etc/apt/apt.conf.d/docker-clean
   &&  echo 'Acquire::Languages "none";' > /etc/apt/apt.conf.d/docker-no-languages
   &&  echo 'Acquire::GzipIndexes "true"; Acquire::CompressionTypes::Order:: "gz";' > /etc/apt/apt.conf.d/docker-gzip-indexes
   &&  echo 'Apt::AutoRemove::SuggestsImportant "false";' > /etc/apt/apt.conf.d/docker-autoremove-suggests
RUN rm -rf /var/lib/apt/lists/*
RUN sed -i 's/^#\s*\(deb.*universe\)$/\1/g' /etc/apt/sources.list
RUN mkdir -p /run/systemd
   &&  echo 'docker' > /run/systemd/container
CMD ["/bin/bash"]

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

Removing Read-only CheckBox from C:\Users\SQL Service account name\AppData\Local\Temp worked for me.

DATEDIFF function in Oracle

In Oracle, you can simply subtract two dates and get the difference in days. Also note that unlike SQL Server or MySQL, in Oracle you cannot perform a select statement without a from clause. One way around this is to use the builtin dummy table, dual:

SELECT TO_DATE('2000-01-02', 'YYYY-MM-DD') -  
       TO_DATE('2000-01-01', 'YYYY-MM-DD') AS DateDiff
FROM   dual

How to print multiple lines of text with Python

The triple quotes answer is great for ASCII art, but for those wondering - what if my multiple lines are a tuple, list, or other iterable that returns strings (perhaps a list comprehension?), then how about:

print("\n".join(<*iterable*>))

For example:

print("\n".join(["{}={}".format(k, v) for k, v in os.environ.items() if 'PATH' in k]))

Bash scripting missing ']'

You're missing a space after "p1":

if [ -s "p1" ];

How does Subquery in select statement work in oracle

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

Shell Script Syntax Error: Unexpected End of File

I have found that this is sometimes caused by running a MS Dos version of a file. If that's the case dos2ux should fix that.

dos2ux file1 > file2

pandas DataFrame: replace nan values with average of columns

In [16]: df = DataFrame(np.random.randn(10,3))

In [17]: df.iloc[3:5,0] = np.nan

In [18]: df.iloc[4:6,1] = np.nan

In [19]: df.iloc[5:8,2] = np.nan

In [20]: df
Out[20]: 
          0         1         2
0  1.148272  0.227366 -2.368136
1 -0.820823  1.071471 -0.784713
2  0.157913  0.602857  0.665034
3       NaN -0.985188 -0.324136
4       NaN       NaN  0.238512
5  0.769657       NaN       NaN
6  0.141951  0.326064       NaN
7 -1.694475 -0.523440       NaN
8  0.352556 -0.551487 -1.639298
9 -2.067324 -0.492617 -1.675794

In [22]: df.mean()
Out[22]: 
0   -0.251534
1   -0.040622
2   -0.841219
dtype: float64

Apply per-column the mean of that columns and fill

In [23]: df.apply(lambda x: x.fillna(x.mean()),axis=0)
Out[23]: 
          0         1         2
0  1.148272  0.227366 -2.368136
1 -0.820823  1.071471 -0.784713
2  0.157913  0.602857  0.665034
3 -0.251534 -0.985188 -0.324136
4 -0.251534 -0.040622  0.238512
5  0.769657 -0.040622 -0.841219
6  0.141951  0.326064 -0.841219
7 -1.694475 -0.523440 -0.841219
8  0.352556 -0.551487 -1.639298
9 -2.067324 -0.492617 -1.675794

How to convert datetime format to date format in crystal report using C#?

if it is just a format issue use ToShortDateString()

installing JDK8 on Windows XP - advapi32.dll error

Oracle has announced fix for Windows XP installation error

Oracle has decided to fix Windows XP installation. As of the JRE 8u25 release in 10/15/2014 the code of the installer has been changes so that installation on Windows XP is again possible.

However, this does not mean that Oracle is continuing to support Windows XP. They make no guarantee about current and future releases of JRE8 being compatible with Windows XP. It looks like it's a run at your own risk kind of thing.

See the Oracle blog post here.

You can get the latest JRE8 right off the Oracle downloads site.

Java associative-array

You can accomplish this via Maps. Something like

Map<String, String>[] arr = new HashMap<String, String>[2]();
arr[0].put("name", "demo");

But as you start using Java I am sure you will find that if you create a class/model that represents your data will be your best options. I would do

class Person{
String name;
String fname;
}
List<Person> people = new ArrayList<Person>();
Person p = new Person();
p.name = "demo";
p.fname = "fdemo";
people.add(p);

What is the equivalent of 'describe table' in SQL Server?

There are a few methods to get metadata about a table:

EXEC sp_help tablename

Will return several result sets, describing the table, it's columns and constraints.

The INFORMATION_SCHEMA views will give you the information you want, though unfortunately you have to query the views and join them manually.

cURL equivalent in Node.js?

You can try using POSTMAN Chrome app for your request and you can generate node js code from there

Entity Framework Provider type could not be loaded?

I had encountered exactly the same problem on my CI build server (running Bamboo), which doesn't install any Visual Studio IDE on it.

Without making any code changing for the build/test process (which I don't think is good solution), the best way is to copy the EntityFramework.SqlServer.dll and paste it to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE. (where your mstest running)

Problem solved!

Python PDF library

There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.

Hidden features of Python

Dict Comprehensions

>>> {i: i**2 for i in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Python documentation

Wikipedia Entry

Display text from .txt file in batch file

type log.txt

But that will give you the whole file. You could change it to:

echo %date%, %time% >> log.txt
echo %date%, %time% > log_last.txt
...
type log_last.txt

to get only the last one.

How can I open a popup window with a fixed size using the HREF tag?

I can't comment on Esben Skov Pedersen's answer directly, but using the following notation for links:

<a href="javascript:window.open('http://www.websiteofyourchoice.com');">Click here</a>

In Internet Explorer, the new browser window appears, but the current window navigates to a page which says "[Object]". To avoid this, simple put a "void(0)" behind the JavaScript function.

Source: https://support.microsoft.com/en-us/kb/257321

How to set .net Framework 4.5 version in IIS 7 application pool

There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

Your ComboBox is trying to bind to bind to GridItem[x].CompanyItems, which doesn't exist.

Your RelativeBinding is close, however it needs to bind to DataContext.CompanyItems because Window.CompanyItems does not exist

asp.net: How can I remove an item from a dropdownlist?

myDropDown.Items.Remove(myDropDown.Items.FindByText("TextToFind"))

Change the background color in a twitter bootstrap modal?

CSS

If this doesn't work:

.modal-backdrop {
   background-color: red;
}

try this:

.modal { 
   background-color: red !important; 
}

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

you set onclick listeners to you buttons. dissmis dialog and do your action. Don't need to halt anything

protected Dialog onCreateDialog(int id) {
  return new AlertDialog.Builder(this).setTitle(R.string.no_connection).setIcon(android.R.drawable.ic_dialog_alert).setView(textEntryView).setPositiveButton(R.string.exit, new DialogInterface.OnClickListener() 
{

   public void onClick(DialogInterface dialog, int whichButton) {

  // Here goes what you want to do
  }

})
}

to call - ex - showDialog(DIALOG_ERROR_PREF);

More http://developer.android.com/guide/topics/ui/dialogs.html

Python 3: EOF when reading a line (Sublime Text 2 is angry)

help(input) shows what keyboard shortcuts produce EOF, namely, Unix: Ctrl-D, Windows: Ctrl-Z+Return:

input([prompt]) -> string

Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.

You could reproduce it using an empty file:

$ touch empty
$ python3 -c "input()" < empty
Traceback (most recent call last):
  File "<string>", line 1, in <module>
EOFError: EOF when reading a line

You could use /dev/null or nul (Windows) as an empty file for reading. os.devnull shows the name that is used by your OS:

$ python3 -c "import os; print(os.devnull)"
/dev/null

Note: input() happily accepts input from a file/pipe. You don't need stdin to be connected to the terminal:

$ echo abc | python3 -c "print(input()[::-1])"
cba

Either handle EOFError in your code:

try:
    reply = input('Enter text')
except EOFError:
    break

Or configure your editor to provide a non-empty input when it runs your script e.g., by using a customized command line if it allows it: python3 "%f" < input_file

Declaring a variable and setting its value from a SELECT query in Oracle

For storing a single row output into a variable from the select into query :

declare v_username varchare(20); SELECT username into v_username FROM users WHERE user_id = '7';

this will store the value of a single record into the variable v_username.


For storing multiple rows output into a variable from the select into query :

you have to use listagg function. listagg concatenate the resultant rows of a coloumn into a single coloumn and also to differentiate them you can use a special symbol. use the query as below SELECT listagg(username || ',' ) within group (order by username) into v_username FROM users;

Fixing broken UTF-8 encoding

I had a problem with an xml file that had a broken encoding, it said it was utf-8 but it had characters that where not utf-8.
After several trials and errors with the mb_convert_encoding() I manage to fix it with

mb_convert_encoding($text, 'Windows-1252', 'UTF-8')

CSS background image URL failing to load

You are using a local path. Is that really what you want? If it is, you need to use the file:/// prefix:

file:///H:/media/css/static/img/sprites/buttons-v3-10.png

obviously, this will work only on your local computer.

Also, in many modern browsers, this works only if the page itself is also on a local file path. Addressing local files from remote (http://, https://) pages has been widely disabled due to security reasons.

How to get current available GPUs in tensorflow?

In TensorFlow 2.0, you can use tf.config.experimental.list_physical_devices('GPU'):

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    print("Name:", gpu.name, "  Type:", gpu.device_type)

If you have two GPUs installed, it outputs this:

Name: /physical_device:GPU:0   Type: GPU
Name: /physical_device:GPU:1   Type: GPU

From 2.1, you can drop experimental:

gpus = tf.config.list_physical_devices('GPU')

See:

Wait until an HTML5 video loads

call function on load:

<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">

get video duration

var video = document.getElementById("video");
var duration = video.duration;