Programs & Examples On #Disconnected environment

How to add multiple font files for the same font?

If you are using Google fonts I would suggest the following.

If you want the fonts to run from your localhost or server you need to download the files.

Instead of downloading the ttf packages in the download links, use the live link they provide, for example:

http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,300italic,400italic,600italic

Paste the URL in your browser and you should get a font-face declaration similar to the first answer.

Open the URLs provided, download and rename the files.

Stick the updated font-face declarations with relative paths to the woff files in your CSS, and you are done.

SQL Server Text type vs. varchar data type

TEXT is used for large pieces of string data. If the length of the field exceeed a certain threshold, the text is stored out of row.

VARCHAR is always stored in row and has a limit of 8000 characters. If you try to create a VARCHAR(x), where x > 8000, you get an error:

Server: Msg 131, Level 15, State 3, Line 1

The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)

These length limitations do not concern VARCHAR(MAX) in SQL Server 2005, which may be stored out of row, just like TEXT.

Note that MAX is not a kind of constant here, VARCHAR and VARCHAR(MAX) are very different types, the latter being very close to TEXT.

In prior versions of SQL Server you could not access the TEXT directly, you only could get a TEXTPTR and use it in READTEXT and WRITETEXT functions.

In SQL Server 2005 you can directly access TEXT columns (though you still need an explicit cast to VARCHAR to assign a value for them).

TEXT is good:

  • If you need to store large texts in your database
  • If you do not search on the value of the column
  • If you select this column rarely and do not join on it.

VARCHAR is good:

  • If you store little strings
  • If you search on the string value
  • If you always select it or use it in joins.

By selecting here I mean issuing any queries that return the value of the column.

By searching here I mean issuing any queries whose result depends on the value of the TEXT or VARCHAR column. This includes using it in any JOIN or WHERE condition.

As the TEXT is stored out of row, the queries not involving the TEXT column are usually faster.

Some examples of what TEXT is good for:

  • Blog comments
  • Wiki pages
  • Code source

Some examples of what VARCHAR is good for:

  • Usernames
  • Page titles
  • Filenames

As a rule of thumb, if you ever need you text value to exceed 200 characters AND do not use join on this column, use TEXT.

Otherwise use VARCHAR.

P.S. The same applies to UNICODE enabled NTEXT and NVARCHAR as well, which you should use for examples above.

P.P.S. The same applies to VARCHAR(MAX) and NVARCHAR(MAX) that SQL Server 2005+ uses instead of TEXT and NTEXT. You'll need to enable large value types out of row for them with sp_tableoption if you want them to be always stored out of row.

As mentioned above and here, TEXT is going to be deprecated in future releases:

The text in row option will be removed in a future version of SQL Server. Avoid using this option in new development work, and plan to modify applications that currently use text in row. We recommend that you store large data by using the varchar(max), nvarchar(max), or varbinary(max) data types. To control in-row and out-of-row behavior of these data types, use the large value types out of row option.

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

http://www.carqueryapi.com

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

Mac OS X - EnvironmentError: mysql_config not found

I had been debugging this problem forever - 3 hours 17 mins. What particularly annoyed me was that I already had sql installed on my system through prior uni work but pip/pip3 wasn't recognising it. These threads above and many other I scoured the internet for were helpful in eluminating the problem but didn't actually solve things.

ANSWER

Pip is looking for mysql binaries in the Homebrew Directory which is located relative to Macintosh HD @

/usr/local/Cellar/

so I found that this requires you making a few changes

step 1: Download MySql if not already done so https://dev.mysql.com/downloads/

Step 2: Locate it relative to Macintosh HD and cd

/usr/local/mysql/bin

Step 3: Once there open terminal and use a text editor of choice - I'm a neovim guy myself so I typed (doesn't automatically come with Mac... another story for another day)

nvim mysql_config

Step 4: You will see at approx line 112

# Create options 
libs="-L$pkglibdir"
libs="$libs -l "

Change to

# Create options 
libs="-L$pkglibdir"
libs="$libs -lmysqlclient -lssl -lcrypto"

*you'll notice that this file has read-only access so if your using vim or neovim

:w !sudo tee %

Step 5: Head to the home directory and edit the .bash_profile file

cd ~

Then

nvim .bash_profile

and add

export PATH="/usr/local/mysql/bin:$PATH"

to the file then save

Step 6: relative to Macintosh HD locate paths and add to it

cd /private/etc/

then

nvim paths

and add

/usr/local/mysql/bin

*you'll again notice that this file has read-only access so if your using vim or neovim

:w !sudo tee % 

then

cd ~

then refresh the terminal with your changes by running

source .bash_profile

Finally

pip3 install mysqlclient

And Viola. Remember it's a vibe.

How do I make an HTML button not reload the page

there is no need to js or jquery. to stop page reloading just specify the button type as 'button'. if you dont specify the button type, browser will set it to 'reset' or 'submit' witch cause to page reload.

 <button type='button'>submit</button> 

PHP Fatal error: Cannot access empty property

This way you can create a new object with a custom property name.

$my_property = 'foo';
$value = 'bar';
$a = (object) array($my_property => $value);

Now you can reach it like:

echo $a->foo;  //returns bar

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

"No backupset selected to be restored" SQL Server 2012

Run SQL Server Management Studio as an administrator (right-click the shortcut/exe, then select "Run as Administrator"), then try to restore.

PHP header() redirect with POST variables

It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.

You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.

How to use LogonUser properly to impersonate domain user from workgroup client

Very few posts suggest using LOGON_TYPE_NEW_CREDENTIALS instead of LOGON_TYPE_NETWORK or LOGON_TYPE_INTERACTIVE. I had an impersonation issue with one machine connected to a domain and one not, and this fixed it. The last code snippet in this post suggests that impersonating across a forest does work, but it doesn't specifically say anything about trust being set up. So this may be worth trying:

const int LOGON_TYPE_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_WINNT50 = 3;
bool returnValue = LogonUser(user, domain, password,
            LOGON_TYPE_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50,
            ref tokenHandle);

MSDN says that LOGON_TYPE_NEW_CREDENTIALS only works when using LOGON32_PROVIDER_WINNT50.

Python: find position of element in array

For your first question, find the position of some value in a list x using index(), like so:

x.index(value)

For your second question, to check for multiple same values you should split your list into chunks and use the same logic from above. They say divide and conquer. It works. Try this:

value = 1 
x = [1,2,3,4,5,6,2,1,4,5,6]

chunk_a = x[:int(len(x)/2)] # get the first half of x 
chunk_b = x[int(len(x)/2):] # get the rest half of x

print(chunk_a.index(value))
print(chunk_b.index(value))

Hope that helps!

Replace last occurrence of character in string

_x000D_
_x000D_
    // Define variables_x000D_
    let haystack = 'I do not want to replace this, but this'_x000D_
    let needle = 'this'_x000D_
    let replacement = 'hey it works :)'_x000D_
    _x000D_
    // Reverse it_x000D_
    haystack = Array.from(haystack).reverse().join('')_x000D_
    needle = Array.from(needle).reverse().join('')_x000D_
    replacement = Array.from(replacement).reverse().join('')_x000D_
    _x000D_
    // Make the replacement_x000D_
    haystack = haystack.replace(needle, replacement)_x000D_
    _x000D_
    // Reverse it back_x000D_
    let results = Array.from(haystack).reverse().join('')_x000D_
    console.log(results)_x000D_
    // 'I do not want to replace this, but hey it works :)'
_x000D_
_x000D_
_x000D_

PHP - Move a file into a different folder on the server

Use the rename() function.

rename("user/image1.jpg", "user/del/image1.jpg");

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

You have to include one more jar.

xmlbeans-2.3.0.jar

Add this and try.

Note: It is required for the files with .xlsx formats only, not for just .xls formats.

Open and write data to text file using Bash?

For environments where here documents are unavailable (Makefile, Dockerfile, etc) you can often use printf for a reasonably legible and efficient solution.

printf '%s\n' '#!/bin/sh' '# Second line' \
    '# Third line' \
    '# Conveniently mix single and double quotes, too' \
    "# Generated $(date)" \
    '# ^ the date command executes when the file is generated' \
    'for file in *; do' \
    '    echo "Found $file"' \
    'done' >outputfile

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

I had the same issue and I got the exception when I was trying to create MassTransit queues:

"Exception: System.TypeInitializationException: The type initializer for 'MassTransit.Serialization.JsonMessageSerializer' threw an exception. ---> System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)"

Solution that worked for me (after spending couple of days reverting several commits):

  • We had a windows service solution that has .Service project and .XUnitTests project. Both of them were using a common nuget that has dependency on Newtonsoft.Json.dll. There was no explicit reference to Newtonsoft.Json nuget package in both projects (but we were using 'using Newtonsoft.Json;' namespace in our classes), so the common nuget was using version 9 of Newtonsoft.Json by default.

  • As soon as I installed the Newtonsoft.Json nuget in both .Service and .XUnitTests projects, the common nuget package started using the latest v12 Newtonsoft and that fixed my issue.

Just posting it in here if it saves anyone their valuable time.

How to use random in BATCH script?

here is a example i created for you, it should display a dialog asking you to select a number 1-10, depending on the number you select, it will generate a random number example to a batch file that you named. If you select "1" then you will get a random 1 digit number example. if you select "10" then you will get a random 10 digit number example.

@echo off
color f0
set /p "FileName= Enter Filename (Without Extension) : "
echo @echo off >> %FileName%.bat
echo File Created!
pause
cls
:CommandLine
set /p "calc= ~%ComputerName%: Enter a number to recieve the amount of  random digits :"
if %calc%==genrand_help goto GenerateRandomHelp
if %calc%==1 echo echo %%RANDOM:~-1%% >> %FileName%.bat
if %calc%==2 echo echo %%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat 
if %calc%==3 echo echo %%RANDOM:~-1%%%%RANDOM:~-1%%%RANDOM:~-1%% >>  %FileName%.bat
if %calc%==4 echo echo %%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat
if %calc%==5 echo echo %%Random%% >> %FileName%.bat
if %calc%==6 echo echo %%Random%%%%RANDOM:~-1%% >> %FileName%.bat
if %calc%==7 echo echo %%Random%%%%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat 
if %calc%==8 echo echo %%Random%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat
if %calc%==9 echo echo  %%Random%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%% >>  %FileName%.bat
if %calc%==10 echo echo %%Random%%%%Random%% >> %FileName%.bat  
goto CommandLine

How to get a parent element to appear above child

Since your divs are position:absolute, they're not really nested as far as position is concerned. On your jsbin page I switched the order of the divs in the HTML to:

<div class="child"><div class="parent"></div></div>

and the red box covered the blue box, which I think is what you're looking for.

.trim() in JavaScript not working in IE

I had a similar issue when trying to trim a value from an input and then ask if it was equal to nothing:

if ($(this).val().trim() == "")

However this threw a spanner in the works for IE6 - 8. Annoyingly enough I'd tried to var it up like so:

   var originalValue = $(this).val();

However, using jQuery's trim method, works perfectly for me in all browsers..

var originalValueTrimmed = $.trim($(this).val());              
            if (originalValueTrimmed  == "") { ... }

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

You have to add THEN

IF EXISTS(SELECT * FROM component_psar WHERE tbl_id = '2' AND row_nr = '1') 
THEN
UPDATE component_psar SET col_1 = '1', col_2 = '1', col_3 = '1', col_4 = '1', col_5 = '1', col_6 = '1', unit = '1', add_info = '1', fsar_lock = '1' WHERE tbl_id = '2' AND row_nr = '1' 
ELSE 
INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock) VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

File sutest

#!/bin/bash
echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"

run it: `./sutest' gives me

uid is 500
user is stephenp
username is stephenp

but using sudo: sudo ./sutest gives

uid is 0
user is root
username is stephenp

So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:

#!/bin/bash
sudo -u ${USERNAME} normal_command_1
root_command_1
root_command_2
sudo -u ${USERNAME} normal_command_2
# etc.

Just sudo to invoke your script in the first place, it will prompt for the password once.


I originally wrote this answer on Linux, which does have some differences with OS X

OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER when you're running sudo, which can be used in place of USERNAME above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.

Changing the original script for OS X, it becomes...

#!/bin/bash
sudo -u ${SUDO_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${SUDO_USER} normal_command_2
# etc.

A first stab at making it cross-platform could be...

#!/bin/bash
#
# set "THE_USER" to SUDO_USER if that's set,
#  else set it to USERNAME if THAT is set,
#   else set it to the string "unknown"
# should probably then test to see if it's "unknown"
#
THE_USER=${SUDO_USER:-${USERNAME:-unknown}}

sudo -u ${THE_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${THE_USER} normal_command_2
# etc.

jQuery Screen Resolution Height Adjustment

var space = $(window).height();
var diff = space - HEIGHT;
var margin = (diff > 0) ? (space - HEIGHT)/2 : 0;
$('#container').css({'margin-top': margin});

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Instead of

<button ng-click="removeTask({{task.id}})">remove</button>

do this:

<button ng-click="removeTask(task.id)">remove</button>

Please see this fiddle:

http://jsfiddle.net/JSWorld/Hp4W7/34/

How to use function srand() with time.h?

You need to call srand() once, to randomize the seed, and then call rand() in your loop:

#include <stdlib.h>
#include <time.h>

#define size 10

srand(time(NULL)); // randomize seed

for(i=0;i<size;i++)
    Arr[i] = rand()%size;

LDAP server which is my base dn

Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:

slapcat > backup.ldif

If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.

add elements to object array

I know this is old, but came across it looking for a simpler way, and this is how i do it, just create a new list of the same object and add it to the one you want to use e.g.

Subject[] subjectsList = {new Subject1{....}, new Subject2{....}, new Subject3{....}} 
univStudent.subjects = subjectsList ;

jQuery Call to WebService returns "No Transport" error

I had the same error on a page, and I added these lines:

<!--[if lte IE 9]>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.3/jquery.xdomainrequest.min.js'></script>
<![endif]-->

and it finally works for me ;) no more error in IE9.

Is it necessary to write HEAD, BODY and HTML tags?

Firebug shows this correctly because your Browser automagically fixes the bad markup for you. This behaviour is not specified anywhere and can (will) vary from browser to browser. Those tags are required by the DOCTYPE you're using and should not be omitted.

The html element is the root element of every html page. If you look at all other elements' description it says where an element can be used (and almost all elements require either head or body).

INSERT INTO vs SELECT INTO

Select into for large datasets may be good only for a single user using one single connection to the database doing a bulk operation task. I do not recommend to use

SELECT * INTO table

as this creates one big transaction and creates schema lock to create the object, preventing other users to create object or access system objects until the SELECT INTO operation completes.

As proof of concept open 2 sessions, in first session try to use

select into temp table from a huge table 

and in the second section try to

create a temp table 

and check the locks, blocking and the duration of second session to create a temp table object. My recommendation it is always a good practice to create and Insert statement and if needed for minimal logging use trace flag 610.

/** and /* in Java Comments

Java supports two types of comments:

  • /* multiline comment */ : The compiler ignores everything from /* to */. The comment can span over multiple lines.

  • // single line : The compiler ignores everything from // to the end of the line.

Some tool such as javadoc use a special multiline comment for their purpose. For example /** doc comment */ is a documentation comment used by javadoc when preparing the automatically generated documentation, but for Java it's a simple multiline comment.

How to use a client certificate to authenticate and authorize in a Web API

Tracing helped me find what the problem was (Thank you Fabian for that suggestion). I found with further testing that I could get the client certificate to work on another server (Windows Server 2012). I was testing this on my development machine (Window 7) so I could debug this process. So by comparing the trace to an IIS Server that worked and one that did not I was able to pinpoint the relevant lines in the trace log. Here is a portion of a log where the client certificate worked. This is the setup right before the send

System.Net Information: 0 : [17444] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [17444] SecureChannel#54718731 - We have user-provided certificates. The server has not specified any issuers, so try all the certificates.
System.Net Information: 0 : [17444] SecureChannel#54718731 - Selected certificate:

Here is what the trace log looked like on the machine where the client certificate failed.

System.Net Information: 0 : [19616] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [19616] SecureChannel#54718731 - We have user-provided certificates. The server has specified 137 issuer(s). Looking for certificates that match any of the issuers.
System.Net Information: 0 : [19616] SecureChannel#54718731 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [19616] Using the cached credential handle.

Focusing on the line that indicated the server specified 137 issuers I found this Q&A that seemed similar to my issue. The solution for me was not the one marked as an answer since my certificate was in the trusted root. The answer is the one under it where you update the registry. I just added the value to the registry key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL

Value name: SendTrustedIssuerList Value type: REG_DWORD Value data: 0 (False)

After adding this value to the registry it started to work on my Windows 7 machine. This appears to be a Windows 7 issue.

How to Convert unsigned char* to std::string in C++?

Here is the complete code

#include <bits/stdc++.h>

using namespace std;

typedef unsigned char BYTE;

int main() {
  //method 1;
  std::vector<BYTE> data = {'H','E','L','L','O','1','2','3'};
  //string constructor accepts only const char
  std::string s((const char*)&(data[0]), data.size());
  std::cout << s << std::endl;

  //method 2
  std::string s2(data.begin(),data.end());
  std::cout << s2 << std::endl;

  //method 3
  std::string s3(reinterpret_cast<char const*>(&data[0]), data.size()) ;
  std::cout << s3 << std::endl;
 
  return 0;
}

HTML character codes for this ? or this ?

You don't need to use character codes; just use UTF-8 and put them in literally; like so:

??

If you absolutely must use the entites, they are &#x25b2; and &#x25bc;, respectively.

how to check if a file is a directory or regular file in python?

An educational example from the stat documentation:

import os, sys
from stat import *

def walktree(top, callback):
    '''recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'''

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.stat(pathname)[ST_MODE]
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print 'Skipping %s' % pathname

def visitfile(file):
    print 'visiting', file

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)

ArrayList: how does the size increase?

when a ArrayList is declared and initialized using default constructor, memory space for 10 elements will be created. now, when i add 11 th element, what happens is

ArrayList create a new object with the following size

i.e OldCapacity*3/2+1 = 10*3/2+1 =16

Centering text in a table in Twitter Bootstrap

If it's just once, you shouldn't alter your style sheet. Just edit that particular td:

<td style="text-align: center;">

Cheers

WCF service startup error "This collection already contains an address with scheme http"

In my case root cause of this issue was multiple http bindings defined at parent web site i.e. InetMgr->Sites->Mysite->properties->EditBindings. I deleted one http binding which was not required and problem got resolved.

How to install pywin32 module in windows 7

Quoting the README at https://github.com/mhammond/pywin32:

By far the easiest way to use pywin32 is to grab binaries from the most recent release

Just download the installer for your version of Python from https://github.com/mhammond/pywin32/releases and run it, and you're done.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

Java "?" Operator for checking null - What is it? (Not Ternary!)

You can test the code which you have provided and it will give syntax error.So, it is not supported in Java. Groovy does support it and it was proposed for Java 7 (but never got included).

However, you can use the Optional provided in Java 8. This might help you in achieving something on similar line. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html

Example Code for Optional

How do I measure the execution time of JavaScript code with callbacks?

For anyone want to get time elapsed value instead of console output :

use process.hrtime() as @D.Deriso suggestion, below is my simpler approach :

function functionToBeMeasured() {
    var startTime = process.hrtime();
    // do some task...
    // ......
    var elapsedSeconds = parseHrtimeToSeconds(process.hrtime(startTime));
    console.log('It takes ' + elapsedSeconds + 'seconds');
}

function parseHrtimeToSeconds(hrtime) {
    var seconds = (hrtime[0] + (hrtime[1] / 1e9)).toFixed(3);
    return seconds;
}

Name does not exist in the current context

I solved mine by using an Import directive under my Page directive. You may also want to add the namespace to your Inherits attribute of your Page directive.

Since it appears that your default namespace is "stman.Members", try: <%@ Page Title="" Language="C#" MasterPageFile="~/Members/Members.master" AutoEventWireup="true" CodeFile="Jobs.aspx.cs" Inherits="stman.Members.Members_Jobs" %> <%@ Import Namespace="stman.Members"%>

Additionally, data that I wanted to pass between aspx.cs and aspx, I put inside a static class inside the namespace. That static class was available to move data around in the name space and no longer has a "not in context" error.

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

If you want the old directive back, you can add this to your app:

Directive:

directives.directive('ngBindHtmlUnsafe', ['$sce', function($sce){
    return {
        scope: {
            ngBindHtmlUnsafe: '=',
        },
        template: "<div ng-bind-html='trustedHtml'></div>",
        link: function($scope, iElm, iAttrs, controller) {
            $scope.updateView = function() {
                $scope.trustedHtml = $sce.trustAsHtml($scope.ngBindHtmlUnsafe);
            }

            $scope.$watch('ngBindHtmlUnsafe', function(newVal, oldVal) {
                $scope.updateView(newVal);
            });
        }
    };
}]);

Usage

<div ng-bind-html-unsafe="group.description"></div>

Source - https://github.com/angular-ui/bootstrap/issues/813

How to resolve /var/www copy/write permission denied?

First off, this has nothing to do with php. This is a unix permission issue. You need to login as a superuser ( sudo/su ) and type your password, then try that command.

$ su
(type password )
\# your command

$ sudo command
$ (type password)

It might also help if you actually specified the operating system you use.

How can I undo a `git commit` locally and on a remote after `git push`

Generally, make an "inverse" commit, using:

git revert 364705c

then send it to the remote as usual:

git push

This won't delete the commit: it makes an additional commit that undoes whatever the first commit did. Anything else, not really safe, especially when the changes have already been propagated.

Can we open pdf file using UIWebView on iOS?

Swift 4

     let webView = UIWebView(frame: view.bounds)
    let targetURL = Bundle.main.url(forResource: "sampleFileName", withExtension: "pdf")
    let request = URLRequest(url: targetURL!)
    webView.loadRequest(request)
    view.addSubview(webView)

Using CSS to align a button bottom of the screen using relative positions

This will work for any resolution,

button{
    position:absolute;
    bottom: 5%;
    right:20%;
}

http://jsfiddle.net/BUuSr/

Get counts of all tables in a schema

If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:

select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;

Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

This might sound really simplistic...

But this will center the div inside the div, exactly in the center in relation to left and right margin or parent container, but you can adjust percentage symmetrically on left and right.

margin-right: 10%;
margin-left: 10%;

Then you can adjust % to make it as wide as you want it.

Find all storage devices attached to a Linux machine

Using HAL (kernel 2.6.17 and up):


#! /bin/bash
hal-find-by-property --key volume.fsusage --string filesystem |
while read udi ; do
    # ignore optical discs
    if [[ "$(hal-get-property --udi $udi --key volume.is_disc)" == "false" ]]; then
        dev=$(hal-get-property --udi $udi --key block.device)   
        fs=$(hal-get-property --udi $udi --key volume.fstype) 
        echo $dev": "$fs
    fi 
done

SQL use CASE statement in WHERE IN clause

I realize this has been answered, but there is a slight issue with the accepted solution. It will return false positives. Easy to fix:

SELECT * FROM Products P    
WHERE (@Status='published' and P.Status IN (1,3))
   or (@Status='standby' and P.Status IN  (2,5,9,6))
   or (@Status='deleted' and P.Status IN (4,5,8,10))
   or (@Status not in ('published','standby','deleted') and P.Status IN (1,2))

Parentheses aren't needed (although perhaps easier to read hence why I included them).

Controller not a function, got undefined, while defining controllers globally

If all else fails and you are using Gulp or something similar...just rerun it!

I wasted 30mins quadruple checking everything when all it needed was a swift kick in the pants.

How can I get the browser's scrollbar sizes?

Create an empty div and make sure it's present on all pages (i.e. by putting it in the header template).

Give it this styling:

#scrollbar-helper {
    // Hide it beyond the borders of the browser
    position: absolute;
    top: -100%;

    // Make sure the scrollbar is always visible
    overflow: scroll;
}

Then simply check for the size of #scrollbar-helper with Javascript:

var scrollbarWidth = document.getElementById('scrollbar-helper').offsetWidth;
var scrollbarHeight = document.getElementById('scrollbar-helper').offsetHeight;

No need to calculate anything, as this div will always have the width and height of the scrollbar.

The only downside is that there will be an empty div in your templates.. But on the other hand, your Javascript files will be cleaner, as this only takes 1 or 2 lines of code.

Confirm password validation in Angular 6

My answer is very simple>i have created password and confirm password validation using template driiven in angular 6

My html file

<div class="form-group">
  <label class="label-sm">Confirm Password</label>
  <input class="form-control" placeholder="Enter Password" type="password" #confirm_password="ngModel" [(ngModel)]="userModel.confirm_password" name="confirm_password" required (keyup)="checkPassword($event)" />
  <div *ngIf="confirm_password.errors && (confirm_password.dirty||confirm_password.touched||signup.submitted)">
  <div class="error" *ngIf="confirm_password.errors.required">Please confirm your password</div>
  </div>
  <div *ngIf="i" class='error'>Password does not match</div>
</div>

My typescript file

      public i: boolean;

      checkPassword(event) {
        const password = this.userModel.password;
        const confirm_new_password = event.target.value;

        if (password !== undefined) {
          if (confirm_new_password !== password) {
            this.i = true;
          } else {
            this.i = false;
          }
        }
      }

when clicking on submit button i check whether value of i is true or false

if true

if (this.i) {
      return false;
    }

else{
**form submitted code comes here**
}

ps1 cannot be loaded because running scripts is disabled on this system

The PowerShell execution policy is default set to Restricted. You can change the PowerShell execution policies with Set-ExecutionPolicy cmdlet. To run outside script set policy to RemoteSigned.

PS C:> Set-ExecutionPolicy RemoteSigned Below is the list of four different execution policies in PowerShell

Restricted – No scripts can be run. AllSigned – Only scripts signed by a trusted publisher can be run. RemoteSigned – Downloaded scripts must be signed by a trusted publisher. Unrestricted – All Windows PowerShell scripts can be run.

Switch statement multiple cases in JavaScript

Another way of doing multiple cases in a switch statement, when inside a function:

_x000D_
_x000D_
function name(varName){
  switch (varName) {
     case 'afshin':
     case 'saeed':
     case 'larry':
       return 'Hey';
     default:
       return 'Default case';
   }
}

console.log(name('afshin')); // Hey
_x000D_
_x000D_
_x000D_

Fit background image to div

If what you need is the image to have the same dimensions of the div, I think this is the most elegant solution:

background-size: 100% 100%;

If not, the answer by @grc is the most appropriated one.

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

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

A constructor should no have a return type . remove void before each constructor .

Some very basic characteristic of a constructor :

a. Same name as class b. no return type. c. will be called every time an object is made with the class. for eg- in your program if u made two objects of Flow, Flow flow1=new Flow(); Flow flow2=new Flow(); then Flow constructor will be called for 2 times.

d. If you want to call the constructor just for once then declare that as static (static constructor) and dont forget to remove any access modifier from static constructor ..

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Codified version of all other answers (at the time of writing):

import java.io.*;

/**
 * This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
 * <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
 * of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
 * Also includes comments and observations from others on the same question, and my own experience.
 * <p>
 * <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
 * <p>
 * <b>JVM memory management crash course</b>:
 * Java virtual machine process' heap size is bounded by the maximum memory allowed.
 * The startup and maximum size can be configured by JVM arguments.
 * JVMs don't allocate the maximum memory on startup as the program running may never require that.
 * This is to be a good player and not waste system resources unnecessarily.
 * Instead they allocate some memory and then grow when new allocations require it.
 * The garbage collector will be run at times to clean up unused objects to prevent this growing.
 * Many parameters of this management such as when to grow/shrink or which GC to use
 * can be tuned via advanced configuration parameters on JVM startup.
 *
 * @see <a href="http://stackoverflow.com/a/42567450/253468">
 *     What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
 * @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
 *     Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
 *     Full VM options reference for Windows</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
 *     Full VM options reference for Linux, Mac OS X and Solaris</a>
 * @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
 *     Java HotSpot VM Options quick reference</a>
 */
public class SystemMemory {

    // can be white-box mocked for testing
    private final Runtime runtime = Runtime.getRuntime();

    /**
     * <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
     * <p>
     * <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
     */
    public long getAllocatedTotal() {
        return runtime.totalMemory();
    }

    /**
     * <b>Current allocated free memory</b>: space immediately ready for new objects.
     * <p>
     * <i>Caution</i>: this is not the total free available memory,
     * the JVM may grow the heap for new allocations.
     */
    public long getAllocatedFree() {
        return runtime.freeMemory();
    }

    /**
     * <b>Used memory</b>:
     * Java heap currently used by instantiated objects. 
     * <p>
     * <i>Caution</i>: May include no longer referenced objects, soft references, etc.
     * that will be swept away by the next garbage collection.
     */
    public long getUsed() {
        return getAllocatedTotal() - getAllocatedFree();
    }

    /**
     * <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
     * <p>
     * <i>Caution</i>: This may change over time, do not cache it!
     * There are some JVMs / garbage collectors that can shrink the allocated process memory.
     * <p>
     * <i>Caution</i>: If this is true, the JVM will likely run GC more often.
     */
    public boolean isAtMaximumAllocation() {
        return getAllocatedTotal() == getTotal();
        // = return getUnallocated() == 0;
    }

    /**
     * <b>Unallocated memory</b>: amount of space the process' heap can grow.
     */
    public long getUnallocated() {
        return getTotal() - getAllocatedTotal();
    }

    /**
     * <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
     * <p>
     * <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
     */
    public long getTotal() {
        return runtime.maxMemory();
    }

    /**
     * <b>Total free memory</b>: memory available for new Objects,
     * even at the cost of growing the allocated memory of the process.
     */
    public long getFree() {
        return getTotal() - getUsed();
        // = return getAllocatedFree() + getUnallocated();
    }

    /**
     * <b>Unbounded memory</b>: there is no inherent limit on free memory.
     */
    public boolean isBounded() {
        return getTotal() != Long.MAX_VALUE;
    }

    /**
     * Dump of the current state for debugging or understanding the memory divisions.
     * <p>
     * <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
     */
    public String getCurrentStats() {
        StringWriter backing = new StringWriter();
        PrintWriter out = new PrintWriter(backing, false);
        out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
                getAllocatedTotal(),
                (float)getAllocatedTotal() / (float)getTotal() * 100,
                getTotal(),
                isBounded()? "bounded" : "unbounded",
                isAtMaximumAllocation()? "maxed out" : "can grow",
                getUnallocated()
        );
        out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
                getUsed(),
                (float)getUsed() / (float)getTotal() * 100,
                getTotal(),
                (float)getUsed() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
                getFree(),
                (float)getFree() / (float)getTotal() * 100,
                getTotal(),
                getAllocatedFree(),
                (float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.flush();
        return backing.toString();
    }

    public static void main(String... args) {
        SystemMemory memory = new SystemMemory();
        System.out.println(memory.getCurrentStats());
    }
}

How do I (or can I) SELECT DISTINCT on multiple columns?

I want to select the distinct values from one column 'GrondOfLucht' but they should be sorted in the order as given in the column 'sortering'. I cannot get the distinct values of just one column using

Select distinct GrondOfLucht,sortering
from CorWijzeVanAanleg
order by sortering

It will also give the column 'sortering' and because 'GrondOfLucht' AND 'sortering' is not unique, the result will be ALL rows.

use the GROUP to select the records of 'GrondOfLucht' in the order given by 'sortering

SELECT        GrondOfLucht
FROM            dbo.CorWijzeVanAanleg
GROUP BY GrondOfLucht, sortering
ORDER BY MIN(sortering)

Mergesort with Python

def merge(x):
    if len(x) == 1:
        return x
    else:
        mid = int(len(x) / 2)
        l = merge(x[:mid])
        r = merge(x[mid:])
    i = j = 0
    result = []
    while i < len(l) and j < len(r):
        if l[i] < r[j]:
            result.append(l[i])
            i += 1
        else:
            result.append(r[j])
            j += 1
    result += l[i:]
    result += r[j:]
    return result

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

The bitmap constructor has resizing built in.

Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");

http://msdn.microsoft.com/en-us/library/0wh0045z.aspx

If you want control over interpolation modes see this post.

What is N-Tier architecture?

N-tier data applications are data applications that are separated into multiple tiers. Also called "distributed applications" and "multitier applications," n-tier applications separate processing into discrete tiers that are distributed between the client and the server. When you develop applications that access data, you should have a clear separation between the various tiers that make up the application.

And so on in http://msdn.microsoft.com/en-us/library/bb384398.aspx

How to define object in array in Mongoose schema correctly with 2d geo index

You can declare trk by the following ways : - either

trk : [{
    lat : String,
    lng : String
     }]

or

trk : { type : Array , "default" : [] }

In the second case during insertion make the object and push it into the array like

db.update({'Searching criteria goes here'},
{
 $push : {
    trk :  {
             "lat": 50.3293714,
             "lng": 6.9389939
           } //inserted data is the object to be inserted 
  }
});

or you can set the Array of object by

db.update ({'seraching criteria goes here ' },
{
 $set : {
          trk : [ {
                     "lat": 50.3293714,
                     "lng": 6.9389939
                  },
                  {
                     "lat": 50.3293284,
                     "lng": 6.9389634
                  }
               ]//'inserted Array containing the list of object'
      }
});

How to access at request attributes in JSP?

EL expression:

${requestScope.Error_Message}

There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.

Replace transparency in PNG images with white background

here's how to replace the same image in all folders in a directory with white instead of transparent:

mogrify -background white -flatten */*.png

Get index of a key/value pair in a C# dictionary based on the value

If searching for a value, you will have to loop through all the data. But to minimize code involved, you can use LINQ.

Example:

Given Dictionary defined as following:

Dictionary<Int32, String> dict;

You can use following code :

// Search for all keys with given value
Int32[] keys = dict.Where(kvp => kvp.Value.Equals("SomeValue")).Select(kvp => kvp.Key).ToArray();
        
// Search for first key with given value
Int32 key = dict.First(kvp => kvp.Value.Equals("SomeValue")).Key;

Validating a Textbox field for only numeric input.

If you want to prevent the user from enter non-numeric values at the time of enter the information in the TextBox, you can use the Event OnKeyPress like this:

private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar)) e.Handled = true;         //Just Digits
            if (e.KeyChar == (char)8) e.Handled = false;            //Allow Backspace
            if (e.KeyChar == (char)13) btnSearch_Click(sender, e);  //Allow Enter            
        }

This solution doesn't work if the user paste the information in the TextBox using the mouse (right click / paste) in that case you should add an extra validation.

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

Be careful, that you do not use more than one constraint in the same direction and type.

For example: Vertical constraint for trailing = 15 and another one is >= 10.

Sometimes, Xcode creates some constraints you don't notice. You have to get rid of redundant constraints and the log warning will surely disappear.

enter image description here

Additionaly, you can read and detect some certain reasons, directly from the log:

NSLayoutConstraint:0xa338390 V:|-(15)-[UILabel:0xa331260] (Names: '|':UILabel:0xa330270 )>

This we can read as problem in UILabel constraint, it is leading vertical constraint being 15pt long.

NSLayoutConstraint:0x859ab20 H:-(13)-|[UIView:0x85a8fb0]...

This would be trailing horizontal constraint etc.

How can I convert IPV6 address to IPV4 address?

The IPAddress Java library can accomplish what you are describing here.

IPv6 addresses are 16 bytes. Using that library, if you are starting with a 16-byte array you can construct the IPv6 address object:

IPv6Address addr = new IPv6Address(bytes); //bytes is byte[16]

From there you can check if the address is IPv4 mapped, IPv4 compatible, IPv4 translated, and so on (there are many possible ways IPv6 represents IPv4 addresses). In most cases, if an IPv6 address represents an IPv4 address, the ipv4 address is in the lower 4 bytes, and so you can get the derived IPv4 address as follows. Afterwards, you can convert back to bytes, which will be just 4 bytes for IPv4.

    if(addr.isIPv4Compatible() || addr.isIPv4Mapped()) {
        IPv4Address derivedIpv4Address = addr.getEmbeddedIPv4Address();
        byte ipv4Bytes[] = derivedIpv4Address.getBytes();
        ...
     }

The javadoc is available at the link.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

just Check Your Database Table Field Length . Your Input Text Is Greater than the length of column field data type length

Python: Random numbers into a list

You could use random.sample to generate the list with one call:

import random
my_randoms = random.sample(range(100), 10)

That generates numbers in the (inclusive) range from 0 to 99. If you want 1 to 100, you could use this (thanks to @martineau for pointing out my convoluted solution):

my_randoms = random.sample(range(1, 101), 10)

How to find numbers from a string?

I was looking for the answer of the same question but for a while I found my own solution and I wanted to share it for other people who will need those codes in the future. Here is another solution without function.

Dim control As Boolean
Dim controlval As String
Dim resultval As String
Dim i as Integer

controlval = "A1B2C3D4"

For i = 1 To Len(controlval)
control = IsNumeric(Mid(controlval, i, 1))
If control = True Then resultval = resultval & Mid(controlval, i, 1)
Next i

resultval = 1234

How do you make a LinearLayout scrollable?

You can add an atrribute in linearLayout : android:scrollbars="vertical"

log4net vs. Nlog

I echo the above and do prefer nLog. Entlib is needlessly bloated.

Re:Log4net One thing that ALWAYS gets me with log4net is forgetting to add the following to the global.asax to init the component:

log4net.Config.XmlConfigurator.Configure();

Escaping double quotes in JavaScript onClick event handler

I think that the best approach is to assign the onclick handler unobtrusively.

Something like this:

window.onload = function(){
    var myLink = document.getElementsById('myLinkId');
    myLink.onclick = function(){ 
        parse('#', false, '<a href="xyz');
        return false;
    }
}

//...


<a href="#" id="myLink">Test</a>

Can a Byte[] Array be written to a file in C#?

Based on the first sentence of the question: "I'm trying to write out a Byte[] array representing a complete file to a file."

The path of least resistance would be:

File.WriteAllBytes(string path, byte[] bytes)

Documented here:

System.IO.File.WriteAllBytes - MSDN

How to subtract X days from a date using Java calendar?

int x = -1;
Calendar cal = ...;
cal.add(Calendar.DATE, x);

See java.util.Calendar#add(int,int)

Count frequency of words in a list and sort by frequency

Try this:

words = []
freqs = []

for line in sorted(original list): #takes all the lines in a text and sorts them
    line = line.rstrip() #strips them of their spaces
    if line not in words: #checks to see if line is in words
        words.append(line) #if not it adds it to the end words
        freqs.append(1) #and adds 1 to the end of freqs
    else:
        index = words.index(line) #if it is it will find where in words
        freqs[index] += 1 #and use the to change add 1 to the matching index in freqs

Fastest way to check a string contain another substring in JavaScript?

The Fastest

  1. (ES6) includes
    var string = "hello",
    substring = "lo";
    string.includes(substring);
  1. ES5 and older indexOf
    var string = "hello",
    substring = "lo";
    string.indexOf(substring) !== -1;

http://jsben.ch/9cwLJ

enter image description here

What is the default maximum heap size for Sun's JVM from Java SE 6?

One can ask with some Java code:

long maxBytes = Runtime.getRuntime().maxMemory();
System.out.println("Max memory: " + maxBytes / 1024 / 1024 + "M");

See javadoc.

What is dtype('O'), in pandas?

When you see dtype('O') inside dataframe this means Pandas string.

What is dtype?

Something that belongs to pandas or numpy, or both, or something else? If we examine pandas code:

df = pd.DataFrame({'float': [1.0],
                    'int': [1],
                    'datetime': [pd.Timestamp('20180310')],
                    'string': ['foo']})
print(df)
print(df['float'].dtype,df['int'].dtype,df['datetime'].dtype,df['string'].dtype)
df['string'].dtype

It will output like this:

   float  int   datetime string    
0    1.0    1 2018-03-10    foo
---
float64 int64 datetime64[ns] object
---
dtype('O')

You can interpret the last as Pandas dtype('O') or Pandas object which is Python type string, and this corresponds to Numpy string_, or unicode_ types.

Pandas dtype    Python type     NumPy type          Usage
object          str             string_, unicode_   Text

Like Don Quixote is on ass, Pandas is on Numpy and Numpy understand the underlying architecture of your system and uses the class numpy.dtype for that.

Data type object is an instance of numpy.dtype class that understand the data type more precise including:

  • Type of the data (integer, float, Python object, etc.)
  • Size of the data (how many bytes is in e.g. the integer)
  • Byte order of the data (little-endian or big-endian)
  • If the data type is structured, an aggregate of other data types, (e.g., describing an array item consisting of an integer and a float)
  • What are the names of the "fields" of the structure
  • What is the data-type of each field
  • Which part of the memory block each field takes
  • If the data type is a sub-array, what is its shape and data type

In the context of this question dtype belongs to both pands and numpy and in particular dtype('O') means we expect the string.


Here is some code for testing with explanation: If we have the dataset as dictionary

import pandas as pd
import numpy as np
from pandas import Timestamp

data={'id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'date': {0: Timestamp('2018-12-12 00:00:00'), 1: Timestamp('2018-12-12 00:00:00'), 2: Timestamp('2018-12-12 00:00:00'), 3: Timestamp('2018-12-12 00:00:00'), 4: Timestamp('2018-12-12 00:00:00')}, 'role': {0: 'Support', 1: 'Marketing', 2: 'Business Development', 3: 'Sales', 4: 'Engineering'}, 'num': {0: 123, 1: 234, 2: 345, 3: 456, 4: 567}, 'fnum': {0: 3.14, 1: 2.14, 2: -0.14, 3: 41.3, 4: 3.14}}
df = pd.DataFrame.from_dict(data) #now we have a dataframe

print(df)
print(df.dtypes)

The last lines will examine the dataframe and note the output:

   id       date                  role  num   fnum
0   1 2018-12-12               Support  123   3.14
1   2 2018-12-12             Marketing  234   2.14
2   3 2018-12-12  Business Development  345  -0.14
3   4 2018-12-12                 Sales  456  41.30
4   5 2018-12-12           Engineering  567   3.14
id               int64
date    datetime64[ns]
role            object
num              int64
fnum           float64
dtype: object

All kind of different dtypes

df.iloc[1,:] = np.nan
df.iloc[2,:] = None

But if we try to set np.nan or None this will not affect the original column dtype. The output will be like this:

print(df)
print(df.dtypes)

    id       date         role    num   fnum
0  1.0 2018-12-12      Support  123.0   3.14
1  NaN        NaT          NaN    NaN    NaN
2  NaN        NaT         None    NaN    NaN
3  4.0 2018-12-12        Sales  456.0  41.30
4  5.0 2018-12-12  Engineering  567.0   3.14
id             float64
date    datetime64[ns]
role            object
num            float64
fnum           float64
dtype: object

So np.nan or None will not change the columns dtype, unless we set the all column rows to np.nan or None. In that case column will become float64 or object respectively.

You may try also setting single rows:

df.iloc[3,:] = 0 # will convert datetime to object only
df.iloc[4,:] = '' # will convert all columns to object

And to note here, if we set string inside a non string column it will become string or object dtype.

Sorting an Array of int using BubbleSort

public class SortingArray {
public static void main(String[] args) {

int[] a={3,7,9,5,1,4,0,2,8,6};
int temp=0;

boolean isSwapped=true;


System.out.println(" before sorting the array: ");

for(int i=0;i<a.length;i++)
{
    System.out.print(a[i]);
}
System.out.println("");

do
{

isSwapped=false;

for(int i=0;i<a.length-1;i++)

{

    if(a[i]>a[i+1])

    {

        temp=a[i];

        a[i]=a[i+1];

        a[i+1]=temp;

    }



}


}while(isSwapped);


System.out.println("after sorting the array: ");

    for(int array:a)

    {

        System.out.print(array);


    }
  }
}

Remove element of a regular array

In a normal array you have to shuffle down all the array entries above 2 and then resize it using the Resize method. You might be better off using an ArrayList.

How do I use $scope.$watch and $scope.$apply in AngularJS?

There are $watchGroup and $watchCollection as well. Specifically, $watchGroup is really helpful if you want to call a function to update an object which has multiple properties in a view that is not dom object, for e.g. another view in canvas, WebGL or server request.

Here, the documentation link.

Get docker container id from container name

Thanks for the answer of https://stackoverflow.com/a/65513726/889126, it gave me an idea to make a complete bash script as it is

export api_image_id=$(docker inspect --format="{{.Id}}" <image-name> | sed '/^[[:space:]]*$/d')

sudo docker exec -i -t ${api_image_id} /bin/bash

I need a specific container and make a script to extract some info from it in a quick sight.

Hope this would help others.

How do I list loaded plugins in Vim?

The problem with :scriptnames, :commands, :functions, and similar Vim commands, is that they display information in a large slab of text, which is very hard to visually parse.

To get around this, I wrote Headlights, a plugin that adds a menu to Vim showing all loaded plugins, TextMate style. The added benefit is that it shows plugin commands, mappings, files, and other bits and pieces.

How to export datagridview to excel using vb.net?

Dim rowNo1 As Short Dim numrow As Short Dim colNo1 As Short Dim colNo2 As Short

    rowNo1 = 1
    colNo1 = 1
    colNo2 = 1
    numrow = 1

    ObjEXCEL = CType(CreateObject("Excel.Application"), Microsoft.Office.Interop.Excel.Application)
    objEXCELBook = CType(ObjEXCEL.Workbooks.Add, Microsoft.Office.Interop.Excel.Workbook)
    objEXCELSheet = CType(objEXCELBook.Worksheets(1), Microsoft.Office.Interop.Excel.Worksheet)

    ObjEXCEL.Visible = True

    For numCounter = 0 To grdName.Columns.Count - 1
        ' MsgBox(grdName.Columns(numCounter).HeaderText())
        If grdName.Columns(numCounter).Width > 0 Then
            ObjEXCEL.Cells(1, numCounter + 1) = grdName.Columns(numCounter).HeaderText()
        End If
        ' ObjEXCEL.Cells(1, numCounter + 1) = grdName.Columns.GetFirstColumn(DataGridViewElementStates.Displayed)
    Next numCounter

    ObjEXCEL.Range("A:A").ColumnWidth = 10
    ObjEXCEL.Range("B:B").ColumnWidth = 25
    ObjEXCEL.Range("C:C").ColumnWidth = 20
    ObjEXCEL.Range("D:D").ColumnWidth = 20
    ObjEXCEL.Range("E:E").ColumnWidth = 20
    ObjEXCEL.Range("F:F").ColumnWidth = 25

    For rowNo1 = 0 To grdName.RowCount - 1
        For colNo1 = 0 To grdName.ColumnCount - 1
            If grdName.Columns(colNo1).Width > 0 Then
                If Trim(grdName.Item(colNo1, rowNo1).Value) <> "" Then
                    'If IsDate(grdName.Item(colNo1, rowNo1).Value) = True Then
                    '    ObjEXCEL.Cells(numrow + 1, colNo2) = Format(CDate(grdName.Item(colNo1, rowNo1).Value), "dd/MMM/yyyy")
                    'Else
                    ObjEXCEL.Cells(numrow + 1, colNo2) = grdName.Item(colNo1, rowNo1).Value
                    'End If
                End If
                If colNo2 >= grdName.ColumnCount Then
                    colNo2 = 1
                Else
                    colNo2 = colNo2 + 1
                End If
            End If
        Next colNo1
        numrow = numrow + 1
    Next rowNo1

What's the easiest way to call a function every 5 seconds in jQuery?

you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)

<script>
  var time = 3670;
window.setInterval(function(){

  // Time calculations for days, hours, minutes and seconds
    var h = Math.floor(time / 3600);
    var m = Math.floor(time % 3600 / 60);
    var s = Math.floor(time % 3600 % 60);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  h + "h "
  + m + "m " + s + "s ";

  // If the count down is finished, write some text 
  if (time < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

  time--;
}, 1000);


</script>

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

I faced same issue (VS 2015), but my application is running under 32-bit application pool. So even though machine is 64-bit. I installed 32-bit installation and it works.

Delete all files of specific type (extension) recursively down a directory using a batch file

You can use wildcards with the del command, and /S to do it recursively.

del /S *.jpg

Addendum

@BmyGuest asked why a downvoted answer (del /s c:\*.blaawbg) was any different than my answer.

There's a huge difference between running del /S *.jpg and del /S C:\*.jpg. The first command is executed from the current location, whereas the second is executed on the whole drive.

In the scenario where you delete jpg files using the second command, some applications might stop working, and you'll end up losing all your family pictures. This is utterly annoying, but your computer will still be able to run.

However, if you are working on some project, and want to delete all your dll files in myProject\dll, and run the following batch file:

@echo off

REM This short script will only remove dlls from my project... or will it?

cd \myProject\dll
del /S /Q C:\*.dll

Then you end up removing all dll files form your C:\ drive. All of your applications stop working, your computer becomes useless, and at the next reboot you are teleported in the fourth dimension where you will be stuck for eternity.

The lesson here is not to run such command directly at the root of a drive (or in any other location that might be dangerous, such as %windir%) if you can avoid it. Always run them as locally as possible.

Addendum 2

The wildcard method will try to match all file names, in their 8.3 format, and their "long name" format. For example, *.dll will match project.dll and project.dllold, which can be surprising. See this answer on SU for more detailed information.

What is the most useful script you've written for everyday life?

I wrote a cron job to grab the ip address of my dads router and ftp it to a secure location so when he needed help I could remote desktop in and fix his comp.

JDK was not found on the computer for NetBeans 6.5

Do the following steps to resolve the problem

  1. Ensure that the JDK is already installed.

  2. If the installer is on a CD, Copy the EXE file for the Netbeans 6.5.1 installer onto your hard disk.

  3. Note the location of the installer.

  4. Open a Command Prompt running as administrator: Go to Start button > All Programs > Accessories Right click Command Prompt Select Run as administrator

  5. In the Command Prompt use the cd command to change to the directory containing the installer.

  6. Execute the following command to extract the contents of the installer: [Note: You might need to change the name of the installer to match the one you have.]

    netbeans-6.5.1-ml-java-windows.exe --extract

  7. Execute the following command to manually execute the installer:

    java -jar bundle.jar

You will see rapid scrolling output in the Command Prompt window for a few moments, then the installer window will appear to begin the installation process.

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

Add labels to each argument in your plot call corresponding to the series it is graphing, i.e. label = "series 1"

Then simply add Pyplot.legend() to the bottom of your script and the legend will display these labels.

GitHub authentication failing over https, returning wrong email address

Same thing happened with me, when i have enabled 2-way authentication for github. Things i did to resolve:

  • Get you personal access token. This you have to check and generate if not available already. Link for this: https://github.com/settings/tokens
  • Go to your local and delete folder and re-clone branch from github.
  • Now try the command you were trying earlier i.e: git pull origin master
  • Enter username and In password paste the token generated and also don't forget to save that token somewhere, so you can re-use if required.

Doing this will solve your issue.

Select all child elements recursively in CSS

The rule is as following :

A B 

B as a descendant of A

A > B 

B as a child of A

So

div.dropdown *

and not

div.dropdown > *

AngularJS ng-click stopPropagation

<ul class="col col-double clearfix">
 <li class="col__item" ng-repeat="location in searchLocations">
   <label>
    <input type="checkbox" ng-click="onLocationSelectionClicked($event)" checklist-model="selectedAuctions.locations" checklist-value="location.code" checklist-change="auctionSelectionChanged()" id="{{location.code}}"> {{location.displayName}}
   </label>



$scope.onLocationSelectionClicked = function($event) {
      if($scope.limitSelectionCountTo &&         $scope.selectedAuctions.locations.length == $scope.limitSelectionCountTo) {
         $event.currentTarget.checked=false;
      }
   };

How do I create a foreign key in SQL Server?

You can also name your foreign key constraint by using:

CONSTRAINT your_name_here FOREIGN KEY (question_exam_id) REFERENCES EXAMS (exam_id)

how to add script src inside a View when using Layout

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.

_Layout

<!DOCTYPE html>
<html>
  <head>
    <title>...</title>
    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    @RenderSection("Scripts",false/*required*/)
  </head>
  <body>
    @RenderBody()
  </body>
</html>

View

@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
  <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}

Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.

How to check if all inputs are not empty with jQuery

Use each:

var isValid;
$("input").each(function() {
   var element = $(this);
   if (element.val() == "") {
       isValid = false;
   }
});

However you probably will be better off using something like jQuery validate which IMO is cleaner.

VBA vlookup reference in different sheet

The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range you use. Please read this explanation and its conclusion, which I guess will give essential information.

The error you are getting is likely due to the sought-for value Sheet2!D2 not being found in the searched range Sheet1!A1:A65536. This may stem from two cases:

  1. The value is actually not present (pointed out by chris nielsen).

  2. You are searching the wrong Range. If the ActiveSheet is Sheet1, then using Range("D2") without qualifying it will be searching for Sheet1!D2, and it will throw the same error even if the sought-for value is present in the correct Range. Code accounting for this (and items below) follows:

    Sub srch()
        Dim ws1 As Worksheet, ws2 As Worksheet
        Dim srchres As Variant
    
        Set ws1 = Worksheets("Sheet1")
        Set ws2 = Worksheets("Sheet2")
    
        On Error Resume Next
        srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
        On Error GoTo 0
        If (IsEmpty(srchres)) Then
          ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
        Else
          ws2.Range("E2").Value = srchres
        End If
    End Sub
    

I will point out a few additional notable points:

  1. Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup (although it will not suitably handle case 2 above).

  2. This catching is actually performed by the function VLOOKUP as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...).

  3. Using =VLOOKUP... is fundamentally different from Application.WorksheetFunction.VLookup: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.

  4. Both solutions by L42 qualify Ranges suitably.

  5. You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).

JavaScript: remove event listener

You could use a named function expression (in this case the function is named abc), like so:

let click = 0;
canvas.addEventListener('click', function abc(event) {
    click++;
    if (click >= 50) {
        // remove event listener function `abc`
        canvas.removeEventListener('click', abc);
    }
    // More code here ...
}

Quick and dirty working example: http://jsfiddle.net/8qvdmLz5/2/.

More information about named function expressions: http://kangax.github.io/nfe/.

How can I upgrade NumPy?

Because you have multiple versions of NumPy installed.

Try pip uninstall numpy and pip list | grep numpy several times, until you see no output from pip list | grep numpy.

Then pip install numpy will get you the newest version of NumPy.

What is the default stack size, can it grow, how does it work with garbage collection?

How much a stack can grow?

You can use a VM option named ss to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M to set the maximum of stack size to 1M.

Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss set the size of the Java Stack in most cases.

For many JVMs, they put different default values for stack size on different platforms.

Can we limit this growth?

When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).

Does stack has some default minimum value or default maximum value?

As I said before, different VMs are different, and may change over versions. See here.

how does garbage collection work on stack?

Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.

This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

Rails Model find where not equal

Rails 4

GroupUser.where.not(user_id: me)

How do I include negative decimal numbers in this regular expression?

This will allow a - or + character only when followed by a number:

 ^([+-](?=\.?\d))?(\d+)?(\.\d+)?$

Get program execution time in the shell

If you intend to use the times later to compute with, learn how to use the -f option of /usr/bin/time to output code that saves times. Here's some code I used recently to get and sort the execution times of a whole classful of students' programs:

fmt="run { date = '$(date)', user = '$who', test = '$test', host = '$(hostname)', times = { user = %U, system = %S, elapsed = %e } }"
/usr/bin/time -f "$fmt" -o $timefile command args...

I later concatenated all the $timefile files and pipe the output into a Lua interpreter. You can do the same with Python or bash or whatever your favorite syntax is. I love this technique.

Checking character length in ruby

Ruby provides a built-in function for checking the length of a string. Say it's called s:

if s.length <= 25
  # We're OK
else
  # Too long
end

Set an empty DateTime variable

No. You have 2 options:

DateTime date = DateTime.MinValue;

This works when you need to do something every X amount of time (since you will always be over MinValue) but can actually cause subtle errors (such as using some operators w/o first checking if you are not MinValue) if you are not careful.

And you can use Nullable:

DateTime? date = null;

Which is nice and avoids most issues while introducing only 1 or 2.

It really depends on what you are trying to achieve.

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

Necessary to add link tag for favicon.ico?

We can add for all devices with platform specific size

<link rel="apple-touch-icon" sizes="57x57" href="fav_icons/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="fav_icons/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="fav_icons/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="fav_icons/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="fav_icons/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="fav_icons/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="fav_icons/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="fav_icons/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="fav_icons/apple-icon-180x180.png">

<link rel="icon" type="image/png" sizes="192x192"  href="fav_icons/android-icon-192x192.pn">
<link rel="icon" type="image/png" sizes="32x32" href="fav_icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="fav_icons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="fav_icons/favicon-16x16.png">

plot different color for different categorical levels using matplotlib

Using Altair.

from altair import *
import pandas as pd

df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')

enter image description here

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

I resolved this issue by downgrading my Firefox to an older version that had previously worked well with Selenium-WebDriver. In my case, I had to downgrade back to Firefox 18 and this version worked with Selenium 2.27

Here is the link to get older versions of firefox: https://ftp.mozilla.org/pub/mozilla.org/firefox/releases/

How to show progress bar while loading, using ajax

This link describes how you can add a progress event listener to the xhr object using jquery.

$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();

        // Upload progress
        xhr.upload.addEventListener("progress", function(evt){
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                //Do something with upload progress
                console.log(percentComplete);
            }
       }, false);
       
       // Download progress
       xhr.addEventListener("progress", function(evt){
           if (evt.lengthComputable) {
               var percentComplete = evt.loaded / evt.total;
               // Do something with download progress
               console.log(percentComplete);
           }
       }, false);
       
       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        // Do something success-ish
    }
});

HTML embedded PDF iframe

It's downloaded probably because there is not Adobe Reader plug-in installed. In this case, IE (it doesn't matter which version) doesn't know how to render it, and it'll simply download the file (Chrome, for example, has its own embedded PDF renderer).

That said. <iframe> is not best way to display a PDF (do not forget compatibility with mobile browsers, for example Safari). Some browsers will always open that file inside an external application (or in another browser window). Best and most compatible way I found is a little bit tricky but works on all browsers I tried (even pretty outdated):

Keep your <iframe> but do not display a PDF inside it, it'll be filled with an HTML page that consists of an <object> tag. Create an HTML wrapping page for your PDF, it should look like this:

<html>
<body>
    <object data="your_url_to_pdf" type="application/pdf">
        <embed src="your_url_to_pdf" type="application/pdf" />
    </object>
</body>
</html>

Of course, you still need the appropriate plug-in installed in the browser. Also, look at this post if you need to support Safari on mobile devices.

1st. Why nesting <embed> inside <object>? You'll find the answer here on SO. Instead of a nested <embed> tag, you may (should!) provide a custom message for your users (or a built-in viewer, see next paragraph). Nowadays, <object> can be used without worries, and <embed> is useless.

2nd. Why an HTML page? So you can provide a fallback if PDF viewer isn't supported. Internal viewer, plain HTML error messages/options, and so on...

It's tricky to check PDF support so that you may provide an alternate viewer for your customers, take a look at PDF.JS project; it's pretty good but rendering quality - for desktop browsers - isn't as good as a native PDF renderer (I didn't see any difference in mobile browsers because of screen size, I suppose).

How to uninstall / completely remove Oracle 11g (client)?

Do everything suggested by ziesemer.

You may also want to :

  • Stop the Oracle-related services (before deleting them from the registry).
  • In the registry, look not only for entries named "Oracle" but also e.g. for "ODP".

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

Old question but here is the approach we have used ever since Visual Studio 2005 with success. I just tested it using Visual Studio 2012 Update 4 as well (since we are finally updating our software from 2010 to 2012).

Since the Visual C++ Redistributable packages register their uninstaller with windows (so it shows up in the Control Panel "Programs and Features" list), we simply check for the Display Name of the uninstaller key in the registry.

Here is the relevant NSIS code:

ReadRegStr $0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{33d1fd90-4274-48a1-9bc1-97e33d9c2d6f}\" "DisplayName"
StrCmp $0 "Microsoft Visual C++ 2012 Redistributable (x86) - 11.0.61030" vs2012redistInstalled
DetailPrint "Microsoft Visual C++ 2012 Update 4 Redistributable not found!"
DetailPrint "Downloading from www.mywebsite.com"
; insert applicable download code here
ExecWait '"<downloaded redist exe>" /promptrestart /passive'
vs2012redistInstalled:

Note that since our installer is a 32bit exe, windows handles determining if the registry key is actually in the virtualized Wow6432Node instead of the above location so the above code works on both 64bit and 32bit windows installs without having to check both keys explicitly.

Also note that to update the above code to a different version of the VC++ Redist, simply change the GUID in the registry key path and the display name to whatever you need.

While this may not be the recommended method, It has worked on 10,000+ machines over the past 10 years running every flavor of windows from XP/XP64 Through Windows 10 using redists for 2005, 2010, 2010sp1, and now 2012u4.

How can I run a php without a web server?

PHP is a normal sripting language similar to bash or python or perl. So a script with shebang works, at least on linux.

Example PHP file:

#!/usr/bin/env php

<?php

echo("Hello World!\n")

?>

How to run it:

$ chmod 755 hello.php  # do this only once
$ ./hello.php

Multi-character constant warnings

Simplest C/C++ any compiler/standard compliant solution, was mentioned by @leftaroundabout in comments above:

int x = *(int*)"abcd";

Or a bit more specific:

int x = *(int32_t*)"abcd";

One more solution, also compliant with C/C++ compiler/standard since C99 (except clang++, which has a known bug):

int x = ((union {char s[5]; int number;}){"abcd"}).number;

/* just a demo check: */
printf("x=%d stored %s byte first\n", x, x==0x61626364 ? "MSB":"LSB");

Here anonymous union is used to give a nice symbol-name to the desired numeric result, "abcd" string is used to initialize the lvalue of compound literal (C99).

How to remove all whitespace from a string?

Please note that soultions written above removes only space. If you want also to remove tab or new line use stri_replace_all_charclass from stringi package.

library(stringi)
stri_replace_all_charclass("   ala \t  ma \n kota  ", "\\p{WHITE_SPACE}", "")
## [1] "alamakota"

SoapUI "failed to load url" error when loading WSDL

If you are running your Web Application with the default port of 8080, please try to change the port to some other value and run your application again and trigger again your SOAPUI request. As you might have history projects in your SOAP UI workspace with port number 8080, might create issues.

Select elements by attribute in CSS

    [data-value] {
  /* Attribute exists */
}

[data-value="foo"] {
  /* Attribute has this exact value */
}

[data-value*="foo"] {
  /* Attribute value contains this value somewhere in it */
}

[data-value~="foo"] {
  /* Attribute has this value in a space-separated list somewhere */
}

[data-value^="foo"] {
  /* Attribute value starts with this */
}

[data-value|="foo"] {
  /* Attribute value starts with this in a dash-separated list */
}

[data-value$="foo"] {
  /* Attribute value ends with this */
}

How do I link to Google Maps with a particular longitude and latitude?

To open the google maps app in android:-

geo:<lat>,<lng>?z=<zoom>

open app with marker for give location:-

geo:<lat>,<lng>?q=<lat>,<lng>(Label,Name)

open google map in ios:-

comgooglemaps://?q=<lat>,<lng>

open google maps in browser with following parameters:-

http://maps.google.com/maps?z=12&t=m&q=<lat>,<lng>
  • z is the zoom level (1-21)
  • t is the map type ("m" map, "k" satellite, "h" hybrid, "p" terrain, "e" GoogleEarth)
  • q is the search query

What is the difference between RTP or RTSP in a streaming server?

I hear your pain. I'm going through this right now (years later). From what I've learned, you can think of RTSP as a "VCR controller", the protocol allows you to specify which streams (presentations) you want to play, it will then send you a description of the media, and then you can use RTSP to play, stop, pause, and record the remote stream. The media itself goes over RTP. RTSP is normally implemented over a different socket or communication layer. Although it is simply a protocol, most often it's implemented by a server over a socket. For live streams, the RTSP stream you request is simply a name of a stream. It doesn't need to refer to a file on the server, the server's RTSP implementation can parse that stream, put together a live graph, and then provide the SDP (description) for that stream name. But, this is of course specific to the way the RTSP server has been implemented. For "live" streams, it's probably simpler to just use RTP, but you'll need a way to transfer the SDP from the RTP server to the client that wants to play that stream.

How to catch a click event on a button?

/src/com/example/MyClass.java

package com.example

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MyClass extends Activity
{

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);    

    Button button = (Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener()
    {
      public void onClick(View v)
      {
         ImageView iv = (ImageView) findViewById(R.id.imageview1);
         iv.setVisibility(View.VISIBLE);
      }
    });

  }
}

/res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
    <Button 
      android:text="Button"
      android:id="@+id/button1"
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"
    />
    <ImageView 
      android:src="@drawable/image" 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:id="@+id/imageview1"
      android:visibility="invisible"
    />
</LinearLayout>

Winforms TableLayoutPanel adding rows programmatically

I just looked into my code. In one application, I just add the controls, but without specifying the index, and when done, I just loop through the row styles and set the size type to AutoSize. So just adding them without specifying the indices seems to add the rows as intended (provided the GrowStyle is set to AddRows).

In another application, I clear the controls and set the RowCount property to the needed value. This does not add the RowStyles. Then I add my controls, this time specifying the indices, and add a new RowStyle (RowStyles.Add(new RowStyle(...)) and this also works.

So, pick one of these methods, they both work. I remember the headaches the table layout panel caused me.

What is the purpose of Node.js module.exports and how do you use it?

the module.exports property or the exports object allows a module to select what should be shared with the application

enter image description here

I have a video on module_export available here

How can I limit possible inputs in a HTML5 "number" element?

Maycow Moura's answer was a good start. However, his solution means that when you enter the second digit all editing of the field stops. So you cannot change values or delete any characters.

The following code stops at 2, but allows editing to continue;

//MaxLength 2
onKeyDown="if(this.value.length==2) this.value = this.value.slice(0, - 1);"

Razor View Engine : An expression tree may not contain a dynamic operation

Before using (strongly type html helper into view) this line

@Html.TextBoxFor(p => p.Product.Name)

You should include your model into you page for making strongly type view.

@model SampleModel

How to set the 'selected option' of a select dropdown list with jquery

Try this :

$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");

Just replace option[value="Bruce Jones"] by option[value=result[0]]

And before selecting a new option, you might want to "unselect" the previous :

$('select[name^="salesrep"] option:selected').attr("selected",null);

You may want to read this too : jQuery get specific option tag text

Edit: Using jQuery Mobile, this link may provide a good solution : jquery mobile - set select/option values

How to embed images in email

Here is how to get the code for an embedded image without worrying about any files or base64 statements or mimes (it's still base64, but you don't have to do anything to get it). I originally posted this same answer in this thread, but it may be valuable to repeat it in this one, too.

To do this, you need Mozilla Thunderbird, you can fetch the html code for an image like this:

  1. Copy a bitmap to clipboard.
  2. Start a new email message.
  3. Paste the image. (don't save it as a draft!!!)
  4. Double-click on it to get to the image settings dialogue.
  5. Look for the "image location" property.
  6. Fetch the code and wrap it in an image tag, like this:

You should end up with a string of text something like this:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaIAAAGcCAIAAAAUGTPlAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAPbklEQVR4nO3d2ZbixhJAUeku//8vcx/oxphBaMgpIvd+c7uqmqakQ6QkxHq73RaA3tZ13fNlJ5K1yhzQy860fbS/XTIHtHOla9/8jJjMARXV6No332omc0BhLdP27r1pMgeU0bduz16yJnPAVeME7uG5bDIHxTzv7bn3rAG79u7xK/in7+OArNY14QwRom7v/tf7AUASQROw07qu4f6Bjwcsc1BLuC58FDFwD/dHbtEKtWwvWl/aMeAKN27dXpjmoIyLnRqtKaM9ntPWdTXNQRWHRrmhjPzYzjHNQXnnJrsR+jLCYyjONAej6Ht4LmXg7kxzUMahTAx1wiH0udQ9ZA6G0Ct8uQN3Z9EKBeyPxThvCJshcHcJ348CFx29ou1jLz7cDmikC+Xmadxi0Qo/XS/C+8EvjWvJohX+42gCtr9+56DX0myNW0xzsMeJNHw7falx7Znm4Lyj1ThxmK9gFuds3GKagxdfPzblr+c/afWgCoj1aMtyphVevZ8uKNKIc2ds93zjTzM3brFohXc1Xvs7zhOTN24xzcFOvWKR7P5OXTg2ByRnmoO9ak9GxXdGo9yyLLfbzTQHQ9C4ekxzcECNdtTYBzXu7v7cmubggOJJMmc0IHPQTaXGGeXuHk+v6+agg3pDnMa9M83BAW3eDsF1z0+yzMFe4zfOKPeRzEFT9UqkcQ8vryUyB7sUjEiNHmncBqcg4LfiEbn/wPd7nzhsd937c2iagx9aLjPP/V1GuW2mOdhSqiCPEaPSYMjdx3FY5uCr6wV53+ue/+Tjz19Xb8EsTObgsyuNu9KpQ99rlHv27amTOfjgXD6O1q3U7dfZJnPwqvjndVX6URL5bOOpkzn4j0PtuB44h+GK2H4aXVACf3z7AOlvNj7qsNAj2mKU2880B8tybaG6ffmbea22358M6XcAZRv381uuM8o97HliTXNpeRfRTlcWqvu/t8jVcOp2jszNwkWnH51uXMviqNs3OzdpmcvJjrHH4G8g9UssReYmYqB7diIiTqEOZf/GLHNhXD/WpnEPA6ZkwIc0skMbs+vmYjh6xx5F2zBUUNa/ej+QSI5u3qa5WQjf3ThBGeeRpCdzgW0fa7v/r8ddats9rIGNUJYRHkNoJzZmmQtMvA7p3pfuDyCBc9u8zGVmv7rzPORw+nXdKYgYTvyC7dt3ngdMc2FcuQR/5xVzyd4fJnCZXNkaTXOBbezGRa59DZ2J0A+eFxdfcWUuNjvzR56WTK6vKmQuocl38sn/+ckUOXIic+HZq595NjIpdXRY5kLauOvZuaNyH78r3CkIjcuk4ObnTOu83qMQrmtkVXZTNM0lcW/WnnOvWd8rnu9fNK3iL7emuTx+7uduasL4amyHpjmWReMYQ6XtUObQOJKTudlpHIOotyk6NjeiZO8thW21t3CZG87H95ZW2g72/1jlpZIG25JFa1TXN47Tjfv4J3BCm9dLmYuheFaMY/R1u92abYQyF4MqkUnj7VnmZpQymin/Ufm0HOIeZG44tTeCIp9jPWBTHC4cXJfA3dU6hUcpz3vvxo1Jdkr56xa4wXXf6mQugG+lO7p7p/ld61ogI2x1rpsLpt41dCGujBO4EEbbeGQuntOl21j/FvxbKhG42h6/7tNP9VAbzLOxNmW++XYLzCI7/+12G/PuwdLWTPffdVUyF0OvHb7bqTGBa2WGArighK80Lr0ZGrfIXBT1NsfbX5V+/lEa18w4v/TanIKY1M9NvP0+IHAtzdO4xbG5cC62YMxft8C1NOY2UJVpbgrDbtkC19iwW0JVjs3lN+yWrXGNDbsl1GaaowOBa2/axi0yl96hjbvBRcIC197MgbuzaGVZlmVd128BKhgmjWtP4xbTXG7bm/j+6Ny/8soOI3BdaNydzM2oZXQErguBe+a6uUgOJePjb7bxZXca14Wd+oVjc7PYOPp26IdU+mJK0bh3MpfT9dupX6RxXWjcR47NZdalNQLXhcBtkLmEvt0ms4jtuwprXBfNGhfiTvrvZC6Mo9d/NCZwvexszaFb5P/8CbE4NkcBcXeA6E407v0/T4vyezfNxTDy9jTyY0ts/0TmF2Sa4xK7UBfXD4qV+rCk6z+kAZnjpCIX4nHO9Wf+RKGiRO2dd0EEoCZs2LMLf/sAzP0ePyFiMUxzENueV8GXNk3VuEXmxmeU46eql0lGb9ziTCvwUabXV9Mc5Hf0urnrx/KGYpobWqZXVEJocKP89kxzEN6JDH3MWdaXVdPcuLJuczS2Z0Pa+Jroo9wiczC57QgmaNwic8MyylHExoY0zzbm2BzEVm/gyjHKLaa5Mc3zMstFVUuU4MLgO5mDqH7Wp/h95d7/xut362zAW/eHY5RjfPduRLmK2DQHHBbrxdgpiLHE2nrgxZgbsGkOKPY+ijEXraa5gYz5SsgMTmx7YxbtI5kDluXUXe8v3q2zGWdaR2GUYxzJsmCaA14le9E1zQ0h2VZFGjn6YJoDvsrxAixzwJYEH8jrujngt3Vd39/gFWVJ69jcEKK/WhLIx13+9BYYIiAy15/G0dLpz6Iu9QPbs2iFuTyWnzs9f3HQl2SnIGA6QWt1msxBErfbrfb68f3nj79iXWQOcnjkZmfsigx0IRq3OAUxgtlWEJS1vQvP8PmEPzkFAVHtidTja2Z+NTXN9Tfz9sc5p3fbOYc7metP5tiv1A77batLGQSZG4LSsa3GfhroLucXOdMKQ2twmcizlK+4TkEM4Xa7pdy8OK3XVGWao6KUmxcnNBvf5tnkHJsbi5kuqCvzeN99MOKNlY6SuXFJXiDv92Lb+S00IHMxSN7I7ESDk7nY5K87e9D4nIIITOO607gQZC4qjYOdXDcXksZ1Z44LxDQXj8Z1p3GxyBwco3HhyFwwRrm+NC4imYO9NC4omYNdNC4umYvEirUXjQtN5sLQuF40LjrXzcFXApeDaS4Go1x7GpeGzMEHGpeJRSv8h8DlI3Pwh8BlJXMBODBXm8Dl5tgcs9O49GRudEa5qjRuBhatTErg5iFzTEfgZiNzQ7NiLUvg5iRzTEHgZiZzJCdwONM6LivW6zSOxTRHVgLHg2mOhDSOZ6a5QVmxnqBufCRzZCBwbLBoJTyNY9tqExmQFes5NmY+Ms2Rx7quXiF4J3Nko3S8kDkSUjqeydxw7KJFeBp5kDkgOZkjLQMddzIHJCdzYzGAQHEyByQnc0ByMkda3vvFncwNxIE5qEHmgORkjpysWHmQOSA5mSMhoxzPZA5ITubIxijHC5kjFY3jncwBycncKFwbfJ1Rjo9kjiQ0jm9kjgw0jg0yByT3T+8HAFf9HOVejnsa/WZjmhuC8w+nHW0cE5I5Ajs3lwnfbGSOqKw92UnmCOlK4/RxNk5BkNztdju3Sn3+LmUMzTRHPKejc7vddn7vSxkdzgtN5vqzCx1isOIomSOSE40r9Sri1SgumSOMjo0797czCJkjhsaNE7VMnGklgJaN+/iNqheazDG6Nol5r5u0pSFzjK7qsf9vP1zjMpE5ZrSdTo1LRuaYyJ7BUOPycaYV/qVxKckc/KFxWckcLIvGpSZzoHHJyRws67p6y2pizrTCH4/SvQx3PjEnOtMcvFr/+vZ/Gz8eLjLNwVeKloPM8cd9LTbVjr1n+fnxCVnX1dI1EItWluVph7f37uFZikXmOhtweppnH/ber0lYtPJhTz79aVilbJ/r7Ev4wnGIobPuO/DGBtDmsbn1ObXJXGcjZ+6h7IMsvsldfHh2gfQsWqe2cw+/eBK2dkcmPEfMIaa5zoY6BBbdxpO5ncJkzwMvTHPk8XOs+/YFz38iefm4oIRsPp44fvnP7ideaEnm5pV4bNnzT9uOHZnIHPkdHdAMdMnIXE92p2YOPdWmvGRkblK59+T9Ucv9PHAnc8xiZ/uELx8XlDCLb/3StfRMcySkXDyTuRlNWIEJ/8k8WLSSk67xYJoDkpO56RhzmI3MAcnJ3FyMckxI5oDkZG4iRjnmJHNAcjIHJCdzQHIyByQnc7Nw/oFpyRyQnMwByclcNz4IAtqQuSk4MMfMZA5ITuaA5GQuPytWJidzQHIyByQnc8lZsYLMAcnJHJCczGVmxQqLzPXinV7QjMylZZSDO5kDkpO5nIxy8CBzQHIyByQnc0ByMgckJ3MJOf8Az2SuA9cGQ0syByQnc9lYscILmQOSkzkgOZkDkpO51qqeZnVgDt7JHJCczAHJyVweVqzwkcwByclcU/XOPxjl4BuZA5KTOSA5mcvAihU2yByQnMy1U+n8g1EOtskckJzMAcnJXGxWrPCTzAHJyVwjNc4/GOVgD5kDkpM5IDmZi8qKFXaSOSA5mQvJKAf7yVwLVT/mBtgmc0ByMhePFSscInNAcjIXjFEOjpK56px/gL5kDkhO5uoqO8pZscIJMgckJ3NhGOXgHJmryMkHGIHMAcnJXAxWrHCazNVixQqDkLkAjHJwhcwByclcFQVXrEY5uEjmgORkbmhGObhO5oDkZG5cRjkoQubKc8UcDEXmBmWUg1JkrjCjHIxG5kZklIOCZA5ITuZKsmKFAclcMaUaZ8UKZcncWDQOipO5MixXYVgyNxCjHNQgcwUY5WBkMjcKoxxUInNXFRnlNA7qkTkgOZnrzygHVcncJU4+wPhk7jxH5SAEmQOSk7mTjHIQhcwBycncGc48QCAy140VK7Qhc4c5KgexyFwHGgctydwx10c5jYPGZA5ITuYOMMpBRDK3l8ZBUDK3i8ZBXDIHJCdzvxnlIDSZ+0HjIDqZ2+K9q5CAzH3lTV2Qg8wBycncZ0Y5SEPmPtA4yETmXmkcJCNz5WkcDEXm/sNVcpCPzP1L4yAlmftD4yArmVsWjYPUZM47uiC52TPn8hFIb+rMaRzMYN7MaRxMYtLMaRzMY8bMaRxMZbrMaRzMZq7MaRxM6J/eD6CRUhfHaRyEM8U0p3Ews/yZ0ziYXOZFa8F3cWkcxJV2mtM44C7nNGehCjxky5whDniRJ3Nl76ekcZBGhswJHLAhduaK3xFT4yCfwGdaNQ7YI+Q0J3DAfsEyV+NzGzQOcguTuUofTKNxkF6AzAkccMW4mav3uYICB1MZMXNVPzhV42A2Y2VO4IDiRsmcwAGV9Mxc1bTdCRzQJ3MCBzTTOnO1A6duwIsWmWswuy0CB3xRJXNtuvYgcMCGYplrnLY7gQN+upq5LnVbBA7Y7VjmekXtmcABh+zKXPe6SRtw2mvmuhftQdqAIv5kbpC6SRtQXP+6SRtQ1XqvjCvdgKzW9+L42FMgk/8DDsgw4HlIEQ0AAAAASUVORK5CYII=" alt="" height="211" width="213">

You can wrap this up into a string variable and place this absolutely anywhere that you would present an html email message - even in your email signatures. The advantage is that there are no attachments, and there are no links. (this code will display a lizard)

A picture is worth a thousand words: enter image description here

Incidentally, I did write a program to do all of this for you. It's called BaseImage, and it will create the image code as well as the html for you. Please don't consider this self-promotion; I'm just sharing a solution.

How to make a whole 'div' clickable in html and css without JavaScript?

Something like this?

<div onclick="alert('test');">

</div>

How to open the terminal in Atom?

In the Atom IDE:

  1. Open file>settings
  2. Click "+" (install)
  3. Search for a terminal package called "platformio-ide-terminal"
  4. Click "install".
  5. Press Crtl+` to toggle the terminal

private constructor

One common use is for template-typedef workaround classes like following:

template <class TObj>
class MyLibrariesSmartPointer
{
  MyLibrariesSmartPointer();
  public:
    typedef smart_ptr<TObj> type;
};

Obviously a public non-implemented constructor would work aswell, but a private construtor raises a compile time error instead of a link time error, if anyone tries to instatiate MyLibrariesSmartPointer<SomeType> instead of MyLibrariesSmartPointer<SomeType>::type, which is desireable.

jQuery AutoComplete Trigger Change Event

This post is pretty old, but for thoses who got here in 2016. None of the example here worked for me. Using keyup instead of autocompletechange did the job. Using jquery-ui 10.4

$("#CompanyList").on("keyup", function (event, ui) {
    console.log($(this).val());
});

Hope this help!

The difference between "require(x)" and "import x"

This simple diagram that helps me to understand the difference between require and import.

enter image description here

Apart from that,

You can't selectively load only the pieces you need with require but with imports, you can selectively load only the pieces you need. That can save memory.

Loading is synchronous(step by step) for require on the other hand import can be asynchronous(without waiting for previous import) so it can perform a little better than require.

How to get first element in a list of tuples?

if the tuples are unique then this can work

>>> a = [(1, u'abc'), (2, u'def')]
>>> a
[(1, u'abc'), (2, u'def')]
>>> dict(a).keys()
[1, 2]
>>> dict(a).values()
[u'abc', u'def']
>>> 

Php multiple delimiters in explode

function multiexplode ($delimiters,$string) {

    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";


$exploded = multiexplode(array(",",".","|",":"),$text);

print_r($exploded);

//And output will be like this:
// Array
// (
//    [0] => here is a sample
//    [1] =>  this text
//    [2] =>  and this will be exploded
//    [3] =>  this also 
//    [4] =>  this one too 
//    [5] => )
// )

Source: php@metehanarslan at php.net

How to play a notification sound on websites?

One more plugin, to play notification sounds on websites: Ion.Sound

Advantages:

  • JavaScript-plugin for playing sounds based on Web Audio API with fallback to HTML5 Audio.
  • Plugin is working on most popular desktop and mobile browsers and can be used everywhere, from common web sites to browser games.
  • Audio-sprites support included.
  • No dependecies (jQuery not required).
  • 25 free sounds included.

Set up plugin:

// set up config
ion.sound({
    sounds: [
        {
            name: "my_cool_sound"
        },
        {
            name: "notify_sound",
            volume: 0.2
        },
        {
            name: "alert_sound",
            volume: 0.3,
            preload: false
        }
    ],
    volume: 0.5,
    path: "sounds/",
    preload: true
});

// And play sound!
ion.sound.play("my_cool_sound");

How can I find all of the distinct file extensions in a folder hierarchy?

I think the most simple & straightforward way is

for f in *.*; do echo "${f##*.}"; done | sort -u

It's modified on ChristopheD's 3rd way.

What is the preferred syntax for defining enums in JavaScript?

It's easy to use, I think. https://stackoverflow.com/a/32245370/4365315

var A = {a:11, b:22}, 
enumA = new TypeHelper(A);

if(enumA.Value === A.b || enumA.Key === "a"){ 
... 
}

var keys = enumA.getAsList();//[object, object]

//set
enumA.setType(22, false);//setType(val, isKey)

enumA.setType("a", true);

enumA.setTypeByIndex(1);

UPDATE:

There is my helper codes(TypeHelper).

_x000D_
_x000D_
var Helper = {_x000D_
    isEmpty: function (obj) {_x000D_
        return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;_x000D_
    },_x000D_
_x000D_
    isObject: function (obj) {_x000D_
        return (typeof obj === 'object');_x000D_
    },_x000D_
_x000D_
    sortObjectKeys: function (object) {_x000D_
        return Object.keys(object)_x000D_
            .sort(function (a, b) {_x000D_
                c = a - b;_x000D_
                return c_x000D_
            });_x000D_
    },_x000D_
    containsItem: function (arr, item) {_x000D_
        if (arr && Array.isArray(arr)) {_x000D_
            return arr.indexOf(item) > -1;_x000D_
        } else {_x000D_
            return arr === item;_x000D_
        }_x000D_
    },_x000D_
_x000D_
    pushArray: function (arr1, arr2) {_x000D_
        if (arr1 && arr2 && Array.isArray(arr1)) {_x000D_
            arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);_x000D_
        }_x000D_
    }_x000D_
};_x000D_
function TypeHelper() {_x000D_
    var _types = arguments[0],_x000D_
        _defTypeIndex = 0,_x000D_
        _currentType,_x000D_
        _value,_x000D_
        _allKeys = Helper.sortObjectKeys(_types);_x000D_
_x000D_
    if (arguments.length == 2) {_x000D_
        _defTypeIndex = arguments[1];_x000D_
    }_x000D_
_x000D_
    Object.defineProperties(this, {_x000D_
        Key: {_x000D_
            get: function () {_x000D_
                return _currentType;_x000D_
            },_x000D_
            set: function (val) {_x000D_
                _currentType.setType(val, true);_x000D_
            },_x000D_
            enumerable: true_x000D_
        },_x000D_
        Value: {_x000D_
            get: function () {_x000D_
                return _types[_currentType];_x000D_
            },_x000D_
            set: function (val) {_x000D_
                _value.setType(val, false);_x000D_
            },_x000D_
            enumerable: true_x000D_
        }_x000D_
    });_x000D_
    this.getAsList = function (keys) {_x000D_
        var list = [];_x000D_
        _allKeys.forEach(function (key, idx, array) {_x000D_
            if (key && _types[key]) {_x000D_
_x000D_
                if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {_x000D_
                    var json = {};_x000D_
                    json.Key = key;_x000D_
                    json.Value = _types[key];_x000D_
                    Helper.pushArray(list, json);_x000D_
                }_x000D_
            }_x000D_
        });_x000D_
        return list;_x000D_
    };_x000D_
_x000D_
    this.setType = function (value, isKey) {_x000D_
        if (!Helper.isEmpty(value)) {_x000D_
            Object.keys(_types).forEach(function (key, idx, array) {_x000D_
                if (Helper.isObject(value)) {_x000D_
                    if (value && value.Key == key) {_x000D_
                        _currentType = key;_x000D_
                    }_x000D_
                } else if (isKey) {_x000D_
                    if (value && value.toString() == key.toString()) {_x000D_
                        _currentType = key;_x000D_
                    }_x000D_
                } else if (value && value.toString() == _types[key]) {_x000D_
                    _currentType = key;_x000D_
                }_x000D_
            });_x000D_
        } else {_x000D_
            this.setDefaultType();_x000D_
        }_x000D_
        return isKey ? _types[_currentType] : _currentType;_x000D_
    };_x000D_
_x000D_
    this.setTypeByIndex = function (index) {_x000D_
        for (var i = 0; i < _allKeys.length; i++) {_x000D_
            if (index === i) {_x000D_
                _currentType = _allKeys[index];_x000D_
                break;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
_x000D_
    this.setDefaultType = function () {_x000D_
        this.setTypeByIndex(_defTypeIndex);_x000D_
    };_x000D_
_x000D_
    this.setDefaultType();_x000D_
}_x000D_
_x000D_
var TypeA = {_x000D_
    "-1": "Any",_x000D_
    "2": "2L",_x000D_
    "100": "100L",_x000D_
    "200": "200L",_x000D_
    "1000": "1000L"_x000D_
};_x000D_
_x000D_
var enumA = new TypeHelper(TypeA, 4);_x000D_
_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
_x000D_
enumA.setType("200L", false);_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
enumA.setDefaultType();_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
_x000D_
enumA.setTypeByIndex(1);_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
document.writeln("is equals = ", (enumA.Value == TypeA["2"]));
_x000D_
_x000D_
_x000D_

403 - Forbidden: Access is denied. ASP.Net MVC

In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :

  • IIS is pointing to an empty folder.
  • You do not have a default document set.

Align text in JLabel to the right

This can be done in two ways.

JLabel Horizontal Alignment

You can use the JLabel constructor:

JLabel(String text, int horizontalAlignment) 

To align to the right:

JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);

JLabel also has setHorizontalAlignment:

label.setHorizontalAlignment(SwingConstants.RIGHT);

This assumes the component takes up the whole width in the container.

Using Layout

A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout:

    Box box = Box.createVerticalBox();
    JLabel label1 = new JLabel("test1, the beginning");
    label1.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label1);

    JLabel label2 = new JLabel("test2, some more");
    label2.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label2);

    JLabel label3 = new JLabel("test3");
    label3.setAlignmentX(Component.RIGHT_ALIGNMENT);
    box.add(label3);


    add(box);

How do I left align these Bootstrap form items?

Instead of altering the original bootstrap css class create a new css file that will override the default style.

Make sure you include the new css file after including the bootstrap.css file.

In the new css file do

.form-horizontal .control-label{
   text-align:left !important; 
}

How to install plugin for Eclipse from .zip

This is the easiest way that I found to install a plugin locally at eclipse -

enter image description here

How do I add a simple jQuery script to WordPress?

I know what you mean about the tutorials. Here's how I do it:

First you need to write your script. In your theme folder create a folder called something like 'js'. Create a file in that folder for your javascript. E.g. your-script.js. Add your jQuery script to that file (you don't need <script> tags in a .js file).

Here is an example of how your jQuery script (in wp-content/themes/your-theme/js/your-scrript.js) might look:

jQuery(document).ready(function($) {
  $('#nav a').last().addClass('last');
})

Notice that I use jQuery and not $ at the start of the function.

Ok, now open your theme's functions.php file. You'll want to use the wp_enqueue_script() function so that you can add your script whilst also telling WordPress that it relies on jQuery. Here's how to do that:

add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
    wp_enqueue_script(
        'your-script', // name your script so that you can attach other scripts and de-register, etc.
        get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
        array('jquery') // this array lists the scripts upon which your script depends
    );
}

Assuming that your theme has wp_head and wp_footer in the right places, this should work. Let me know if you need any more help.

WordPress questions can be asked over at WordPress Answers.

Adding multiple class using ng-class

Here is an example comparing multiple angular-ui-router states using the OR || operator:

<li ng-class="
    {
        warning:
            $state.includes('out.pay.code.wrong')
            || $state.includes('out.pay.failed')
        ,
        active:
            $state.includes('out.pay')
    }
">

It will give the li the classes warning and/or active, depening on whether the conditions are met.

Build query string for System.Net.HttpClient get

I couldn't find a better solution than creating a extension method to convert a Dictionary to QueryStringFormat. The solution proposed by Waleed A.K. is good as well.

Follow my solution:

Create the extension method:

public static class DictionaryExt
{
    public static string ToQueryString<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
    {
        return ToQueryString<TKey, TValue>(dictionary, "?");
    }

    public static string ToQueryString<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, string startupDelimiter)
    {
        string result = string.Empty;
        foreach (var item in dictionary)
        {
            if (string.IsNullOrEmpty(result))
                result += startupDelimiter; // "?";
            else
                result += "&";

            result += string.Format("{0}={1}", item.Key, item.Value);
        }
        return result;
    }
}

And them:

var param = new Dictionary<string, string>
          {
            { "param1", "value1" },
            { "param2", "value2" },
          };
param.ToQueryString(); //By default will add (?) question mark at begining
//"?param1=value1&param2=value2"
param.ToQueryString("&"); //Will add (&)
//"&param1=value1&param2=value2"
param.ToQueryString(""); //Won't add anything
//"param1=value1&param2=value2"

Replacing H1 text with a logo image: best method for SEO and accessibility?

After reading through the above solutions, I used a CSS Grid solution.

  1. Create a div containing the h1 text and the image.
  2. Position the two items in the same cell and make them both relatively positioned.
  3. Use the old zeldman.com technique to hide the text using text-indent, white-space, and overflow properties.
<div class="title-stack">
    <h1 class="title-stack__title">StackOverflow</h1>
    <a href="#" class="title-stack__logo">
        <img src="/images/stack-overflow.png" alt="Stack Overflow">
    </a>
</div>
.title-stack {
    display: grid;
}
.title-stack__title, .title-stack__logo {
    grid-area: 1/1/1/1;
    position: relative;
}
.title-stack__title {
    z-index: 0;
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}

How to get the query string by javascript?

Works for me-

function querySt(Key) {

    var url = window.location.href;

    KeysValues = url.split(/[\?&]+/); 

    for (i = 0; i < KeysValues.length; i++) {

            KeyValue= KeysValues[i].split("=");

            if (KeyValue[0] == Key) {

                return KeyValue[1];

        }

    }

}

function GetQString(Key) {     

    if (querySt(Key)) {

         var value = querySt(Key);

         return value;        

    }

 }

CSS technique for a horizontal line with words in the middle

I have tried most of the ways suggested but ends with some problems like full width, or Not suitable for dynamic content. Finally i modified a code, and works perfectly. This example code will draw those lines before and after, and it is flexible in content change. Center aligned too.

HTML

        <div style="text-align:center"> 
            <h1>
                <span >S</span>
            </h1> 
        </div> 

        <div style="text-align:center"> 
            <h1>
                <span >Long text</span>
            </h1> 
        </div> 

CSS

      h1 {
            display: inline-block;
            position: relative;
            text-align: center;
        }

        h1 span {
            background: #fff;
            padding: 0 10px;
            position: relative;
            z-index: 1;
        }

        h1:before {
            background: #ddd;
            content: "";
            height: 1px;
            position: absolute;
            top: 50%;
            width: calc(100% + 50px);//Support in modern browsers
            left: -25px;
        }

        h1:before {
            left: ;
        }

Result: https://jsfiddle.net/fasilkk/vowqfnb9/

Eclipse: Set maximum line length for auto formatting?

Comments have their own line length setting at the bottom of the setting page java->code style->formatter-> Edit... ->comments

How to create a directive with a dynamic template in AngularJS?

Had a similar need. $compile does the job. (Not completely sure if this is "THE" way to do it, still working my way through angular)

http://jsbin.com/ebuhuv/7/edit - my exploration test.

One thing to note (per my example), one of my requirements was that the template would change based on a type attribute once you clicked save, and the templates were very different. So though, you get the data binding, if need a new template in there, you will have to recompile.

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

If you use mod_rewrite to hide the extension of your scripts, or if you just like pretty URLs that end in /, then you might want to approach this from the other direction. Tell nginx to let anything with a non-static extension to go through to apache. For example:

location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
{
    root   /path/to/static-content;
}

location ~* ^!.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

I found the first part of this snippet over at: http://code.google.com/p/scalr/wiki/NginxStatic

Finding the index of an item in a list

>>> ["foo", "bar", "baz"].index("bar")
1

Reference: Data Structures > More on Lists

Caveats follow

Note that while this is perhaps the cleanest way to answer the question as asked, index is a rather weak component of the list API, and I can't remember the last time I used it in anger. It's been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Some caveats about list.index follow. It is probably worth initially taking a look at the documentation for it:

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Linear time-complexity in list length

An index call checks every element of the list in order, until it finds a match. If your list is long, and you don't know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give index a hint. For instance, in this snippet, l.index(999_999, 999_990, 1_000_000) is roughly five orders of magnitude faster than straight l.index(999_999), because the former only has to search 10 entries, while the latter searches a million:

>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514
 

Only returns the index of the first match to its argument

A call to index searches through the list in order until it finds a match, and stops there. If you expect to need indices of more matches, you should use a list comprehension, or generator expression.

>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> next(g)
0
>>> next(g)
2

Most places where I once would have used index, I now use a list comprehension or generator expression because they're more generalizable. So if you're considering reaching for index, take a look at these excellent Python features.

Throws if element not present in list

A call to index results in a ValueError if the item's not present.

>>> [1, 1].index(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 2 is not in list

If the item might not be present in the list, you should either

  1. Check for it first with item in my_list (clean, readable approach), or
  2. Wrap the index call in a try/except block which catches ValueError (probably faster, at least when the list to search is long, and the item is usually present.)

How do I execute a command and get the output of the command within C++ using POSIX?

I'd use popen() (++waqas).

But sometimes you need reading and writing...

It seems like nobody does things the hard way any more.

(Assuming a Unix/Linux/Mac environment, or perhaps Windows with a POSIX compatibility layer...)

enum PIPE_FILE_DESCRIPTERS
{
  READ_FD  = 0,
  WRITE_FD = 1
};

enum CONSTANTS
{
  BUFFER_SIZE = 100
};

int
main()
{
  int       parentToChild[2];
  int       childToParent[2];
  pid_t     pid;
  string    dataReadFromChild;
  char      buffer[BUFFER_SIZE + 1];
  ssize_t   readResult;
  int       status;

  ASSERT_IS(0, pipe(parentToChild));
  ASSERT_IS(0, pipe(childToParent));

  switch (pid = fork())
  {
    case -1:
      FAIL("Fork failed");
      exit(-1);

    case 0: /* Child */
      ASSERT_NOT(-1, dup2(parentToChild[READ_FD], STDIN_FILENO));
      ASSERT_NOT(-1, dup2(childToParent[WRITE_FD], STDOUT_FILENO));
      ASSERT_NOT(-1, dup2(childToParent[WRITE_FD], STDERR_FILENO));
      ASSERT_IS(0, close(parentToChild [WRITE_FD]));
      ASSERT_IS(0, close(childToParent [READ_FD]));

      /*     file, arg0, arg1,  arg2 */
      execlp("ls", "ls", "-al", "--color");

      FAIL("This line should never be reached!!!");
      exit(-1);

    default: /* Parent */
      cout << "Child " << pid << " process running..." << endl;

      ASSERT_IS(0, close(parentToChild [READ_FD]));
      ASSERT_IS(0, close(childToParent [WRITE_FD]));

      while (true)
      {
        switch (readResult = read(childToParent[READ_FD],
                                  buffer, BUFFER_SIZE))
        {
          case 0: /* End-of-File, or non-blocking read. */
            cout << "End of file reached..."         << endl
                 << "Data received was ("
                 << dataReadFromChild.size() << "): " << endl
                 << dataReadFromChild                << endl;

            ASSERT_IS(pid, waitpid(pid, & status, 0));

            cout << endl
                 << "Child exit staus is:  " << WEXITSTATUS(status) << endl
                 << endl;

            exit(0);


          case -1:
            if ((errno == EINTR) || (errno == EAGAIN))
            {
              errno = 0;
              break;
            }
            else
            {
              FAIL("read() failed");
              exit(-1);
            }

          default:
            dataReadFromChild . append(buffer, readResult);
            break;
        }
      } /* while (true) */
  } /* switch (pid = fork())*/
}

You also might want to play around with select() and non-blocking reads.

fd_set          readfds;
struct timeval  timeout;

timeout.tv_sec  = 0;    /* Seconds */
timeout.tv_usec = 1000; /* Microseconds */

FD_ZERO(&readfds);
FD_SET(childToParent[READ_FD], &readfds);

switch (select (1 + childToParent[READ_FD], &readfds, (fd_set*)NULL, (fd_set*)NULL, & timeout))
{
  case 0: /* Timeout expired */
    break;

  case -1:
    if ((errno == EINTR) || (errno == EAGAIN))
    {
      errno = 0;
      break;
    }
    else
    {
      FAIL("Select() Failed");
      exit(-1);
    }

  case 1:  /* We have input */
    readResult = read(childToParent[READ_FD], buffer, BUFFER_SIZE);
    // However you want to handle it...
    break;

  default:
    FAIL("How did we see input on more than one file descriptor?");
    exit(-1);
}

link button property to open in new tab?

From the docs:

Use the LinkButton control to create a hyperlink-style button on the Web page. The LinkButton control has the same appearance as a HyperLink control, but has the same functionality as a Button control. If you want to link to another Web page when the control is clicked, consider using the HyperLink control.

As this isn't actually performing a link in the standard sense, there's no Target property on the control (the HyperLink control does have a Target) - it's attempting to perform a PostBack to the server from a text link.

Depending on what you are trying to do you could either:

  1. Use a HyperLink control, and set the Target property
  2. Provide a method to the OnClientClick property that opens a new window to the correct place.
  3. In your code that handles the PostBack add some JavaScript to fire on PageLoad that will open a new window correct place.

how to make a new line in a jupyter markdown cell

"We usually put ' (space)' after the first sentence before a new line, but it doesn't work in Jupyter."

That inspired me to try using two spaces instead of just one - and it worked!!

(Of course, that functionality could possibly have been introduced between when the question was asked in January 2017, and when my answer was posted in March 2018.)

How can I open Java .class files in a human-readable way?

jd-gui is the best decompiler at the moment. it can handle newer features in Java, as compared to the getting-dusty JAD.

How to add number of days to today's date?

Here is a solution that worked for me.

function calduedate(ndays){

    var newdt = new Date(); var chrday; var chrmnth;
    newdt.setDate(newdt.getDate() + parseInt(ndays));

    var newdate = newdt.getFullYear();
    if(newdt.getMonth() < 10){
        newdate = newdate+'-'+'0'+newdt.getMonth();
    }else{
        newdate = newdate+'-'+newdt.getMonth();
    }
    if(newdt.getDate() < 10){
        newdate = newdate+'-'+'0'+newdt.getDate();
    }else{
        newdate = newdate+'-'+newdt.getDate();
    }

    alert("newdate="+newdate);

}

How to inject Javascript in WebBrowser control?

i use this:

webBrowser.Document.InvokeScript("execScript", new object[] { "alert(123)", "JavaScript" })

How to read a configuration file in Java

Create a configuration file and put your entries there.

SERVER_PORT=10000     
THREAD_POOL_COUNT=3     
ROOT_DIR=/home/   

You can load this file using Properties.load(fileName) and retrieved values you get(key);

How can I split a string into segments of n characters?

Here's a way to do it without regular expressions or explicit loops, although it's stretching the definition of a one liner a bit:

const input = 'abcdefghijlkm';

// Change `3` to the desired split length.
const output = input.split('').reduce((s, c) => {let l = s.length-1; (s[l] && s[l].length < 3) ? s[l] += c : s.push(c); return s;}, []);

console.log(output);  // output: [ 'abc', 'def', 'ghi', 'jlk', 'm' ]

It works by splitting the string into an array of individual characters, then using Array.reduce to iterate over each character. Normally reduce would return a single value, but in this case the single value happens to be an array, and as we pass over each character we append it to the last item in that array. Once the last item in the array reaches the target length, we append a new array item.

How can I trigger a Bootstrap modal programmatically?

The same thing happened to me. I wanted to open the Bootstrap modal by clicking on the table rows and get more details about each row. I used a trick to do this, Which I call the virtual button! Compatible with the latest version of Bootstrap (v5.0.0-alpha2). It might be useful for others as well.

See this code snippet with preview: https://gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba

Summary:

let exampleButton = document.createElement("button");
exampleButton.classList.add("d-none");
document.body.appendChild(exampleButton);
exampleButton.dataset.toggle = "modal";
exampleButton.dataset.target = "#exampleModal";

//AddEventListener to all rows
document.querySelectorAll('#exampleTable tr').forEach(row => {
    row.addEventListener('click', e => {
        //Set parameteres (clone row dataset)
        exampleButton.dataset.whatever = e.target.closest('tr').dataset.whatever;
        //Button click simulation
        //Now we can use relatedTarget
        exampleButton.click();
    })
});

All this is to use the relatedTarget property. (See Bootstrap docs)

Android SQLite: Update Statement

you can always execute SQL.

update [your table] set [your column]=value

for example

update Foo set Bar=125

Generate Controller and Model

Thank you @user1909426, I can found solution by php artisan list it will list all command that was used on L4. It can create controller only not Model. I follow this command to generate controller.

php artisan controller:make [Name]Controller

On Laravel 5, the command has changed:

php artisan make:controller [Name]Controller

Note: [Name] name of controller

What is the SSIS package and what does it do?

SSIS (SQL Server Integration Services) is an upgrade of DTS (Data Transformation Services), which is a feature of the previous version of SQL Server. SSIS packages can be created in BIDS (Business Intelligence Development Studio). These can be used to merge data from heterogeneous data sources into SQL Server. They can also be used to populate data warehouses, to clean and standardize data, and to automate administrative tasks.

SQL Server Integration Services (SSIS) is a component of Microsoft SQL Server 2005. It replaces Data Transformation Services, which has been a feature of SQL Server since Version 7.0. Unlike DTS, which was included in all versions, SSIS is only available in the "Standard" and "Enterprise" editions. Integration Services provides a platform to build data integration and workflow applications. The primary use for SSIS is data warehousing as the product features a fast and flexible tool for data extraction, transformation, and loading (ETL).). The tool may also be used to automate maintenance of SQL Server databases, update multidimensional cube data, and perform other functions.

How to convert a string or integer to binary in Ruby?

I am almost a decade late but if someone still come here and want to find the code without using inbuilt function like to_S then I might be helpful.

find the binary

def find_binary(number)
  binary = []  
  until(number == 0)
    binary << number%2
    number = number/2
  end
  puts binary.reverse.join
end

How to automatically update your docker containers, if base-images are updated

Another approach could be to assume that your base image gets behind quite quickly (and that's very likely to happen), and force another image build of your application periodically (e.g. every week) and then re-deploy it if it has changed.

As far as I can tell, popular base images like the official Debian or Java update their tags to cater for security fixes, so tags are not immutable (if you want a stronger guarantee of that you need to use the reference [image:@digest], available in more recent Docker versions). Therefore, if you were to build your image with docker build --pull, then your application should get the latest and greatest of the base image tag you're referencing.

Since mutable tags can be confusing, it's best to increment the version number of your application every time you do this so that at least on your side things are cleaner.

So I'm not sure that the script suggested in one of the previous answers does the job, since it doesn't rebuild you application's image - it just updates the base image tag and then it restarts the container, but the new container still references the old base image hash.

I wouldn't advocate for running cron-type jobs in containers (or any other processes, unless really necessary) as this goes against the mantra of running only one process per container (there are various arguments about why this is better, so I'm not going to go into it here).

Extract digits from string - StringUtils Java

You can also use java.util.Scanner:

new Scanner(str).useDelimiter("[^\\d]+").nextInt()

You can use next() instead of nextInt() to get the digits as string.

You can check for the presence of number using hasNextInt() on the Scanner.

Long Press in JavaScript?

You could set the timeout for that element on mouse down and clear it on mouse up:

$("a").mousedown(function() {
    // set timeout for this element
    var timeout = window.setTimeout(function() { /* … */ }, 1234);
    $(this).mouseup(function() {
        // clear timeout for this element
        window.clearTimeout(timeout);
        // reset mouse up event handler
        $(this).unbind("mouseup");
        return false;
    });
    return false;
});

With this each element gets its own timeout.

Is right click a Javascript event?

Yes - it is!

function doSomething(e) {
    var rightclick;
    if (!e) var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert('Rightclick: ' + rightclick); // true or false
}

How to go back (ctrl+z) in vi/vim

You can use the u button to undo the last modification. (And Ctrl+R to redo it).

Read more about it at: http://vim.wikia.com/wiki/Undo_and_Redo

How do I get a div to float to the bottom of its container?

One interesting approach is to stack a couple of right float elements on top of each other.

<div>
<div style="float:right;height:200px;"></div>
<div style="float:right;clear:right;">Floated content</div>
<p>Other content</p>
</div>

Only problem is that this only works when you know the height of the box.

Difference between dangling pointer and memory leak

A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.

#include <stdlib.h>
#include <stdio.h> 
 void  main()
 {
    int *ptr = (int *)malloc(sizeof(int));
    // After below free call, ptr becomes a 
    // dangling pointer
    free(ptr); 
 }

for more information click HERE

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

I found the answer!

I want to acknowledge the hard work of everyone in trying to find a better way to solve this problem, unfortunately because of a series of larger constraints I am unable to select them as the "answer" (I am voting them up because you deserve points for contributing).

The specific problem I was facing was a JavaScript onScoll event that was firing but a subsequent CSS update that wasn't causing IE8 (in standards mode) to redraw. Even stranger was the fact that in some pages it was redrawing while in others (with no obvious similarity) it wasn't. The solution in the end was to add the following CSS

#ActionBox {
  position: relative;
  float: right;
}

Here is an updated pastbin showing this (I added some more style to show how I am implementing this code). The IE "edit code" then "view output" bug fudgey talked about still occurs (but it seems to be a event binding issue unique to pastbin (and similar services)

I don't know why adding "float: right" allows IE8 to complete a redraw on an event that was already firing, but for some reason it does.

Java Ordered Map

Since Java 6 there is also non-blocking thread-safe alternative to TreeMap. See ConcurrentSkipListMap.

Go: panic: runtime error: invalid memory address or nil pointer dereference

Since I got here with my problem I will add this answer although it is not exactly relevant to the original question. When you are implementing an interface make sure you do not forget to add the type pointer on your member function declarations. Example:

type AnimalSounder interface {
    MakeNoise()
}

type Dog struct {
    Name string
    mean bool
    BarkStrength int
}

func (dog *Dog) MakeNoise() {
    //implementation
}

I forgot the *(dog Dog) part, I do not recommend it. Then you get into ugly trouble when calling MakeNoice on an AnimalSounder interface variable of type Dog.

SQL Client for Mac OS X that works with MS SQL Server

This doesn't specifically answer your question, because I'm not sure in any clients exist in Mac OS X, but I generally just Remote Desktop into the server and work through that. Another option is VMware Fusion (which is much better than Parallels in my opinion) + Windows XP + SQL Server Management Studio.

Error: class X is public should be declared in a file named X.java

error example:

public class MaainActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.activity_main);

  }
}

correct example:just make sure that you written correct name of activity that is"main activity"

public class MainActivity extends Activity {


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.activity_main);

  }
}

Linq on DataTable: select specific column into datatable, not whole table

If you already know beforehand how many columns your new DataTable would have, you can do something like this:

DataTable matrix = ... // get matrix values from db

DataTable newDataTable = new DataTable();
newDataTable.Columns.Add("c_to", typeof(string));
newDataTable.Columns.Add("p_to", typeof(string));

var query = from r in matrix.AsEnumerable()
            where r.Field<string>("c_to") == "foo" &&
                    r.Field<string>("p_to") == "bar"
            let objectArray = new object[]
            {
                r.Field<string>("c_to"), r.Field<string>("p_to")
            }
            select objectArray;

foreach (var array in query)
{
    newDataTable.Rows.Add(array);
}

How to know a Pod's own IP address from inside a container in the Pod?

The container's IP address should be properly configured inside of its network namespace, so any of the standard linux tools can get it. For example, try ifconfig, ip addr show, hostname -I, etc. from an attached shell within one of your containers to test it out.

jQuery: Uncheck other checkbox on one checked

you could use class for all your checkboxes, and do:

$(".check_class").click(function() {
  $(".check_class").attr("checked", false); //uncheck all checkboxes
  $(this).attr("checked", true);  //check the clicked one
});

What is the difference between an int and an Integer in Java and C#?

I'll add to the excellent answers given above, and talk about boxing and unboxing, and how this applies to Java (although C# has it too). I'll use just Java terminology because I am more au fait with that.

As the answers mentioned, int is just a number (called the unboxed type), whereas Integer is an object (which contains the number, hence a boxed type). In Java terms, that means (apart from not being able to call methods on int), you cannot store int or other non-object types in collections (List, Map, etc.). In order to store them, you must first box them up in its corresponding boxed type.

Java 5 onwards have something called auto-boxing and auto-unboxing which allow the boxing/unboxing to be done behind the scenes. Compare and contrast: Java 5 version:

Deque<Integer> queue;

void add(int n) {
    queue.add(n);
}

int remove() {
    return queue.remove();
}

Java 1.4 or earlier (no generics either):

Deque queue;

void add(int n) {
    queue.add(Integer.valueOf(n));
}

int remove() {
    return ((Integer) queue.remove()).intValue();
}

It must be noted that despite the brevity in the Java 5 version, both versions generate identical bytecode. Thus, although auto-boxing and auto-unboxing are very convenient because you write less code, these operations do happens behind the scenes, with the same runtime costs, so you still have to be aware of their existence.

Hope this helps!

How to move a marker in Google Maps API

<style>
    #frame{
        position: fixed;
        top: 5%;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 6px #B2B2B2;
        display: inline-block;
        padding: 8px 8px;
        width: 98%;
        height: 92%;
        display: none;
        z-index: 1000;
    }
    #map{
        position: fixed;
        display: inline-block;
        width: 99%;
        height: 93%;
        display: none;
        z-index: 1000;
    }

    #loading{
        position: fixed;
        top: 50%;
        left: 50%;
        opacity: 1!important;
        margin-top: -100px;
        margin-left: -150px;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 6px #B2B2B2;
        display: inline-block;
        padding: 8px 8px;
        max-width: 66%;
        display: none;
        color: #000;

    }
    #mytitle{
        color: #FFF;
        background-image: linear-gradient(to bottom,#d67631,#d67631);
        //  border-color: rgba(47, 164, 35, 1);
        width: 100%;
        cursor: move;
    }
    #closex{ 
        display: block;
        float:right;
        position:relative;
        top:-10px;
        right: -10px;
        height: 20px;
        cursor: pointer;
    }
    .pointer{
        cursor: pointer !important;
    }

</style> 
<div id="loading">
    <i class="fa fa-circle-o-notch fa-spin fa-2x"></i>
    Loading...
</div>
<div id="frame">
    <div id="headerx"></div>
    <div id="map" >    
    </div>
</div>


<?php
$url = Yii::app()->baseUrl . '/reports/reports/transponderdetails';
?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

<script>
    function clode() {
        $('#frame').hide();
        $('#frame').html();
    }
    function track(id) {
        $('#loading').show();
        $('#loading').parent().css("opacity", '0.7');


        $.ajax({
            type: "POST",
            url: '<?php echo $url; ?>',
            data: {'id': id},
            success: function(data) {
                $('#frame').show();
                $('#headerx').html(data);
                $('#loading').parents().css("opacity", '1');
                $('#loading').hide();
                var thelat = parseFloat($('#lat').text());
                var long = parseFloat($('#long').text());
                $('#map').show();
                var lat = thelat;
                var lng = long;
                var orlat=thelat;
                var orlong=long;
                //Intialize the Path Array
                var path = new google.maps.MVCArray();
                var service = new google.maps.DirectionsService();


                var myLatLng = new google.maps.LatLng(lat, lng), myOptions = {zoom: 4, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP};
                var map = new google.maps.Map(document.getElementById('map'), myOptions);
                var poly = new google.maps.Polyline({map: map, strokeColor: '#4986E7'});
                var marker = new google.maps.Marker({position: myLatLng, map: map});

                function initialize() {
                    marker.setMap(map);
                    movepointer(map, marker);
                    var drawingManager = new google.maps.drawing.DrawingManager();
                    drawingManager.setMap(map);
                }

                function movepointer(map, marker) {
                    marker.setPosition(new google.maps.LatLng(lat, lng));
                    map.panTo(new google.maps.LatLng(lat, lng));

                    var src = myLatLng;//start point
                    var des = myLatLng;// should be the destination
                    path.push(src);
                    poly.setPath(path);
                    service.route({
                        origin: src,
                        destination: des,
                        travelMode: google.maps.DirectionsTravelMode.DRIVING
                    }, function(result, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                            for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                                path.push(result.routes[0].overview_path[i]);
                            }
                        }
                    });

                }
                ;

                // function()
                setInterval(function() {
                    lat = Math.random() + orlat;
                    lng = Math.random() + orlong;
                    console.log(lat + "-" + lng);
                    myLatLng = new google.maps.LatLng(lat, lng);
                    movepointer(map, marker);

                }, 1000);



            },
            error: function() {
                $('#frame').html('Sorry, no details found');
            },
        });
        return false;
    }
    $(function() {
        $("#frame").draggable();
    });

</script>

How can I undo git reset --hard HEAD~1?

Before answering lets add some background, explaining what is this HEAD.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time. (excluding git worktree)

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history its called detached HEAD.

enter image description here

On the command line it will look like this- SHA-1 instead of the branch name since the HEAD is not pointing to the the tip of the current branch

enter image description here


A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point you can create a branch and start to work from this point on.

# Checkout a given commit. 
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

enter image description here


git reset HEAD --hard <commit_id>

"Move" your head back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts, if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.


git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be commited while the original commit will remain in the history as well.

# add new commit with the undo of the original one.
# the <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrate which command does what.
As you can see there reset && checkout modify the HEAD.

enter image description here

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

sending email via php mail function goes to spam

What we usually do with e-mail, preventing spam-folders as the end destination, is using either Gmail as the smtp server or Mandrill as the smtp server.

What is the difference between state and props in React?

Props and state are related. The state of one component will often become the props of a child component. Props are passed to the child within the render method of the parent as the second argument to React.createElement() or, if you're using JSX, the more familiar tag attributes.

<MyChild name={this.state.childsName} />

The parent's state value of childsName becomes the child's this.props.name. From the child's perspective, the name prop is immutable. If it needs to be changed, the parent should just change its internal state:

this.setState({ childsName: 'New name' });

and React will propagate it to the child for you. A natural follow-on question is: what if the child needs to change its name prop? This is usually done through child events and parent callbacks. The child might expose an event called, for example, onNameChanged. The parent would then subscribe to the event by passing a callback handler.

<MyChild name={this.state.childsName} onNameChanged={this.handleName} />

The child would pass its requested new name as an argument to the event callback by calling, e.g., this.props.onNameChanged('New name'), and the parent would use the name in the event handler to update its state.

handleName: function(newName) {
   this.setState({ childsName: newName });
}

What is the difference between connection and read timeout for sockets?

  1. What is the difference between connection and read timeout for sockets?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

  1. What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?

It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt() call may also do the trick ... not sure.)

  1. What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?

It means that a call to read on the socket stream may block for ever. Once again there is no infinite loop, but the read can be unblocked by a Thread.interrupt() call, closing the socket, and (of course) the other end sending data or closing the connection.


1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.

Why are you not able to declare a class as static in Java?

Sure they can, but only inner nested classes. There, it means that instances of the nested class do not require an enclosing instance of the outer class.

But for top-level classes, the language designers couldn't think of anything useful to do with the keyword, so it's not allowed.

Characters allowed in a URL

I tested it by requesting my website (apache) with all available chars on my german keyboard as URL parameter:

http://example.com/?^1234567890ß´qwertzuiopü+asdfghjklöä#<yxcvbnm,.-°!"§$%&/()=? `QWERTZUIOPÜ*ASDFGHJKLÖÄ\'>YXCVBNM;:_²³{[]}\|µ@€~

These were not encoded:

^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.-!/()=?`*;:_{}[]\|~

Not encoded after urlencode():

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_

Not encoded after rawurlencode():

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~

Note: Before PHP 5.3.0 rawurlencode() encoded ~ because of RFC 1738. But this was replaced by RFC 3986 so its safe to use, now. But I do not understand why for example {} are encoded through rawurlencode() because they are not mentioned in RFC 3986.

An additional test I made was regarding auto-linking in mail texts. I tested Mozilla Thunderbird, aol.com, outlook.com, gmail.com, gmx.de and yahoo.de and they fully linked URLs containing these chars:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~+#,%&=*;:@

Of course the ? was linked, too, but only if it was used once.

Some people would now suggest to use only the rawurlencode() chars, but did you ever hear that someone had problems to open these websites?

Asterisk
http://wayback.archive.org/web/*/http://google.com

Colon
https://en.wikipedia.org/wiki/Wikipedia:About

Plus
https://plus.google.com/+google

At sign, Colon, Comma and Exclamation mark
https://www.google.com/maps/place/USA/@36.2218457,...

Because of that these chars should be usable unencoded without problems. Of course you should not use &; because of encoding sequences like &amp;. The same reason is valid for % as it used to encode chars in general. And = as it assigns a value to a parameter name.

Finally I would say its ok to use these unencoded:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~!+,*:@

But if you expect randomly generated URLs you should not use .!, because those mark the end of a sentence and some mail apps will not auto-link the last char of the url. Example:

Visit http://example.com/foo=bar! !

Make docker use IPv4 for port binding

ISSUE RESOVLED:

USE docker run -it -p 80:80 --name nginx --net=host -d nginx

that's issue we face with VM some time instead of bridge network try with host that will work for you

tcp     0    0 0.0.0.0:80            0.0.0.0:*             LISTEN      - 
tcp6    0    0 :::80                 :::*                  LISTEN      -  

Connecting to TCP Socket from browser using javascript

This will be possible via the navigator interface as shown below:

navigator.tcpPermission.requestPermission({remoteAddress:"127.0.0.1", remotePort:6789}).then(
  () => {
    // Permission was granted
    // Create a new TCP client socket and connect to remote host
    var mySocket = new TCPSocket("127.0.0.1", 6789);

    // Send data to server
    mySocket.writeable.write("Hello World").then(
        () => {

            // Data sent sucessfully, wait for response
            console.log("Data has been sent to server");
            mySocket.readable.getReader().read().then(
                ({ value, done }) => {
                    if (!done) {
                        // Response received, log it:
                        console.log("Data received from server:" + value);
                    }

                    // Close the TCP connection
                    mySocket.close();
                }
            );
        },
        e => console.error("Sending error: ", e)
    );
  }
);

More details are outlined in the w3.org tcp-udp-sockets documentation.

http://raw-sockets.sysapps.org/#interface-tcpsocket

https://www.w3.org/TR/tcp-udp-sockets/

Another alternative is to use Chrome Sockets

Creating connections

chrome.sockets.tcp.create({}, function(createInfo) {
  chrome.sockets.tcp.connect(createInfo.socketId,
    IP, PORT, onConnectedCallback);
});

Sending data

chrome.sockets.tcp.send(socketId, arrayBuffer, onSentCallback);

Receiving data

chrome.sockets.tcp.onReceive.addListener(function(info) {
  if (info.socketId != socketId)
    return;
  // info.data is an arrayBuffer.
});

You can use also attempt to use HTML5 Web Sockets (Although this is not direct TCP communication):

var connection = new WebSocket('ws://IPAddress:Port');

connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server
};

http://www.html5rocks.com/en/tutorials/websockets/basics/

Your server must also be listening with a WebSocket server such as pywebsocket, alternatively you can write your own as outlined at Mozilla

How do I push to GitHub under a different username?

git add .
git commit -m "initial commit"
git config --local credential.helper ""
git push https://github.com/youraccount/repo.git --all

After this push command, a username password prompt will be opened.

Change Select List Option background colour on hover in html

Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

How to convert <select> dropdown into an unordered list using jquery?