Programs & Examples On #Dxf

DXF (Drawing Exchange Format) is a CAD data file developed by AutoDesk for interoperability between AutoCAD and other CAD applications.

OSX -bash: composer: command not found

this wasted me a day or two. like why dont anybody say on tutorials that the command composer is not to be used without actually linking and stuff... I mean everyone is writing composer command like its the next step when we are not all 5 years experienced users to know these details.

cp composer.phar /usr/local/bin/composer

did it for me on ubuntu after getting stuck for 2 days

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

Interfaces with static fields in java for sharing 'constants'

It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.

But don't just take my word for it, Josh Bloch also says it's bad:

The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.

An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.

MySQL create stored procedure syntax with delimiter

MY SQL STORED PROCEDURE CREATION

DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin

select * from users
where id=UserId ;
END $$
DELIMITER ;

Can you nest html forms?

Use empty form tag before your nested form

Tested and Worked on Firefox, Chrome

Not Tested on I.E.

<form name="mainForm" action="mainAction">
  <form></form>
  <form name="subForm"  action="subAction">
  </form>
</form>

EDIT by @adusza: As the commenters pointed out, the above code does not result in nested forms. However, if you add div elements like below, you will have subForm inside mainForm, and the first blank form will be removed.

<form name="mainForm" action="mainAction">
  <div>
      <form></form>
      <form name="subForm"  action="subAction">
      </form>
  </div>
</form>

Check if a div exists with jquery

As karim79 mentioned, the first is the most concise. However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true in if-statements. And because of that, the third method is incorrect.

How to convert integer to string in C?

Use sprintf():

int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);

All numbers that are representable by int will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int. When using numbers with greater bitsize, e.g. long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.

How do you access the matched groups in a JavaScript regular expression?

_x000D_
_x000D_
function getMatches(string, regex, index) {_x000D_
  index || (index = 1); // default to the first capturing group_x000D_
  var matches = [];_x000D_
  var match;_x000D_
  while (match = regex.exec(string)) {_x000D_
    matches.push(match[index]);_x000D_
  }_x000D_
  return matches;_x000D_
}_x000D_
_x000D_
_x000D_
// Example :_x000D_
var myString = 'Rs.200 is Debited to A/c ...2031 on 02-12-14 20:05:49 (Clear Bal Rs.66248.77) AT ATM. TollFree 1800223344 18001024455 (6am-10pm)';_x000D_
var myRegEx = /clear bal.+?(\d+\.?\d{2})/gi;_x000D_
_x000D_
// Get an array containing the first capturing group for every match_x000D_
var matches = getMatches(myString, myRegEx, 1);_x000D_
_x000D_
// Log results_x000D_
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))_x000D_
console.log(matches);
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
function getMatches(string, regex, index) {_x000D_
  index || (index = 1); // default to the first capturing group_x000D_
  var matches = [];_x000D_
  var match;_x000D_
  while (match = regex.exec(string)) {_x000D_
    matches.push(match[index]);_x000D_
  }_x000D_
  return matches;_x000D_
}_x000D_
_x000D_
_x000D_
// Example :_x000D_
var myString = 'something format_abc something format_def something format_ghi';_x000D_
var myRegEx = /(?:^|\s)format_(.*?)(?:\s|$)/g;_x000D_
_x000D_
// Get an array containing the first capturing group for every match_x000D_
var matches = getMatches(myString, myRegEx, 1);_x000D_
_x000D_
// Log results_x000D_
document.write(matches.length + ' matches found: ' + JSON.stringify(matches))_x000D_
console.log(matches);
_x000D_
_x000D_
_x000D_

How to disable or enable viewpager swiping in android

Disable swipe progmatically by-

    final View touchView = findViewById(R.id.Pager); 
    touchView.setOnTouchListener(new View.OnTouchListener() 
    {         
        @Override
        public boolean onTouch(View v, MotionEvent event)
        { 
           return true; 
        }
     });

and use this to swipe manually

touchView.setCurrentItem(int index);

How to trigger a phone call when clicking a link in a web page on mobile phone

The proper URL scheme is tel:[number] so you would do

_x000D_
_x000D_
<a href="tel:5551234567"><img src="callme.jpg" /></a>
_x000D_
_x000D_
_x000D_

How to set min-height for bootstrap container

Have you tried height: auto; on your .container div?

Here is a fiddle, if you change img height, container height will adjust to it.

EDIT

So if you "can't" change the inline min-height, you can overwrite the inline style with an !important parameter. It's not the cleanest way, but it solves your problem.

add to your .containerclass this line

min-height:0px !important;

I've updated my fiddle to give you an example.

Oracle SQL query for Date format

to_date() returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:

select * 
from table
where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')

You probably want to create an index on trunc(es_date) if that is something you are doing on a regular basis.

The literal '27-APR-12' can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date() with a proper format mask (or an ANSI literal: date '2012-04-27')

Although you did right in using to_date() and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'.

With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy') when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy' or 'yyyy-mm-dd'

stop all instances of node.js server

it works fine in windows 10

taskkill /f /im node.exe

Java count occurrence of each item in an array

You can do it by using Arrays.sort and Recursion. The same wine but in a different bottle....

import java.util.Arrays;

public class ArrayTest {
public static int mainCount=0;

public static void main(String[] args) {
    String prevItem = "";
    String[] array = {"name1","name1","name2","name2", "name2"};
    Arrays.sort(array);

    for(String item:array){
        if(! prevItem.equals(item)){
            mainCount = 0;
            countArray(array, 0, item);
            prevItem = item;
        }
    }
}

private static void countArray(String[] arr, int currentPos, String item) {
    if(currentPos == arr.length){
        System.out.println(item + " " +  mainCount);
        return;
    }
    else{
        if(arr[currentPos].toString().equals(item)){
            mainCount += 1;
        }
        countArray(arr, currentPos+1, item);
    }
  }
}

Spring MVC 4: "application/json" Content Type is not being set correctly

I had the dependencies as specified @Greg post. I still faced the issue and could be able to resolve it by adding following additional jackson dependency:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.7.4</version>
</dependency>

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

Solved, just renamed the Global.asax or delete it fixed the problem :/

Other known related bugs I found on the web:

  1. Global.asax.cs: must inherit from HttpApplication -> public class MvcApplication : HttpApplication
  2. Project output must be the bin folder and not Bin/Debug, etc.
  3. Iss application pool is not in the correct .net version.

Run JavaScript when an element loses focus

You want to use the onblur event.

<input type="text" name="name" value="value" onblur="alert(1);"/>

How do you find the row count for all your tables in Postgres

Simple Two Steps:
(Note : No need to change anything - just copy paste)
1. create function

create function 
cnt_rows(schema text, tablename text) returns integer
as
$body$
declare
  result integer;
  query varchar;
begin
  query := 'SELECT count(1) FROM ' || schema || '.' || tablename;
  execute query into result;
  return result;
end;
$body$
language plpgsql;

2. Run this query to get rows count for all the tables

select sum(cnt_rows) as total_no_of_rows from (select 
  cnt_rows(table_schema, table_name)
from information_schema.tables
where 
  table_schema not in ('pg_catalog', 'information_schema') 
  and table_type='BASE TABLE') as subq;

or

To get rows counts tablewise

select
  table_schema,
  table_name, 
  cnt_rows(table_schema, table_name)
from information_schema.tables
where 
  table_schema not in ('pg_catalog', 'information_schema') 
  and table_type='BASE TABLE'
order by 3 desc;

PowerShell script to return versions of .NET Framework on a machine?

This is purely because I had to spend time making/editing this when it should be widely available, so I'm providing it to everyone else.

The below script will Output a couple of CSV files to TEMP with the versions and vulnerability status of each machine in a selected (in the code) OU. You'll be able to remotely "security audit" an OU of machines.

Powershell 7.0 needed for the connection test line RSAT needed to get the AD module Visual Studio Code needed to get powershell 7.0 (on win7)

By the time you read this, the version list will probably be out of date within the file. Use this website https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies to add newer dotnet entries. It's just a bunch of key values in "DotNet4Builds"

If within CompromisedCheck.csv a machine shows as =0, it's had it's security turned off manually, and you should raise whether the supplier did it, or a suspect employee.

I hope this helps someone searching for it for their business.

     <#
        Script Name : Get-DotNetVersions_Tweaked.ps1
        Description : This script reports the various .NET Framework versions installed on the local or a remote set of computers
        Author      : Original by Martin Schvartzman - Edited by Mark Purnell
        Reference   : https://msdn.microsoft.com/en-us/library/hh925568
#>

$ErrorActionPreference = "Continue”
import-module ActiveDirectory
$searchOU = "OU=OU LEVEL 1,OU=OU LEVEL 2,OU=MACHINES,OU=OUR LAPTOPS,DC=PUT,DC=MY,DC=DOMAIN,DC=CONTROLLER,DC=HERE,DC=OK"
$computerList = Get-ADComputer -searchbase $searchOU -Filter *


function Get-DotNetFrameworkVersion($computerList)
{
    $dotNetter = @()
    $compromisedCheck = @()
    
    $dotNetRoot = 'SOFTWARE\Microsoft\.NETFramework'
    $dotNetRegistry  = 'SOFTWARE\Microsoft\NET Framework Setup\NDP'
    $dotNet4Registry = 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
    $dotNet4Builds = @{
        '30319'  = @{ Version = [System.Version]'4.0'                                                     }
        '378389' = @{ Version = [System.Version]'4.5'                                                     }
        '378675' = @{ Version = [System.Version]'4.5.1'   ; Comment = '(8.1/2012R2)'                      }
        '378758' = @{ Version = [System.Version]'4.5.1'   ; Comment = '(8/7 SP1/Vista SP2)'               }
        '379893' = @{ Version = [System.Version]'4.5.2'                                                   }
        '380042' = @{ Version = [System.Version]'4.5'     ; Comment = 'and later with KB3168275 rollup'   }
        '393295' = @{ Version = [System.Version]'4.6'     ; Comment = '(Windows 10)'                      }
        '393297' = @{ Version = [System.Version]'4.6'     ; Comment = '(NON Windows 10)'                  }
        '394254' = @{ Version = [System.Version]'4.6.1'   ; Comment = '(Windows 10)'                      }
        '394271' = @{ Version = [System.Version]'4.6.1'   ; Comment = '(NON Windows 10)'                  }
        '394802' = @{ Version = [System.Version]'4.6.2'   ; Comment = '(Windows 10 Anniversary Update)'   }
        '394806' = @{ Version = [System.Version]'4.6.2'   ; Comment = '(NON Windows 10)'                  }
        '460798' = @{ Version = [System.Version]'4.7'     ; Comment = '(Windows 10 Creators Update)'      }
        '460805' = @{ Version = [System.Version]'4.7'     ; Comment = '(NON Windows 10)'                  }
        '461308' = @{ Version = [System.Version]'4.7.1'   ; Comment = '(Windows 10 Fall Creators Update)' }
        '461310' = @{ Version = [System.Version]'4.7.1'   ; Comment = '(NON Windows 10)'                  }
        '461808' = @{ Version = [System.Version]'4.7.2'   ; Comment = '(Windows 10 April & Winserver)'    }
        '461814' = @{ Version = [System.Version]'4.7.2'   ; Comment = '(NON Windows 10)'                  }
        '528040' = @{ Version = [System.Version]'4.8'     ; Comment = '(Windows 10 May 2019 Update)'  }
        '528049' = @{ Version = [System.Version]'4.8'     ; Comment = '(NON Windows 10)'  }
    }

    foreach($computerObject in $computerList)
    {
        $computerName = $computerObject.DNSHostName
        write-host("PCName is " + $computerName)

        if(test-connection -TargetName $computerName -Quiet -TimeOutSeconds 1 -count 2){
            if($regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computerName))           
            {
                $os = (Get-WMIObject win32_operatingsystem -ComputerName SPL305350).Name
                if(!$?){
                    write-host("wim not available")
                    $dotNetter += New-Object -TypeName PSObject -Property @{
                        'ComputerName' = $computerName
                        'OS' = "WIM not available"
                        'Build' = "WIM not available"
                        'Version' = "WIM not available"
                        'Comment' = "WIM not available"
                    }
                }
                else{
                    if ($netRegKey = $regKey.OpenSubKey("$dotNetRegistry"))
                    {
                        foreach ($versionKeyName in $netRegKey.GetSubKeyNames())
                        {
                            if ($versionKeyName -match '^v[123]') {
                                $versionKey = $netRegKey.OpenSubKey($versionKeyName)
                                $version = [System.Version]($versionKey.GetValue('Version', ''))
                                
                                write-host("adding old dotnet")
                                $dotNetter += New-Object -TypeName PSObject -Property @{
                                        ComputerName = $computerName
                                        OS = $os
                                        Build = $version.Build
                                        Version = $version
                                        Comment = ''
                                }
                            }
                        }
                    }
                    if ($net4RegKey = $regKey.OpenSubKey("$dotNet4Registry"))
                    {
                        if(-not ($net4Release = $net4RegKey.GetValue('Release')))
                        {
                            $net4Release = 30319
                        }
                        
                        write-host("adding new dotnet")
                        $dotNetter += New-Object -TypeName PSObject -Property @{
                                'ComputerName' = $computerName
                                'OS' = $os
                                'Build' = $net4Release
                                'Version' = $dotNet4Builds["$net4Release"].Version
                                'Comment' = $dotNet4Builds["$net4Release"].Comment
                        }
                    }
                    if ($netRegKey = $regKey.OpenSubKey("$dotNetRoot")){
                        write-host("Checking for hacked keys")
                        foreach ($versionKeyName in $netRegKey.GetSubKeyNames())
                        {
                            if ($versionKeyName -match '^v[1234]') {
                                $versionKey = $netRegKey.OpenSubKey($versionKeyName)
                                write-host("versionKeyName is" + $versionKeyName)
                                write-host('ASPNetEnforceViewStateMac = ' + $versionKey.GetValue('ASPNetEnforceViewStateMac', ''))
                                $compromisedCheck += New-Object -TypeName PSObject -Property @{
                                    'ComputerName' = $computerName
                                    'version' = $versionKeyName
                                    'compromisedCheck' = ('ASPNetEnforceViewStateMac = ' + $versionKey.GetValue('ASPNetEnforceViewStateMac', ''))
                                }
                            }
                        }
                    }
                }
            }
        }
        else{
            write-host("could not connect to machine")
            $dotNetter += New-Object -TypeName PSObject -Property @{
                    'ComputerName' = $computerName
                    'OS' = $os
                    'Build' = "Could not connect"
                    'Version' = "Could not connect"
                    'Comment' = "Could not connect"
            }
        }
    }
    $dotNetter | export-CSV c:\temp\DotNetVersions.csv
    $compromisedCheck | export-CSV C:\temp\CompromisedCheck.csv
}
get-dotnetframeworkversion($computerList)

Installing PDO driver on MySQL Linux server

Basically the answer from Jani Hartikainen is right! I upvoted his answer. What was missing on my system (based on Ubuntu 15.04) was to enable PDO Extension in my php.ini

extension=pdo.so
extension=pdo_mysql.so

restart the webserver (e.g. with "sudo service apache2 restart") -> every fine :-)

To find where your current active php.ini file is located you can use phpinfo() or some other hints from here: https://www.ostraining.com/blog/coding/phpini-file/

Android Center text on canvas

I find that the best solution for centering text is as follows:

textPaint.setTextAlign(Paint.Align.CENTER);
//textPaint is the Paint object being used to draw the text (it must be initialized beforehand)
float textY=center.y;
float textX=center.x; 
// in this case, center.x and center.y represent the coordinates of the center of the rectangle in which the text is being placed
canvas.drawText(text,textX,textY,textPaint);    `

$('body').on('click', '.anything', function(){})

You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.

$(document).on('click','body *',function(){
    //  $(this) = your current element that clicked.
    // additional code
});

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

You should also be able to use..

swfobject.getFlashPlayerVersion().major === 0

with the swfobject-Plugin.

PostgreSQL: How to make "case-insensitive" query

You could also use POSIX regular expressions, like

SELECT id FROM groups where name ~* 'administrator'

SELECT 'asd' ~* 'AsD' returns t

What is @ModelAttribute in Spring MVC?

Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view.

public String add(@ModelAttribute("specified") Model model) {
    ...
}

Close Window from ViewModel

It's simple. You can create your own ViewModel class for Login - LoginViewModel. You can create view var dialog = new UserView(); inside your LoginViewModel. And you can set-up Command LoginCommand into button.

<Button Name="btnLogin" IsDefault="True" Content="Login" Command="{Binding LoginCommand}" />

and

<Button Name="btnCancel" IsDefault="True" Content="Login" Command="{Binding CancelCommand}" />

ViewModel class:

public class LoginViewModel
{
    Window dialog;
    public bool ShowLogin()
    {
       dialog = new UserView();
       dialog.DataContext = this; // set up ViewModel into View
       if (dialog.ShowDialog() == true)
       {
         return true;
       }

       return false;
    }

    ICommand _loginCommand
    public ICommand LoginCommand
    {
        get
        {
            if (_loginCommand == null)
                _loginCommand = new RelayCommand(param => this.Login());

            return _loginCommand;
        }
    }

    public void CloseLoginView()
    {
            if (dialog != null)
          dialog.Close();
    }   

    public void Login()
    {
        if(CheckLogin()==true)
        {
            CloseLoginView();         
        }
        else
        {
          // write error message
        }
    }

    public bool CheckLogin()
    {
      // ... check login code
      return true;
    }
}

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)

I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.

Hope that helps.

Is there a replacement for unistd.h for Windows (Visual C)?

Create your own unistd.h header and include the needed headers for function prototypes.

Hide Text with CSS, Best Practice?

Actually, a new technique came out recently. This article will answer your questions: http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement

.hide-text {
  text-indent: 100%;
  white-space: nowrap;
  overflow: hidden;
}

It is accessible, an has better performance than -99999px.

Update: As @deathlock mentions in the comment area, the author of the fix above (Scott Kellum), has suggested using a transparent font: http://scottkellum.com/2013/10/25/the-new-kellum-method.html.

How to get folder directory from HTML input type "file" or any other way?

Eventhough it is an old question, this may help someone.

We can choose multiple files while browsing for a file using "multiple"

<input type="file" name="datafile" size="40"  multiple> 

Is a new line = \n OR \r\n?

If you are programming in PHP, it is useful to split lines by \n and then trim() each line (provided you don't care about whitespace) to give you a "clean" line regardless.

foreach($line in explode("\n", $data))
{
    $line = trim($line);
    ...
}

JS how to cache a variable

You have three options:

  1. Cookies: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
  2. DOMStorage (sessionStorage or localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
  3. If your users are logged in, you could persist data in your server's DB that is keyed to a user (or group)

Specifying Font and Size in HTML table

Enclose your code with the html and body tags. Size attribute does not correspond to font-size and it looks like its domain does not go beyond value 7. Furthermore font tag is not supported in HTML5. Consider this code for your case

<!DOCTYPE html>
<html>
<body>

<font size="2" face="Courier New" >
<table width="100%">
    <tr>
        <td><b>Client</b></td>
        <td><b>InstanceName</b></td>
        <td><b>dbname</b></td>
        <td><b>Filename</b></td>
        <td><b>KeyName</b></td>
        <td><b>Rotation</b></td>
        <td><b>Path</b></td>
    </tr>
    <tr>
        <td>NEWDEV6</td>
        <td>EXPRESS2012</td>
        <td>master</td><td>master.mdf</td>
        <td>test_key_16</td><td>0</td>
        <td>d:\Program&nbsp;Files\Microsoft&nbsp;SQL&nbsp;Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td>
    </tr>
</table>
</font>
<font size="5" face="Courier New" >
<table width="100%">
    <tr>
        <td><b>Client</b></td>
        <td><b>InstanceName</b></td>
        <td><b>dbname</b></td>
        <td><b>Filename</b></td>
        <td><b>KeyName</b></td>
        <td><b>Rotation</b></td>
        <td><b>Path</b></td></tr>
    <tr>
        <td>NEWDEV6</td>
        <td>EXPRESS2012</td>
        <td>master</td>
        <td>master.mdf</td>
        <td>test_key_16</td>
        <td>0</td>
        <td>d:\Program&nbsp;Files\Microsoft&nbsp;SQL&nbsp;Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td></tr>
</table></font>
</body>
</html>

Can't connect to localhost on SQL Server Express 2012 / 2016

Goto Start -> Programs -> Microsoft SQL ServerYYYY -> Configuration Tools -> SQL Server YYYY Configuration Manager or run "SQLServerManager12.msc".

Make sure that TCP/IP is enabled under Client Protocols.

Then go into "SQL Server Network Configuration" and double click TCP/IP. Click the "IP Addresses" tab and scroll to the bottom. Under "IP All" remove TCP Dynamic Ports if it is present and set TCP Port to 1433. Click OK and then go back to "SQL Server Services" and restart SQL Server instance. Now you can connect via localhost, at least I could.

enter image description here

Note that this error can of course occur when connecting from other applications as well. Example for a normal C# web application Web.config connection string:

<connectionStrings>
    <add name="DefaultConnection" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

Try the following code:

$cfg['Servers'][$i]['password'] = '';

if you see Password column field as 'No' for the 'root' user in Users Overview page of phpMyAdmin.

Interface defining a constructor signature?

As already well noted, you can't have constructors on an Interface. But since this is such a highly ranked result in Google some 7 years later, I thought I would chip in here - specifically to show how you could use an abstract base class in tandem with your existing Interface and maybe cut down on the amount of refactoring needed in the future for similar situations. This concept has already been hinted at in some of the comments but I thought it would be worth showing how to actually do it.

So you have your main interface that looks like this so far:

public interface IDrawable
{
    void Update();
    void Draw();
}

Now create an abstract class with the constructor you want to enforce. Actually, since it's now available since the time you wrote your original question, we can get a little fancy here and use generics in this situation so that we can adapt this to other interfaces that might need the same functionality but have different constructor requirements:

public abstract class MustInitialize<T>
{
    public MustInitialize(T parameters)
    {

    }
}

Now you'll need to create a new class that inherits from both the IDrawable interface and the MustInitialize abstract class:

public class Drawable : MustInitialize<GraphicsDeviceManager>, IDrawable
{
    GraphicsDeviceManager _graphicsDeviceManager;

    public Drawable(GraphicsDeviceManager graphicsDeviceManager)
        : base (graphicsDeviceManager)
    {
        _graphicsDeviceManager = graphicsDeviceManager;
    }

    public void Update()
    {
        //use _graphicsDeviceManager here to do whatever
    }

    public void Draw()
    {
        //use _graphicsDeviceManager here to do whatever
    }
}

Then just create an instance of Drawable and you're good to go:

IDrawable drawableService = new Drawable(myGraphicsDeviceManager);

The cool thing here is that the new Drawable class we created still behaves just like what we would expect from an IDrawable.

If you need to pass more than one parameter to the MustInitialize constructor, you can create a class that defines properties for all of the fields you'll need to pass in.

pop/remove items out of a python tuple

ok I figured out a crude way of doing it.

I store the "n" value in the for loop when condition is satisfied in a list (lets call it delList) then do the following:

    for ii in sorted(delList, reverse=True):
    tupleX.pop(ii)

Any other suggestions are welcome too.

Pass array to mvc Action via AJAX

You need to convert Array to string :

//arrayOfValues = [1, 2, 3];  
$.get('/controller/MyAction', { arrayOfValues: "1, 2, 3" }, function (data) {...

this works even in form of int, long or string

public ActionResult MyAction(int[] arrayOfValues )

Event binding on dynamically created elements?

Event binding on dynamically created elements

Single element:

$(document.body).on('click','.element', function(e) {  });

Child Element:

 $(document.body).on('click','.element *', function(e) {  });

Notice the added *. An event will be triggered for all children of that element.

I have noticed that:

$(document.body).on('click','.#element_id > element', function(e) {  });

It is not working any more, but it was working before. I have been using jQuery from Google CDN, but I don't know if they changed it.

jQuery function to get all unique elements from an array?

I would use underscore.js, which provides a uniq method that does what you want.

Vue.js: Conditional class style binding

if you want to apply separate css classes for same element with conditions in Vue.js you can use the below given method.it worked in my scenario.

html

 <div class="Main" v-bind:class="{ Sub: page}"  >

in here, Main and Sub are two different class names for same div element. v-bind:class directive is used to bind the sub class in here. page is the property we use to update the classes when it's value changed.

js

data:{
page : true;
}

here we can apply a condition if we needed. so, if the page property becomes true element will go with Main and Sub claases css styles. but if false only Main class css styles will be applied.

Calling startActivity() from outside of an Activity context

Kotlin version

val intent = Intent(Intent.ACTION_EDIT, ContactsContract.Profile.CONTENT_URI)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
this.startActivity(intent)

What’s the best way to load a JSONObject from a json text file?

try this:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils; 

    public class JsonParsing {

        public static void main(String[] args) throws Exception {
            InputStream is = 
                    JsonParsing.class.getResourceAsStream( "sample-json.txt");
            String jsonTxt = IOUtils.toString( is );

            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
            double coolness = json.getDouble( "coolness" );
            int altitude = json.getInt( "altitude" );
            JSONObject pilot = json.getJSONObject("pilot");
            String firstName = pilot.getString("firstName");
            String lastName = pilot.getString("lastName");

            System.out.println( "Coolness: " + coolness );
            System.out.println( "Altitude: " + altitude );
            System.out.println( "Pilot: " + lastName );
        }
    }

and this is your sample-json.txt , should be in json format

{
 'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':
     {
         'firstName':'Buzz',
         'lastName':'Aldrin'
     },
 'mission':'apollo 11'
}

Javascript to export html table to Excel

For UTF 8 Conversion and Currency Symbol Export Use this:

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
      if (!table.nodeType) table = document.getElementById(table)
      var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

add elements to object array

You can't. However, you can replace the array with a new one which contains the extra element.

But it is easier and gives better performance to use an List<T> (uses interface IList) for this. List<T> does not resize the array every time you add an item - instead it doubles it when needed.

Try:

class Student
{
    IList<Subject> subjects = new List<Subject>();
}

class Subject
{
    string Name;
    string referenceBook;
}

Now you can say:

someStudent.subjects.Add(new Subject());

Creating NSData from NSString in Swift

In swift 5

let data = Data(YourString.utf8)

.bashrc at ssh login

.bashrc is not sourced when you log in using SSH. You need to source it in your .bash_profile like this:

if [ -f ~/.bashrc ]; then
  . ~/.bashrc
fi

jQuery equivalent to Prototype array.last()

For arrays, you could simply retrieve the last element position with array.length - 1:

var a = [1,2,3,4];

var lastEl = a[a.length-1]; // 4

In jQuery you have the :last selector, but this won't help you on plain arrays.

Replace Multiple String Elements in C#

I'm doing something similar, but in my case I'm doing serialization/De-serialization so I need to be able to go both directions. I find using a string[][] works nearly identically to the dictionary, including initialization, but you can go the other direction too, returning the substitutes to their original values, something that the dictionary really isn't set up to do.

Edit: You can use Dictionary<Key,List<Values>> in order to obtain same result as string[][]

How to make lists contain only distinct element in Python?

Let me explain to you by an example:

if you have Python list

>>> randomList = ["a","f", "b", "c", "d", "a", "c", "e", "d", "f", "e"]

and you want to remove duplicates from it.

>>> uniqueList = []

>>> for letter in randomList:
    if letter not in uniqueList:
        uniqueList.append(letter)

>>> uniqueList
['a', 'f', 'b', 'c', 'd', 'e']

This is how you can remove duplicates from the list.

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

Remove the string on the beginning of an URL

You can overload the String prototype with a removePrefix function:

String.prototype.removePrefix = function (prefix) {
    const hasPrefix = this.indexOf(prefix) === 0;
    return hasPrefix ? this.substr(prefix.length) : this.toString();
};

usage:

const domain = "www.test.com".removePrefix("www."); // test.com

How to clear the text of all textBoxes in the form?

private void CleanForm(Control ctrl)
{
    foreach (var c in ctrl.Controls)
    {
        if (c is TextBox)
        {
            ((TextBox)c).Text = String.Empty;
        }

        if( c.Controls.Count > 0)
        {
           CleanForm(c);
        }
    }
}

When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

You could convert it to an array and then print that out with Arrays.toString(Object[]):

System.out.println(Arrays.toString(stack.toArray()));

How to solve "The specified service has been marked for deletion" error

steps to follow:

step-1 goto the location C:\Windows\Microsoft.NET\Framework\v4.0.30319

step-2 run command: installutil /u full-path/servicename.exe

step-3 close services panel and reopen it

step-4 run command: installutil full-path/servicename.exe

DROP IF EXISTS VS DROP?

It is not what is asked directly. But looking for how to do drop tables properly, I stumbled over this question, as I guess many others do too.

From SQL Server 2016+ you can use

DROP TABLE IF EXISTS dbo.Table

For SQL Server <2016 what I do is the following for a permanent table

IF OBJECT_ID('dbo.Table', 'U') IS NOT NULL 
  DROP TABLE dbo.Table; 

Or this, for a temporary table

IF OBJECT_ID('tempdb.dbo.#T', 'U') IS NOT NULL
  DROP TABLE #T; 

How do I remove a key from a JavaScript object?

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1
var key = "Cow";
delete thisIsObject[key]; 

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

If you're interested, read Understanding Delete for an in-depth explanation.

Select info from table where row has max date

SELECT group, date, checks
  FROM table 
  WHERE checks > 0
  GROUP BY group HAVING date = max(date) 

should work.

MS-access reports - The search key was not found in any record - on save

Any spaces in the names of the columns in Excel caused the error for me. Once I removed any spaces then it imported with no problems.

Setting a JPA timestamp column to be generated by the database?

I have this working well using JPA2.0 and MySQL 5.5.10, for cases where I only care about the last time the row was modified. MySQL will create a timestamp on first insertion, and every time UPDATE is called on the row. (NOTE: this will be problematic if I cared whether or not the UPDATE actually made a change).

The "timestamp" column in this example is like a "last-touched" column.x`

The code below uses a separate column "version" for optimistic locking.

private long version;
private Date timeStamp

@Version
public long getVersion() {
    return version;
}

public void setVersion(long version) {
    this.version = version;
}

// columnDefinition could simply be = "TIMESTAMP", as the other settings are the MySQL default
@Column(name="timeStamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
@Temporal(TemporalType.TIMESTAMP)
public Date getTimeStamp() {
    return timeStamp;
}

public void setTimeStamp(Date timeStamp) {
    this.timeStamp = timeStamp;
}

(NOTE: @Version doesn't work on a MySQL "DATETIME" column, where the attribute type is "Date" in the Entity class. This was because Date was generating a value down to the millisecond, however MySQL was not storing the millisecond, so when it did a comparison between what was in the database, and the "attached" entity, it thought they had different version numbers)

From the MySQL manual regarding TIMESTAMP :

With neither DEFAULT nor ON UPDATE clauses, it is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.

Send message to specific client with socket.io and node.js

The simplest, most elegant way

verified working with socket.io v3.1.1

It's as easy as:

client.emit("your message");

And that's it. Ok, but how does it work?

Minimal working example

Here's an example of a simple client-server interaction where each client regularly receives a message containing a sequence number. There is a unique sequence for each client and that's where the "I need to send a message to a particular client" comes into play.

Server

server.js

const
    {Server} = require("socket.io"),
    server = new Server(8000);

let
    sequenceNumberByClient = new Map();

// event fired every time a new client connects:
server.on("connection", (socket) => {
    console.info(`Client connected [id=${socket.id}]`);
    // initialize this client's sequence number
    sequenceNumberByClient.set(socket, 1);

    // when socket disconnects, remove it from the list:
    socket.on("disconnect", () => {
        sequenceNumberByClient.delete(socket);
        console.info(`Client gone [id=${socket.id}]`);
    });
});

// sends each client its current sequence number
setInterval(() => {
    for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) {
        client.emit("seq-num", sequenceNumber);
        sequenceNumberByClient.set(client, sequenceNumber + 1);
    }
}, 1000);

The server starts listening on port 8000 for incoming connections. As soon as a new connection is established, that client is added to a map that keeps track of its sequence number. The server also listens for the disconnect event to remove the client from the map when it leaves.

Each and every second, a timer is fired. When it does, the server walks through the map and sends a message to every client with their current sequence number, incrementing it right after. That's all that is to it. Easy peasy.

Client

The client part is even simpler. It just connects to the server and listens for the seq-num message, printing it to the console every time it arrives.

client.js

const
    io = require("socket.io-client"),
    ioClient = io.connect("http://localhost:8000");

ioClient.on("seq-num", (msg) => console.info(msg));

Running the example

Install the required libraries:

npm install [email protected] [email protected]

Run the server:

node server

Open other terminal windows and spawn as many clients as you want by running:

node client

I have also prepared a gist with the full code here.

SQL 'LIKE' query using '%' where the search criteria contains '%'

Escape the percent sign \% to make it part of your comparison value.

Bash script to calculate time elapsed

start=$(date +%Y%m%d%H%M%S);
for x in {1..5};
do echo $x;
sleep 1; done;
end=$(date +%Y%m%d%H%M%S);
elapsed=$(($end-$start));
ftime=$(for((i=1;i<=$((${#end}-${#elapsed}));i++));
        do echo -n "-";
        done;
        echo ${elapsed});
echo -e "Start  : ${start}\nStop   : ${end}\nElapsed: ${ftime}"

Start  : 20171108005304
Stop   : 20171108005310
Elapsed: -------------6

How to add an element at the end of an array?

You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :

public static void main(String[] args) {
    int[] array = new int[] {1, 2, 3};
    System.out.println(Arrays.toString(array));
    array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
    array[array.length - 1] = 4;
    System.out.println(Arrays.toString(array));
}

I would still recommend to drop working with an array and use a List.

Passing environment-dependent variables in webpack

I found the following solution to be easiest to setup environment variable for Webpack 2:

For example we have a webpack settings:

var webpack = require('webpack')

let webpackConfig = (env) => { // Passing envirmonment through
                                // function is important here
    return {
        entry: {
        // entries
        },

        output: {
        // outputs
        },

        plugins: [
        // plugins
        ],

        module: {
        // modules
        },

        resolve: {
        // resolves
        }

    }
};

module.exports = webpackConfig;

Add Environment Variable in Webpack:

plugins: [
    new webpack.EnvironmentPlugin({
       NODE_ENV: 'development',
       }),
]

Define Plugin Variable and add it to plugins:

    new webpack.DefinePlugin({
        'NODE_ENV': JSON.stringify(env.NODE_ENV || 'development')
    }),

Now when running webpack command, pass env.NODE_ENV as argument:

webpack --env.NODE_ENV=development

// OR

webpack --env.NODE_ENV development

Now you can access NODE_ENV variable anywhere in your code.

How to count the number of occurrences of a character in an Oracle varchar value?

REGEXP_COUNT should do the trick:

select REGEXP_COUNT('123-345-566', '-') from dual;

How do I get started with Node.js

First, learn the core concepts of Node.js:

Then, you're going to want to see what the community has to offer:

The gold standard for Node.js package management is NPM.

Finally, you're going to want to know what some of the more popular packages are for various tasks:

Useful Tools for Every Project:

  • Underscore contains just about every core utility method you want.
  • Lo-Dash is a clone of Underscore that aims to be faster, more customizable, and has quite a few functions that underscore doesn't have. Certain versions of it can be used as drop-in replacements of underscore.
  • TypeScript makes JavaScript considerably more bearable, while also keeping you out of trouble!
  • JSHint is a code-checking tool that'll save you loads of time finding stupid errors. Find a plugin for your text editor that will automatically run it on your code.

Unit Testing:

  • Mocha is a popular test framework.
  • Vows is a fantastic take on asynchronous testing, albeit somewhat stale.
  • Expresso is a more traditional unit testing framework.
  • node-unit is another relatively traditional unit testing framework.
  • AVA is a new test runner with Babel built-in and runs tests concurrently.

Web Frameworks:

  • Express.js is by far the most popular framework.
  • Koa is a new web framework designed by the team behind Express.js, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs.
  • sails.js the most popular MVC framework for Node.js, and is based on express. It is designed to emulate the familiar MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with a scalable, service-oriented architecture.
  • Meteor bundles together jQuery, Handlebars, Node.js, WebSocket, MongoDB, and DDP and promotes convention over configuration without being a Ruby on Rails clone.
  • Tower (deprecated) is an abstraction of a top of Express.js that aims to be a Ruby on Rails clone.
  • Geddy is another take on web frameworks.
  • RailwayJS is a Ruby on Rails inspired MVC web framework.
  • Sleek.js is a simple web framework, built upon Express.js.
  • Hapi is a configuration-centric framework with built-in support for input validation, caching, authentication, etc.
  • Trails is a modern web application framework. It builds on the pedigree of Rails and Grails to accelerate development by adhering to a straightforward, convention-based, API-driven design philosophy.

  • Danf is a full-stack OOP framework providing many features in order to produce a scalable, maintainable, testable and performant applications and allowing to code the same way on both the server (Node.js) and client (browser) sides.

  • Derbyjs is a reactive full-stack JavaScript framework. They are using patterns like reactive programming and isomorphic JavaScript for a long time.

  • Loopback.io is a powerful Node.js framework for creating APIs and easily connecting to backend data sources. It has an Angular.js SDK and provides SDKs for iOS and Android.

Web Framework Tools:

Networking:

  • Connect is the Rack or WSGI of the Node.js world.
  • Request is a very popular HTTP request library.
  • socket.io is handy for building WebSocket servers.

Command Line Interaction:

  • minimist just command line argument parsing.
  • Yargs is a powerful library for parsing command-line arguments.
  • Commander.js is a complete solution for building single-use command-line applications.
  • Vorpal.js is a framework for building mature, immersive command-line applications.
  • Chalk makes your CLI output pretty.

Code Generators:

  • Yeoman Scaffolding tool from the command-line.
  • Skaffolder Code generator with visual and command-line interface. It generates a customizable CRUD application starting from the database schema or an OpenAPI 3.0 YAML file.

Work with streams:

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

Jackson JSON custom serialization for certain fields

In case you don't want to pollute your model with annotations and want to perform some custom operations, you could use mixins.

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.setMixInAnnotation(Person.class, PersonMixin.class);
mapper.registerModule(simpleModule);

Override age:

public abstract class PersonMixin {
    @JsonSerialize(using = PersonAgeSerializer.class)
    public String age;
}

Do whatever you need with the age:

public class PersonAgeSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer integer, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(String.valueOf(integer * 52) + " months");
    }
}

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

Finding version of Microsoft C++ compiler from command-line (for makefiles)

I had the same problem today. I needed to set a flag in a nmake Makefile if the cl compiler version is 15. Here is the hack I came up with:

!IF ([cl /? 2>&1 | findstr /C:"Version 15" > nul] == 0)
FLAG = "cl version 15"
!ENDIF

Note that cl /? prints the version information to the standard error stream and the help text to the standard output. To be able to check the version with the findstr command one must first redirect stderr to stdout using 2>&1.

The above idea can be used to write a Windows batch file that checks if the cl compiler version is <= a given number. Here is the code of cl_version_LE.bat:

@echo off
FOR /L %%G IN (10,1,%1) DO cl /? 2>&1 | findstr /C:"Version %%G" > nul && goto FOUND
EXIT /B 0
:FOUND
EXIT /B 1

Now if you want to set a flag in your nmake Makefile if the cl version <= 15, you can use:

!IF [cl_version_LE.bat 15]
FLAG = "cl version <= 15"
!ENDIF

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

How to check radio button is checked using JQuery?

Given a group of radio buttons:

<input type="radio" id="radio1" name="radioGroup" value="1">
<input type="radio" id="radio2" name="radioGroup" value="2">

You can test whether a specific one is checked using jQuery as follows:

if ($("#radio1").prop("checked")) {
   // do something
}

// OR
if ($("#radio1").is(":checked")) {
   // do something
}

// OR if you don't have ids set you can go by group name and value
// (basically you need a selector that lets you specify the particular input)
if ($("input[name='radioGroup'][value='1']").prop("checked"))

You can get the value of the currently checked one in the group as follows:

$("input[name='radioGroup']:checked").val()

Fitting iframe inside a div

Would this CSS fix it?

iframe {
    display:block;
    width:100%;
}

From this example: http://jsfiddle.net/HNyJS/2/show/

Difference between java HH:mm and hh:mm on SimpleDateFormat

Please take a look here

HH is hour in a day (starting from 0 to 23)

hh are hours in am/pm format

kk is hour in day (starting from 1 to 24)

mm is minute in hour

ss are the seconds in a minute

Python requests - print entire http request (raw)?

An even better idea is to use the requests_toolbelt library, which can dump out both requests and responses as strings for you to print to the console. It handles all the tricky cases with files and encodings which the above solution does not handle well.

It's as easy as this:

import requests
from requests_toolbelt.utils import dump

resp = requests.get('https://httpbin.org/redirect/5')
data = dump.dump_all(resp)
print(data.decode('utf-8'))

Source: https://toolbelt.readthedocs.org/en/latest/dumputils.html

You can simply install it by typing:

pip install requests_toolbelt

In Android EditText, how to force writing uppercase?

Simple kotlin realization

fun EditText.onlyUppercase() {
    inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
    filters = arrayOf(InputFilter.AllCaps())
}

PS it seems that filters is always empty initially

How can I send an email through the UNIX mailx command?

Its faster with MUTT command

echo "Body Of the Email"  | mutt -a "File_Attachment.csv" -s "Daily Report for $(date)"  -c [email protected] [email protected] -y
  1. -c email cc list
  2. -s subject list
  3. -y to send the mail

How to re-enable right click so that I can inspect HTML elements in Chrome?

This bookmarlet works in Google sites/Youtube as of Aug 2019 (tested in Chrome and Firefox):

javascript: function enableContextMenu(aggressive = false) { void(document.ondragstart=null); void(document.onselectstart=null); void(document.onclick=null); void(document.onmousedown=null); void(document.onmouseup=null); void(document.body.oncontextmenu=null); enableRightClickLight(document); if (aggressive) { enableRightClick(document); removeContextMenuOnAll("body"); removeContextMenuOnAll("img"); removeContextMenuOnAll("td"); } } function removeContextMenuOnAll(tagName) { var elements = document.getElementsByTagName(tagName); for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]); } } function enableRightClickLight(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); } function enableRightClick(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); el.addEventListener("dragstart", bringBackDefault, true); el.addEventListener("selectstart", bringBackDefault, true); el.addEventListener("click", bringBackDefault, true); el.addEventListener("mousedown", bringBackDefault, true); el.addEventListener("mouseup", bringBackDefault, true); } function restoreRightClick(el) { el || (el = document); el.removeEventListener("contextmenu", bringBackDefault, true); el.removeEventListener("dragstart", bringBackDefault, true); el.removeEventListener("selectstart", bringBackDefault, true); el.removeEventListener("click", bringBackDefault, true); el.removeEventListener("mousedown", bringBackDefault, true); el.removeEventListener("mouseup", bringBackDefault, true); } function bringBackDefault(event) { event.returnValue = true; (typeof event.stopPropagation === 'function') && event.stopPropagation(); (typeof event.cancelBubble === 'function') && event.cancelBubble(); } enableContextMenu();

For peskier sites, set/pass aggressive to true (this will disable most event handlers and hence disable interaction with the page):

javascript: function enableContextMenu(aggressive = true) { void(document.ondragstart=null); void(document.onselectstart=null); void(document.onclick=null); void(document.onmousedown=null); void(document.onmouseup=null); void(document.body.oncontextmenu=null); enableRightClickLight(document); if (aggressive) { enableRightClick(document); removeContextMenuOnAll("body"); removeContextMenuOnAll("img"); removeContextMenuOnAll("td"); } } function removeContextMenuOnAll(tagName) { var elements = document.getElementsByTagName(tagName); for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]); } } function enableRightClickLight(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); } function enableRightClick(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); el.addEventListener("dragstart", bringBackDefault, true); el.addEventListener("selectstart", bringBackDefault, true); el.addEventListener("click", bringBackDefault, true); el.addEventListener("mousedown", bringBackDefault, true); el.addEventListener("mouseup", bringBackDefault, true); } function restoreRightClick(el) { el || (el = document); el.removeEventListener("contextmenu", bringBackDefault, true); el.removeEventListener("dragstart", bringBackDefault, true); el.removeEventListener("selectstart", bringBackDefault, true); el.removeEventListener("click", bringBackDefault, true); el.removeEventListener("mousedown", bringBackDefault, true); el.removeEventListener("mouseup", bringBackDefault, true); } function bringBackDefault(event) { event.returnValue = true; (typeof event.stopPropagation === 'function') && event.stopPropagation(); (typeof event.cancelBubble === 'function') && event.cancelBubble(); } enableContextMenu();

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

How to filter empty or NULL names in a QuerySet?

Firstly, the Django docs strongly recommend not using NULL values for string-based fields such as CharField or TextField. Read the documentation for the explanation:

https://docs.djangoproject.com/en/dev/ref/models/fields/#null

Solution: You can also chain together methods on QuerySets, I think. Try this:

Name.objects.exclude(alias__isnull=True).exclude(alias="")

That should give you the set you're looking for.

What is the iBeacon Bluetooth Profile

It seems to based on advertisement data, particularly the manufacturer data:

4C00 02 15 585CDE931B0142CC9A1325009BEDC65E 0000 0000 C5

<company identifier (2 bytes)> <type (1 byte)> <data length (1 byte)>
    <uuid (16 bytes)> <major (2 bytes)> <minor (2 bytes)> <RSSI @ 1m>
  • Apple Company Identifier (Little Endian), 0x004c
  • data type, 0x02 => iBeacon
  • data length, 0x15 = 21
  • uuid: 585CDE931B0142CC9A1325009BEDC65E
  • major: 0000
  • minor: 0000
  • meaured power at 1 meter: 0xc5 = -59

I have this node.js script working on Linux with the sample AirLocate app example.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Use these commands on a windows command prompt(cmd) with administrator privilege (run as administrator):

netsh wlan set hostednetwork mode=allow ssid=tests key=tests123

netsh wlan start hostednetwork

Then you go to Network and sharing center and click on "change adapter settings" (I'm using windows 7, it can be a little different on windows 8)

Then right click on the lan connection (internet connection that you are using), properties.

Click on sharing tab, select the wireless connection tests (the name tests you can change on the command line) and check "Allow other network users to connect through this network connection"

This done, your connection is ready to use!

Best way to convert text files between character sets?

PHP iconv()

iconv("UTF-8", "ISO-8859-15", $input);

Twitter Bootstrap carousel different height images cause bouncing arrows

It looks like bootstrap less/CSS forces an automatic height to avoid stretching the image when the width has to change to be responsive. I switched it around to make the width auto and fix the height.

<div class="item peopleCarouselImg">
  <img src="http://upload.wikimedia.org/...">
  ...
</div>

I then define img with a class peopleCarouselImg like this:

.peopleCarouselImg img {
  width: auto;
  height: 225px;
  max-height: 225px;
}

I fix my height to 225px. I let the width automatically adjust to keep the aspect ratio correct.

This seems to work for me.

Command to collapse all sections of code?

if you want to collapse and expand particular loop, if else then install following plugins for visual studio.

enter image description here

Change div height on button click

Do this:

function changeHeight() {
document.getElementById('chartdiv').style.height = "200px"
}
<button type="button" onClick="changeHeight();"> Click Me!</button>

How do I run a simple bit of code in a new thread?

If you are going to use the raw Thread object then you need to set IsBackground to true at a minimum and you should also set the Threading Apartment model (probably STA).

public static void DoWork()
{
    // do some work
}

public static void StartWorker()
{
    Thread worker = new Thread(DoWork);
    worker.IsBackground = true;
    worker.SetApartmentState(System.Threading.ApartmentState.STA);
    worker.Start()
}

I would recommend the BackgroundWorker class if you need UI interaction.

Addition for BigDecimal

It's actually rather easy. Just do this:

BigDecimal test = new BigDecimal(0);
System.out.println(test);
test = test.add(new BigDecimal(30));
System.out.println(test);
test = test.add(new BigDecimal(45));
System.out.println(test);

See also: BigDecimal#add(java.math.BigDecimal)

Java, How to get number of messages in a topic in apache kafka

Use https://prestodb.io/docs/current/connector/kafka-tutorial.html

A super SQL engine, provided by Facebook, that connects on several data sources (Cassandra, Kafka, JMX, Redis ...).

PrestoDB is running as a server with optional workers (there is a standalone mode without extra workers), then you use a small executable JAR (called presto CLI) to make queries.

Once you have configured well the Presto server , you can use traditionnal SQL:

SELECT count(*) FROM TOPIC_NAME;

Sort a list of tuples by 2nd item (integer value)

Adding to Cheeken's answer, This is how you sort a list of tuples by the 2nd item in descending order.

sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)],key=lambda x: x[1], reverse=True)

How do I change the string representation of a Python class?

The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self):
     return "foo"

You may also want to implement __repr__ to aid in debugging.

See here for more information:

How to get the absolute path to the public_html folder?

This is super old, but I came across it and this worked for me.

<?php
//Get absolute path
$path = getcwd();
//strip the path at your root dir name and everything that follows it
$path = substr($path, 0, strpos($path, "root"));
echo "This Is Your Absolute Path: ";
echo $path; //This will output /home/public_html/
?>

How to Empty Caches and Clean All Targets Xcode 4 and later

Command-Option-Shift-K to clean out the build folder. Even better, quit Xcode and clean out ~/Library/Developer/Xcode/DerivedData manually. Remove all its contents because there's a bug where Xcode will run an old version of your project that's in there somewhere. (Xcode 4.2 will show you the Derived Data folder: choose Window > Organizer and switch to the Projects tab. Click the right-arrow to the right of the Derived Data folder name.)

In the simulator, choose iOS Simulator > Reset Content and Settings.

Finally, for completeness, you can delete the contents of /var/folders; some caching happens there too.

WARNING: Deleting /var/folders can cause issues, and you may need to repair or reinstall your operating system after doing so.

EDIT: I have just learned that if you are afraid to grapple with /var/folders/ you can use the following command in the Terminal to delete in a more targeted way:

rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"

EDIT: For certain Swift-related problems I have found it useful to delete ~/Library/Caches/com.apple.dt.Xcode. You lose a lot when you do this, like your spare copies of the downloaded documentation doc sets, but it can be worth it.

transform object to array with lodash

There are quite a few ways to get the result you are after. Lets break them in categories:

ES6 Values only:

Main method for this is Object.values. But using Object.keys and Array.map you could as well get to the expected result:

Object.values(obj)
Object.keys(obj).map(k => obj[k])

_x000D_
_x000D_
var obj = {_x000D_
  A: {_x000D_
    name: "John"_x000D_
  },_x000D_
  B: {_x000D_
    name: "Ivan"_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log('Object.values:', Object.values(obj))_x000D_
console.log('Object.keys:', Object.keys(obj).map(k => obj[k]))
_x000D_
_x000D_
_x000D_

ES6 Key & Value:

Using map and ES6 dynamic/computed properties and destructuring you can retain the key and return an object from the map.

Object.keys(obj).map(k => ({[k]: obj[k]}))
Object.entries(obj).map(([k,v]) => ({[k]:v}))

_x000D_
_x000D_
var obj = {_x000D_
  A: {_x000D_
    name: "John"_x000D_
  },_x000D_
  B: {_x000D_
    name: "Ivan"_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log('Object.keys:', Object.keys(obj).map(k => ({_x000D_
  [k]: obj[k]_x000D_
})))_x000D_
console.log('Object.entries:', Object.entries(obj).map(([k, v]) => ({_x000D_
  [k]: v_x000D_
})))
_x000D_
_x000D_
_x000D_

Lodash Values only:

The method designed for this is _.values however there are "shortcuts" like _.map and the utility method _.toArray which would also return an array containing only the values from the object. You could also _.map though the _.keys and get the values from the object by using the obj[key] notation.

Note: _.map when passed an object would use its baseMap handler which is basically forEach on the object properties.

_.values(obj)
_.map(obj)
_.toArray(obj)
_.map(_.keys(obj), k => obj[k])

_x000D_
_x000D_
var obj = {_x000D_
  A: {_x000D_
    name: "John"_x000D_
  },_x000D_
  B: {_x000D_
    name: "Ivan"_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log('values:', _.values(obj))_x000D_
console.log('map:', _.map(obj))_x000D_
console.log('toArray:', _.toArray(obj))_x000D_
console.log('keys:', _.map(_.keys(obj), k => obj[k]))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Lodash Key & Value:

// Outputs an array with [[KEY, VALUE]]
_.entries(obj)
_.toPairs(obj)

// Outputs array with objects containing the keys and values
_.map(_.entries(obj), ([k,v]) => ({[k]:v}))
_.map(_.keys(obj), k => ({[k]: obj[k]}))
_.transform(obj, (r,c,k) => r.push({[k]:c}), [])
_.reduce(obj, (r,c,k) => (r.push({[k]:c}), r), [])

_x000D_
_x000D_
var obj = {_x000D_
  A: {_x000D_
    name: "John"_x000D_
  },_x000D_
  B: {_x000D_
    name: "Ivan"_x000D_
  }_x000D_
}_x000D_
_x000D_
// Outputs an array with [KEY, VALUE]_x000D_
console.log('entries:', _.entries(obj))_x000D_
console.log('toPairs:', _.toPairs(obj))_x000D_
_x000D_
// Outputs array with objects containing the keys and values_x000D_
console.log('entries:', _.map(_.entries(obj), ([k, v]) => ({_x000D_
  [k]: v_x000D_
})))_x000D_
console.log('keys:', _.map(_.keys(obj), k => ({_x000D_
  [k]: obj[k]_x000D_
})))_x000D_
console.log('transform:', _.transform(obj, (r, c, k) => r.push({_x000D_
  [k]: c_x000D_
}), []))_x000D_
console.log('reduce:', _.reduce(obj, (r, c, k) => (r.push({_x000D_
  [k]: c_x000D_
}), r), []))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Note that in the above examples ES6 is used (arrow functions and dynamic properties). You can use lodash _.fromPairs and other methods to compose an object if ES6 is an issue.

Replace words in the body text

While using innerHTML.replace will work and is pretty fast, this will break the DOM state. You can replicate this by setting "autofocus" on an input field and then changing innerHTML on body, it will loose focus.

A less destructive approach is:

// retrives all childNodes of body
var childNodes = document.body.childNodes;

// start replacing
replaceInNodes(childNodes,"search","replace");

function replaceInNodes(nodes,search,replace){
    // iterate through all nodes
    for (var i = 0; i < nodes.length; i++) { 
            var curNode = nodes[i];
            // if the node has attributes, let us look at those
            // i.E. we want to change "John" in the input placeholder to "Peter" - <input type="text" value="John">
            if(curNode.attributes !== undefined){
                var curNodeAttributes = curNode.attributes;
                for (var ii = 0; ii < curNodeAttributes.length; ii++) {
                    // replace attribute values
                    curNodeAttributes[ii].nodeValue = curNodeAttributes[ii].nodeValue.replace(search, replace);
                }   
            }
            // It is a "TEXT_NODE"
            // i.E. <span>John</span>
            if(curNode.nodeType == 3){
                curNode.data = this.injectIntoString(curNode.data);
            }
            // It is a "ELEMENT_NODE", meaning we need to go deeper
            if(curNode.nodeType == 1){
                this.replaceInNodes(curNode.childNodes);
            }
        }
}

More info can be found here: https://zgheb.com/i?v=blog&pl=71#12.11.2020_-_Unobstrusively_replace_text_with_JavaScript Note: I am the author of said link

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

If you are using InnoDB or any row-level transactional RDBMS, then it is possible that any write transaction can cause a deadlock, even in perfectly normal situations. Larger tables, larger writes, and long transaction blocks will often increase the likelihood of deadlocks occurring. In your situation, it's probably a combination of these.

The only way to truly handle deadlocks is to write your code to expect them. This generally isn't very difficult if your database code is well written. Often you can just put a try/catch around the query execution logic and look for a deadlock when errors occur. If you catch one, the normal thing to do is just attempt to execute the failed query again.

I highly recommend you read this page in the MySQL manual. It has a list of things to do to help cope with deadlocks and reduce their frequency.

How to check if a String contains any of some strings

If you need ContainsAny with a specific StringComparison (for example to ignore case) then you can use this String Extentions method.

public static class StringExtensions
{
    public static bool ContainsAny(this string input, IEnumerable<string> containsKeywords, StringComparison comparisonType)
    {
        return containsKeywords.Any(keyword => input.IndexOf(keyword, comparisonType) >= 0);
    }
}

Usage with StringComparison.CurrentCultureIgnoreCase:

var input = "My STRING contains Many Substrings";
var substrings = new[] {"string", "many substrings", "not containing this string" };
input.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// The statement above returns true.

”xyz”.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// This statement returns false.

unable to start mongodb local server

Try either killall -15 mongod/ killall mongod Even after this if this doesnt work then remove the db storage folder by typing the following commands sudo rm -rf /data/db sudo mkdir /data/db sudo chmod 777 /data/db

row-level trigger vs statement-level trigger

statement level trigger is only once for dml statement row leval trigger is for each row for dml statements

Convert file: Uri to File in Android

None of this works for me. I found this to be the working solution. But my case is specific to images.

String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();

AngularJS view not updating on model change

setTimout executes outside of angular. You need to use $timeout service for this to work:

var app = angular.module('test', []);

    app.controller('TestCtrl', function ($scope, $timeout) {
       $scope.testValue = 0;

        $timeout(function() {
            console.log($scope.testValue++);
        }, 500);
    });

The reason is that two-way binding in angular uses dirty checking. This is a good article to read about angular's dirty checking. $scope.$apply() kicks off a $digest cycle. This will apply the binding. $timeout handles the $apply for you so it is the recommended service to use when using timeouts.

Essentially, binding happens during the $digest cycle (if the value is seen to be different).

Find unique lines

uniq has the option you need:

   -u, --unique
          only print unique lines
$ cat file.txt
1
1
2
3
5
5
7
7
$ uniq -u file.txt
2
3

Connect to SQL Server database from Node.js

We just released preview driver for Node.JS for SQL Server connectivity. You can find it here: Introducing the Microsoft Driver for Node.JS for SQL Server.

The driver supports callbacks (here, we're connecting to a local SQL Server instance):

// Query with explicit connection
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server=(local);Database=AdventureWorks2012;Trusted_Connection={Yes}";

sql.open(conn_str, function (err, conn) {
    if (err) {
        console.log("Error opening the connection!");
        return;
    }
    conn.queryRaw("SELECT TOP 10 FirstName, LastName FROM Person.Person", function (err, results) {
        if (err) {
            console.log("Error running query!");
            return;
        }
        for (var i = 0; i < results.rows.length; i++) {
            console.log("FirstName: " + results.rows[i][0] + " LastName: " + results.rows[i][1]);
        }
    });
});

Alternatively, you can use events (here, we're connecting to SQL Azure a.k.a Windows Azure SQL Database):

// Query with streaming
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server={tcp:servername.database.windows.net,1433};UID={username};PWD={Password1};Encrypt={Yes};Database={databasename}";

var stmt = sql.query(conn_str, "SELECT FirstName, LastName FROM Person.Person ORDER BY LastName OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY");
stmt.on('meta', function (meta) { console.log("We've received the metadata"); });
stmt.on('row', function (idx) { console.log("We've started receiving a row"); });
stmt.on('column', function (idx, data, more) { console.log(idx + ":" + data);});
stmt.on('done', function () { console.log("All done!"); });
stmt.on('error', function (err) { console.log("We had an error :-( " + err); });

If you run into any problems, please file an issue on Github: https://github.com/windowsazure/node-sqlserver/issues

QComboBox - set selected item based on the item's data

You can also have a look at the method findText(const QString & text) from QComboBox; it returns the index of the element which contains the given text, (-1 if not found). The advantage of using this method is that you don't need to set the second parameter when you add an item.

Here is a little example :

/* Create the comboBox */
QComboBox   *_comboBox = new QComboBox;

/* Create the ComboBox elements list (here we use QString) */
QList<QString> stringsList;
stringsList.append("Text1");
stringsList.append("Text3");
stringsList.append("Text4");
stringsList.append("Text2");
stringsList.append("Text5");

/* Populate the comboBox */
_comboBox->addItems(stringsList);

/* Create the label */
QLabel *label = new QLabel;

/* Search for "Text2" text */
int index = _comboBox->findText("Text2");
if( index == -1 )
    label->setText("Text2 not found !");
else
    label->setText(QString("Text2's index is ")
                   .append(QString::number(_comboBox->findText("Text2"))));

/* setup layout */
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(_comboBox);
layout->addWidget(label);

Safest way to run BAT file from Powershell script

What about invoke-item script.bat.

Phone number validation Android

Given the rules you specified:

upto length 13 and including character + infront.

(and also incorporating the min length of 10 in your code)

You're going to want a regex that looks like this:

^\+[0-9]{10,13}$

With the min and max lengths encoded in the regex, you can drop those conditions from your if() block.

Off topic: I'd suggest that a range of 10 - 13 is too limiting for an international phone number field; you're almost certain to find valid numbers that are both longer and shorter than this. I'd suggest a range of 8 - 20 to be safe.

[EDIT] OP states the above regex doesn't work due to the escape sequence. Not sure why, but an alternative would be:

^[+][0-9]{10,13}$

[EDIT 2] OP now adds that the + sign should be optional. In this case, the regex needs a question mark after the +, so the example above would now look like this:

^[+]?[0-9]{10,13}$

Abstract Class:-Real Time Example

The best example of an abstract class is GenericServlet. GenericServlet is the parent class of HttpServlet. It is an abstract class.

When inheriting 'GenericServlet' in a custom servlet class, the service() method must be overridden.

How to add color to Github's README.md file

I added some color to a GitHub markup page using emoji Enicode chars, e.g. or -- some emoji characters are colored in some browsers.

There are also some colored emoji alphabets: blood types ???; parking sign ?; Metro sign ??; a few others with two or more letters, such as , and boxed digits such as 0??. Flag emojis will show as letters (often colored) if the flag is not available: .

However, I don't think there is a complete colored alphabet defined in emoji.

Javascript Click on Element by Class

class of my button is "input-addon btn btn-default fileinput-exists"

below code helped me

document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();

but I want to click second button, I have two buttons in my screen so I used querySelectorAll

var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
                elem[1].click();

here elem[1] is the second button object that I want to click.

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

If you set CURLOPT_RETURNTRANSFER to true or 1 then the return value from curl_exec will be the actual result from the successful operation. In other words it will not return TRUE on success. Although it will return FALSE on failure.

As described in the Return Values section of curl-exec PHP manual page: http://php.net/manual/function.curl-exec.php

You should enable the CURLOPT_FOLLOWLOCATION option for redirects but this would be a problem if your server is in safe_mode and/or open_basedir is in effect which can cause issues with curl as well.

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

Using Python 3 in virtualenv

The below simple commands can create a virtual env with version 3.5

apt-get install python3-venv

python3.5 -m venv <your env name>

if you want virtual env version as 3.6

python3.6 -m venv <your env name>

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch
       form).

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

How to customize <input type="file">?

Just style a normal button however you want, using your favorite CSS.

Then call a simple JS function to create and link a hidden input element to your styled button. Don't add browser-specific CSS to do the hiding part.

<!DOCTYPE html>
<meta charset="utf-8">

<style>
    button {
        width            : 160px;
        height           : 30px;
        font-size        : 13px;
        border           : none;
        text-align       : center;
        background-color : #444;
        color            : #6f0;
    }
    button:active {
        background-color : #779;
    }
</style>

<button id="upload">Styled upload button!</button>

<script>

function Upload_On_Click(id, handler) {
    var hidden_input = null;
    document.getElementById(id).onclick = function() {hidden_input.click();}
    function setup_hidden_input() {
        hidden_input && hidden_input.parentNode.removeChild(hidden_input);
        hidden_input = document.createElement("input");
        hidden_input.setAttribute("type", "file");
        hidden_input.style.visibility = "hidden";
        document.querySelector("body").appendChild(hidden_input);
        hidden_input.onchange = function() {
            handler(hidden_input.files[0]);
            setup_hidden_input();
        };
    }
    setup_hidden_input();
}

Upload_On_Click("upload", function(file) {
    console.log("GOT FILE: " + file.name);
});

</script>

Notice how the above code re-links it after every time the user chooses a file. This is important because "onchange" is only called if the user changes the filename. But you probably want to get the file every time the user provides it.

For more details, research DropZone and gmail uploads.

Single line sftp from terminal

Update Sep 2017 - tl;dr

Download a single file from a remote ftp server to your machine:

sftp {user}@{host}:{remoteFileName} {localFileName}

Upload a single file from your machine to a remote ftp server:

sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'

Original answer:

Ok, so I feel a little dumb. But I figured it out. I almost had it at the top with:

sftp user@host remoteFile localFile

The only documentation shown in the terminal is this:

sftp [user@]host[:file ...]
sftp [user@]host[:dir[/]]

However, I came across this site which shows the following under the synopsis:

sftp [-vC1 ] [-b batchfile ] [-o ssh_option ] [-s subsystem | sftp_server ] [-B buffer_size ] [-F ssh_config ] [-P sftp_server path ] [-R num_requests ] [-S program ] host 
sftp [[user@]host[:file [file]]] 
sftp [[user@]host[:dir[/]]]

So the simple answer is you just do : after your user and host then the remote file and local filename. Incredibly simple!

Single line, sftp copy remote file:

sftp username@hostname:remoteFileName localFileName
sftp kyle@kylesserver:/tmp/myLogFile.log /tmp/fileNameToUseLocally.log

Update Feb 2016

In case anyone is looking for the command to do the reverse of this and push a file from your local computer to a remote server in one single line sftp command, user @Thariama below posted the solution to accomplish that. Hat tip to them for the extra code.

sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'

How is a non-breaking space represented in a JavaScript string?

&nbsp; is a HTML entity. When doing .text(), all HTML entities are decoded to their character values.

Instead of comparing using the entity, compare using the actual raw character:

var x = td.text();
if (x == '\xa0') { // Non-breakable space is char 0xa0 (160 dec)
  x = '';
}

Or you can also create the character from the character code manually it in its Javascript escaped form:

var x = td.text();
if (x == String.fromCharCode(160)) { // Non-breakable space is char 160
  x = '';
}

More information about String.fromCharCode is available here:

fromCharCode - MDC Doc Center

More information about character codes for different charsets are available here:

Windows-1252 Charset
UTF-8 Charset

Entity Framework The underlying provider failed on Open

We had connection string in web.config with Data Source=localhost, and there was this error (MSSQL was on the same machine). Changing it to actual `DOMAIN\MACHINE' helped, somewhy.

C++ preprocessor __VA_ARGS__ number of arguments

If you are using C++11, and you need the value as a C++ compile-time constant, a very elegant solution is this:

#include <tuple>

#define MACRO(...) \
    std::cout << "num args: " \
    << std::tuple_size<decltype(std::make_tuple(__VA_ARGS__))>::value \
    << std::endl;

Please note: the counting happens entirely at compile time, and the value can be used whenever compile-time integer is required, for instance as a template parameter to std::array.

How to set HTML5 required attribute in Javascript?

What matters isn't the attribute but the property, and its value is a boolean.

You can set it using

 document.getElementById("edName").required = true;

What is the default Precision and Scale for a Number in Oracle?

I believe the default precision is 38, default scale is zero. However the actual size of an instance of this column, is dynamic. It will take as much space as needed to store the value, or max 21 bytes.

How are VST Plugins made?

If you know a .NET language (C#/VB.NET etc) then checkout VST.NET. This framework allows you to create (unmanaged) VST 2.4 plugins in .NET. It comes with a framework that structures and simplifies the creation of a VST Plugin with support for Parameters, Programs and Persistence.

There are several samples that demonstrate the typical plugin scenarios. There's also documentation that explains how to get started and some of the concepts behind VST.NET.

Hope it helps. Marc Jacobi

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

The marked answer is the correct one. However, Pricey, you should follow up on this with your AD and desktop admin groups. They are misusing the IE11 Enterprise Mode site list. Microsoft does NOT intend it to be used for all intranet sites within an organization at all. That would be propagating the existing "render all intranet sites in compatibility mode" setting that is the bane of corporate website advancement the world over.

It's meant to implemented as a "Black list", with the handful of sites that actually require a legacy browser mode listed in the Enterprise Mode list with their rendering requirements specified. All other sites in your organization are then freed up to use Edge. The people in your organization who implemented it with all intranet sites included to start with have completely misunderstood how Enterprise Mode is meant to be implemented.

Can not connect to local PostgreSQL

I was getting this same error (it turns out it was an error with postmaster.pid. Here's how I got postgres up and running again (credit to Ricardo Burillo for the fix):

$ rm /usr/local/var/postgres/postmaster.pid 
$ pg_resetxlog -f /usr/local/var/postgres

Javac is not found

As far as I can see you have the JRE in your PATH, but not the JDK.

From a command prompt try this:

set PATH=%PATH%;C:\Program Files (x86)\Java\jdk1.7.0_17\bin

Then try javac again - if this works you'll need to permanently modify your environment variables to have PATH include the JDK too.

Why can templates only be implemented in the header file?

A way to have separate implementation is as follows.

//inner_foo.h

template <typename T>
struct Foo
{
    void doSomething(T param);
};


//foo.tpp
#include "inner_foo.h"
template <typename T>
void Foo<T>::doSomething(T param)
{
    //implementation
}


//foo.h
#include <foo.tpp>

//main.cpp
#include <foo.h>

inner_foo has the forward declarations. foo.tpp has the implementation and include inner_foo.h; and foo.h will have just one line, to include foo.tpp.

On compile time, contents of foo.h are copied to foo.tpp and then the whole file is copied to foo.h after which it compiles. This way, there is no limitations, and the naming is consistent, in exchange for one extra file.

I do this because static analyzers for the code break when it does not see the forward declarations of class in *.tpp. This is annoying when writing code in any IDE or using YouCompleteMe or others.

Converting NSString to NSDate (and back again)

Best practice is to build yourself a general class where you put all your general use methods, methods useful in almost all projects and there add the code suggested by @Pavan as:

+ (NSDate *)getDateOutOfString:(NSString *)passedString andDateFormat:(NSString *)dateFormat{

    NSString *dateString = passedString;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [dateFormatter dateFromString:dateString];
    return dateFromString;

}

.. and so on for all other useful methods

By doing so you start building a clean reusable code for you app. Cheers!

How to check if array element exists or not in javascript?

_x000D_
_x000D_
var fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
if(fruits.indexOf("Banana") == -1){_x000D_
    console.log('item not exist')_x000D_
} else {_x000D_
 console.log('item exist')_x000D_
}
_x000D_
_x000D_
_x000D_

How can I read command line parameters from an R script?

Try library(getopt) ... if you want things to be nicer. For example:

spec <- matrix(c(
        'in'     , 'i', 1, "character", "file from fastq-stats -x (required)",
        'gc'     , 'g', 1, "character", "input gc content file (optional)",
        'out'    , 'o', 1, "character", "output filename (optional)",
        'help'   , 'h', 0, "logical",   "this help"
),ncol=5,byrow=T)

opt = getopt(spec);

if (!is.null(opt$help) || is.null(opt$in)) {
    cat(paste(getopt(spec, usage=T),"\n"));
    q();
}

How to extract numbers from a string and get an array of ints?

public static String extractNumberFromString(String number) {
    String num = number.replaceAll("[^0-9]+", " ");
    return num.replaceAll(" ", "");
}

extracts only numbers from string

How to delete a record in Django models?

There are a couple of ways:

To delete it directly:

SomeModel.objects.filter(id=id).delete()

To delete it from an instance:

instance = SomeModel.objects.get(id=id)
instance.delete()

How to make a TextBox accept only alphabetic characters?

private void textbox1_KeyDown_1(object sender, KeyEventArgs e)
{
    if (e.Key >= Key.A && e.Key <= Key.Z)
    {
    }
    else
    {
       e.Handled = true;
    }
}

Count lines in large files

Your limiting speed factor is the I/O speed of your storage device, so changing between simple newlines/pattern counting programs won't help, because the execution speed difference between those programs are likely to be suppressed by the way slower disk/storage/whatever you have.

But if you have the same file copied across disks/devices, or the file is distributed among those disks, you can certainly perform the operation in parallel. I don't know specifically about this Hadoop, but assuming you can read a 10gb the file from 4 different locations, you can run 4 different line counting processes, each one in one part of the file, and sum their results up:

$ dd bs=4k count=655360 if=/path/to/copy/on/disk/1/file | wc -l &
$ dd bs=4k skip=655360 count=655360 if=/path/to/copy/on/disk/2/file | wc -l &
$ dd bs=4k skip=1310720 count=655360 if=/path/to/copy/on/disk/3/file | wc -l &
$ dd bs=4k skip=1966080 if=/path/to/copy/on/disk/4/file | wc -l &

Notice the & at each command line, so all will run in parallel; dd works like cat here, but allow us to specify how many bytes to read (count * bs bytes) and how many to skip at the beginning of the input (skip * bs bytes). It works in blocks, hence, the need to specify bs as the block size. In this example, I've partitioned the 10Gb file in 4 equal chunks of 4Kb * 655360 = 2684354560 bytes = 2.5GB, one given to each job, you may want to setup a script to do it for you based on the size of the file and the number of parallel jobs you will run. You need also to sum the result of the executions, what I haven't done for my lack of shell script ability.

If your filesystem is smart enough to split big file among many devices, like a RAID or a distributed filesystem or something, and automatically parallelize I/O requests that can be paralellized, you can do such a split, running many parallel jobs, but using the same file path, and you still may have some speed gain.

EDIT: Another idea that occurred to me is, if the lines inside the file have the same size, you can get the exact number of lines by dividing the size of the file by the size of the line, both in bytes. You can do it almost instantaneously in a single job. If you have the mean size and don't care exactly for the the line count, but want an estimation, you can do this same operation and get a satisfactory result much faster than the exact operation.

YouTube URL in Video Tag

Try this solution for the perfectly working

new YouTubeToHtml5();

Using jQuery to test if an input has focus

April 2015 Update

Since this question has been around a while, and some new conventions have come into play, I feel that I should mention the .live method has been depreciated.

In its place, the .on method has now been introduced.

Their documentation is quite useful in explaining how it works;

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live().

So, in order for you to target the 'input focused' event, you can use this in a script. Something like:

$('input').on("focus", function(){
   //do some stuff
});

This is quite robust and even allows you to use the TAB key as well.

What does 'git remote add upstream' help achieve?

The wiki is talking from a forked repo point of view. You have access to pull and push from origin, which will be your fork of the main diaspora repo. To pull in changes from this main repo, you add a remote, "upstream" in your local repo, pointing to this original and pull from it.

So "origin" is a clone of your fork repo, from which you push and pull. "Upstream" is a name for the main repo, from where you pull and keep a clone of your fork updated, but you don't have push access to it.

Command for restarting all running docker containers?

To start all the containers:

  docker restart $(docker ps -a -q)

Use sudo if you don't have permission to perform this:

sudo docker restart $(sudo docker ps -a -q)

How can I get Git to follow symlinks?

Use hard links instead. This differs from a soft (symbolic) link. All programs, including git will treat the file as a regular file. Note that the contents can be modified by changing either the source or the destination.

On macOS (before 10.13 High Sierra)

If you already have git and Xcode installed, install hardlink. It's a microscopic tool to create hard links.

To create the hard link, simply:

hln source destination

macOS High Sierra update

Does Apple File System support directory hard links?

Directory hard links are not supported by Apple File System. All directory hard links are converted to symbolic links or aliases when you convert from HFS+ to APFS volume formats on macOS.

From APFS FAQ on developer.apple.com

Follow https://github.com/selkhateeb/hardlink/issues/31 for future alternatives.

On Linux and other Unix flavors

The ln command can make hard links:

ln source destination

On Windows (Vista, 7, 8, …)

Use mklink to create a junction on Windows:

mklink /j "source" "destination"

How to get a list of user accounts using the command line in MySQL?

SELECT * FROM mysql.user;

It's a big table so you might want to be more selective on what fields you choose.

How to prove that a problem is NP complete?

First, you show that it lies in NP at all.

Then you find another problem that you already know is NP complete and show how you polynomially reduce NP Hard problem to your problem.

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

Which type of folder structure should be used with Angular 2?

I think structuring the project by functionalities is a practical method. It makes the project scalable and maintainable easily. And it makes each part of the project working in a total autonomy. Let me know what you think about this structure below: ANGULAR TYPESCRIPT PROJECT STRUCTURE – ANGULAR 2

source : http://www.angulartypescript.com/angular-typescript-project-structure/

Get property value from C# dynamic object by string (reflection?)

Thought this might help someone in the future.

If you know the property name already, you can do something like the following:

[HttpPost]
[Route("myRoute")]
public object SomeApiControllerMethod([FromBody] dynamic args){
   var stringValue = args.MyPropertyName.ToString();
   //do something with the string value.  If this is an int, we can int.Parse it, or if it's a string, we can just use it directly.
   //some more code here....
   return stringValue;
}

How to check if smtp is working from commandline (Linux)

The only thing about using telnet to test postfix, or other SMTP, is that you have to know the commands and syntax. Instead, just use swaks :)

thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 4 messages
>    1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
? q
Held 4 messages in /home/thufir/Maildir
thufir@dur:~$ 
thufir@dur:~$ swaks --to [email protected]
=== Trying dur.bounceme.net:25...
=== Connected to dur.bounceme.net.
<-  220 dur.bounceme.net ESMTP Postfix (Ubuntu)
 -> EHLO dur.bounceme.net
<-  250-dur.bounceme.net
<-  250-PIPELINING
<-  250-SIZE 10240000
<-  250-VRFY
<-  250-ETRN
<-  250-STARTTLS
<-  250-ENHANCEDSTATUSCODES
<-  250-8BITMIME
<-  250 DSN
 -> MAIL FROM:<[email protected]>
<-  250 2.1.0 Ok
 -> RCPT TO:<[email protected]>
<-  250 2.1.5 Ok
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Mon, 30 Dec 2013 14:33:17 -0800
 -> To: [email protected]
 -> From: [email protected]
 -> Subject: test Mon, 30 Dec 2013 14:33:17 -0800
 -> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 -> 
 -> This is a test mailing
 -> 
 -> .
<-  250 2.0.0 Ok: queued as 52D162C3EFF
 -> QUIT
<-  221 2.0.0 Bye
=== Connection closed with remote host.
thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 5 messages 1 new
     1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
>N   5 [email protected]                   15/581   test Mon, 30 Dec 2013 14:33:17 -0800
? 5
Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from dur.bounceme.net (localhost [127.0.0.1])
    by dur.bounceme.net (Postfix) with ESMTP id 52D162C3EFF
    for <[email protected]>; Mon, 30 Dec 2013 14:33:17 -0800 (PST)
Date: Mon, 30 Dec 2013 14:33:17 -0800
To: [email protected]
From: [email protected]
Subject: test Mon, 30 Dec 2013 14:33:17 -0800
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Message-Id: <[email protected]>

This is a test mailing

New mail has arrived.
? q
Held 5 messages in /home/thufir/Maildir
thufir@dur:~$ 

It's just one easy command.

'NoneType' object is not subscriptable?

The [0] needs to be inside the ).

Set position / size of UI element as percentage of screen size

Take a look at this:

http://developer.android.com/reference/android/util/DisplayMetrics.html

You can get the heigth of the screen and it's simple math to calculate 68 percent of the screen.

How to run php files on my computer

I just put the content in the question in a file called test.php and ran php test.php. (In the folder where the test.php is.)

$ php foo.php                                                                                                                                                                                                                                                                                                                                    
15

"Failed to install the following Android SDK packages as some licences have not been accepted" error

In my case updating buildToolsVersion in app level build.gradle worked perfectly. If you don't know which to use you can create new project and copy buildToolsVersion from that into existing one.

C#: Assign same value to multiple variables in single statement

Your example would be:

int num1 = 1;
int num2 = 1;

num1 = num2 = 5;

Git Symlinks in Windows

I was asking this exact same question a while back (not here, just in general) and ended up coming up with a very similar solution to OP's proposition. First I'll provide direct answers to questions 1 2 & 3, and then I'll post the solution I ended up using.

  1. There are indeed a few downsides to the proposed solution, mainly regarding an increased potential for repository pollution, or accidentally adding duplicate files while they're in their "Windows symlink" states. (More on this under "limitations" below.)
  2. Yes, a post-checkout script is implementable! Maybe not as a literal post-git checkout step, but the solution below has met my needs well enough that a literal post-checkout script wasn't necessary.
  3. Yes!

The Solution:

Our developers are in much the same situation as OP's: a mixture of Windows and Unix-like hosts, repositories and submodules with many git symlinks, and no native support (yet) in the release version of MsysGit for intelligently handling these symlinks on Windows hosts.

Thanks to Josh Lee for pointing out the fact that git commits symlinks with special filemode 120000. With this information it's possible to add a few git aliases that allow for the creation and manipulation of git symlinks on Windows hosts.

  1. Creating git symlinks on Windows

    git config --global alias.add-symlink '!'"$(cat <<'ETX'
    __git_add_symlink() {
      if [ $# -ne 2 ] || [ "$1" = "-h" ]; then
        printf '%b\n' \
            'usage: git add-symlink <source_file_or_dir> <target_symlink>\n' \
            'Create a symlink in a git repository on a Windows host.\n' \
            'Note: source MUST be a path relative to the location of target'
        [ "$1" = "-h" ] && return 0 || return 2
      fi
    
      source_file_or_dir=${1#./}
      source_file_or_dir=${source_file_or_dir%/}
    
      target_symlink=${2#./}
      target_symlink=${target_symlink%/}
      target_symlink="${GIT_PREFIX}${target_symlink}"
      target_symlink=${target_symlink%/.}
      : "${target_symlink:=.}"
    
      if [ -d "$target_symlink" ]; then
        target_symlink="${target_symlink%/}/${source_file_or_dir##*/}"
      fi
    
      case "$target_symlink" in
        (*/*) target_dir=${target_symlink%/*} ;;
        (*) target_dir=$GIT_PREFIX ;;
      esac
    
      target_dir=$(cd "$target_dir" && pwd)
    
      if [ ! -e "${target_dir}/${source_file_or_dir}" ]; then
        printf 'error: git-add-symlink: %s: No such file or directory\n' \
            "${target_dir}/${source_file_or_dir}" >&2
        printf '(Source MUST be a path relative to the location of target!)\n' >&2
        return 2
      fi
    
      git update-index --add --cacheinfo 120000 \
          "$(printf '%s' "$source_file_or_dir" | git hash-object -w --stdin)" \
          "${target_symlink}" \
        && git checkout -- "$target_symlink" \
        && printf '%s -> %s\n' "${target_symlink#$GIT_PREFIX}" "$source_file_or_dir" \
        || return $?
    }
    __git_add_symlink
    ETX
    )"
    

    Usage: git add-symlink <source_file_or_dir> <target_symlink>, where the argument corresponding to the source file or directory must take the form of a path relative to the target symlink. You can use this alias the same way you would normally use ln.

    E.g., the repository tree:

    dir/
    dir/foo/
    dir/foo/bar/
    dir/foo/bar/baz      (file containing "I am baz")
    dir/foo/bar/lnk_file (symlink to ../../../file)
    file                 (file containing "I am file")
    lnk_bar              (symlink to dir/foo/bar/)
    

    Can be created on Windows as follows:

    git init
    mkdir -p dir/foo/bar/
    echo "I am baz" > dir/foo/bar/baz
    echo "I am file" > file
    git add -A
    git commit -m "Add files"
    git add-symlink ../../../file dir/foo/bar/lnk_file
    git add-symlink dir/foo/bar/ lnk_bar
    git commit -m "Add symlinks"
    
  2. Replacing git symlinks with NTFS hardlinks+junctions

    git config --global alias.rm-symlinks '!'"$(cat <<'ETX'
    __git_rm_symlinks() {
      case "$1" in (-h)
        printf 'usage: git rm-symlinks [symlink] [symlink] [...]\n'
        return 0
      esac
      ppid=$$
      case $# in
        (0) git ls-files -s | grep -E '^120000' | cut -f2 ;;
        (*) printf '%s\n' "$@" ;;
      esac | while IFS= read -r symlink; do
        case "$symlink" in
          (*/*) symdir=${symlink%/*} ;;
          (*) symdir=. ;;
        esac
    
        git checkout -- "$symlink"
        src="${symdir}/$(cat "$symlink")"
    
        posix_to_dos_sed='s_^/\([A-Za-z]\)_\1:_;s_/_\\\\_g'
        doslnk=$(printf '%s\n' "$symlink" | sed "$posix_to_dos_sed")
        dossrc=$(printf '%s\n' "$src" | sed "$posix_to_dos_sed")
    
        if [ -f "$src" ]; then
          rm -f "$symlink"
          cmd //C mklink //H "$doslnk" "$dossrc"
        elif [ -d "$src" ]; then
          rm -f "$symlink"
          cmd //C mklink //J "$doslnk" "$dossrc"
        else
          printf 'error: git-rm-symlink: Not a valid source\n' >&2
          printf '%s =/=> %s  (%s =/=> %s)...\n' \
              "$symlink" "$src" "$doslnk" "$dossrc" >&2
          false
        fi || printf 'ESC[%d]: %d\n' "$ppid" "$?"
    
        git update-index --assume-unchanged "$symlink"
      done | awk '
        BEGIN { status_code = 0 }
        /^ESC\['"$ppid"'\]: / { status_code = $2 ; next }
        { print }
        END { exit status_code }
      '
    }
    __git_rm_symlinks
    ETX
    )"
    
    git config --global alias.rm-symlink '!git rm-symlinks'  # for back-compat.
    

    Usage:

    git rm-symlinks [symlink] [symlink] [...]
    

    This alias can remove git symlinks one-by-one or all-at-once in one fell swoop. Symlinks will be replaced with NTFS hardlinks (in the case of files) or NTFS junctions (in the case of directories). The benefit of using hardlinks+junctions over "true" NTFS symlinks is that elevated UAC permissions are not required in order for them to be created.

    To remove symlinks from submodules, just use git's built-in support for iterating over them:

    git submodule foreach --recursive git rm-symlinks
    

    But, for every drastic action like this, a reversal is nice to have...

  3. Restoring git symlinks on Windows

    git config --global alias.checkout-symlinks '!'"$(cat <<'ETX'
    __git_checkout_symlinks() {
      case "$1" in (-h)
        printf 'usage: git checkout-symlinks [symlink] [symlink] [...]\n'
        return 0
      esac
      case $# in
        (0) git ls-files -s | grep -E '^120000' | cut -f2 ;;
        (*) printf '%s\n' "$@" ;;
      esac | while IFS= read -r symlink; do
        git update-index --no-assume-unchanged "$symlink"
        rmdir "$symlink" >/dev/null 2>&1
        git checkout -- "$symlink"
        printf 'Restored git symlink: %s -> %s\n' "$symlink" "$(cat "$symlink")"
      done
    }
    __git_checkout_symlinks
    ETX
    )"
    
    git config --global alias.co-symlinks '!git checkout-symlinks'
    

    Usage: git checkout-symlinks [symlink] [symlink] [...], which undoes git rm-symlinks, effectively restoring the repository to its natural state (except for your changes, which should stay intact).

    And for submodules:

    git submodule foreach --recursive git checkout-symlinks
    
  4. Limitations:

    • Directories/files/symlinks with spaces in their paths should work. But tabs or newlines? YMMV… (By this I mean: don’t do that, because it will not work.)

    • If yourself or others forget to git checkout-symlinks before doing something with potentially wide-sweeping consequences like git add -A, the local repository could end up in a polluted state.

      Using our "example repo" from before:

      echo "I am nuthafile" > dir/foo/bar/nuthafile
      echo "Updating file" >> file
      git add -A
      git status
      # On branch master
      # Changes to be committed:
      #   (use "git reset HEAD <file>..." to unstage)
      #
      #       new file:   dir/foo/bar/nuthafile
      #       modified:   file
      #       deleted:    lnk_bar           # POLLUTION
      #       new file:   lnk_bar/baz       # POLLUTION
      #       new file:   lnk_bar/lnk_file  # POLLUTION
      #       new file:   lnk_bar/nuthafile # POLLUTION
      #
      

      Whoops...

      For this reason, it's nice to include these aliases as steps to perform for Windows users before-and-after building a project, rather than after checkout or before pushing. But each situation is different. These aliases have been useful enough for me that a true post-checkout solution hasn't been necessary.

Hope that helps!

References:

http://git-scm.com/book/en/Git-Internals-Git-Objects

http://technet.microsoft.com/en-us/library/cc753194

Last Update: 2019-03-13

  • POSIX compliance (well, except for those mklink calls, of course) — no more Bashisms!
  • Directories and files with spaces in them are supported.
  • Zero and non-zero exit status codes (for communicating success/failure of the requested command, respectively) are now properly preserved/returned.
  • The add-symlink alias now works more like ln(1) and can be used from any directory in the repository, not just the repository’s root directory.
  • The rm-symlink alias (singular) has been superseded by the rm-symlinks alias (plural), which now accepts multiple arguments (or no arguments at all, which finds all of the symlinks throughout the repository, as before) for selectively transforming git symlinks into NTFS hardlinks+junctions.
  • The checkout-symlinks alias has also been updated to accept multiple arguments (or none at all, == everything) for selective reversal of the aforementioned transformations.

Final Note: While I did test loading and running these aliases using Bash 3.2 (and even 3.1) for those who may still be stuck on such ancient versions for any number of reasons, be aware that versions as old as these are notorious for their parser bugs. If you experience issues while trying to install any of these aliases, the first thing you should look into is upgrading your shell (for Bash, check the version with CTRL+X, CTRL+V). Alternatively, if you’re trying to install them by pasting them into your terminal emulator, you may have more luck pasting them into a file and sourcing it instead, e.g. as

. ./git-win-symlinks.sh

Good luck!

check for null date in CASE statement, where have I gone wrong?

select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
  'Awaiting'
Else
  'Approved'
END AS StartDateStatus
From MyTable

Including external HTML file to another HTML file

You're looking for the <iframe> tag, or, better yet, a server-side templating language.

How to launch an application from a browser?

The correct method is to register your custom URL Protocol in windows registry as follows:

[HKEY_CLASSES_ROOT\customurl]
@="Description here"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\customurl\shell]

[HKEY_CLASSES_ROOT\customurl\shell\open]

[HKEY_CLASSES_ROOT\customurl\shell\open\command]
@="\"C:\\Path To Your EXE\\ExeName.exe\" \"%1\""

Once the above keys and values are added, from the web page, just call "customurl:\\parameter1=xxx&parameter2=xxx" . You will receive the entire url as the argument in exe, which you need to process inside your exe. Change 'customurl' with the text of your choice.

C# DateTime to "YYYYMMDDHHMMSS" format

If you use ReSharper, get help with ':' (see image)

Intellisense

read complete file without using loop in java

If the file is small, you can read the whole data once:

File file = new File("a.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();

String str = new String(data, "UTF-8");

Send cookies with curl

Very annoying, no cookie file exmpale on the official website https://ec.haxx.se/http/http-cookies.

Finnaly, I find it does not work, if your file content is just copyied like this

foo1=bar;foo2=bar2

I gusess the format must looks the style said by @Agustí Sánchez . You can test it by -c to create a cookie file on a website.

So try this way, it works

curl -H "Cookie:`cat ./my.cookie`"   http://xxxx.com

You can just copy the cookie from chrome console network tab.

Jupyter notebook not running code. Stuck on In [*]

I have uninstalled jupyter, notebook and ipython, and installed jupyterlab. It is working for now (with just a few libraries installed and Python 3.6.8.


Something to discard: Uninstalling Python 3.7 completely with his libraries and reverting to 3.6 doesn't fix it, although it improves it, it works intermittently now (but once sth doesn't work properly, things start to get worse and worse, so I did the above).

$.focus() not working

I also had this problem. The solution that worked in my case was using the tabindex property on the HTML element.

I was using ng-repeat for some li elements inside a list and I was not able to bring focus to the first li using .focus(), so I simply added the tabindex attribute to each li during the loop.

so now <li ng-repeat="user in users track by $index" tabindex="{{$index+1}}"></li>

That +1 was index starts from 0. Also make sure that the element is present in DOM before calling the .focus() function

I hope this helps.

Delete all duplicate rows Excel vba

The duplicate values in any column can be deleted with a simple for loop.

Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub

connect local repo with remote repo

I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.

C - casting int to char and append char to char

int myInt = 65;

char myChar = (char)myInt;  // myChar should now be the letter A

char[20] myString = {0}; // make an empty string.

myString[0] = myChar;
myString[1] = myChar; // Now myString is "AA"

This should all be found in any intro to C book, or by some basic online searching.

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the formatter specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s).

Refresh image with a new one at the same url

Simple solution: add this header to the response:

Cache-control: no-store

Why this works is clearly explained at this authoritative page: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

It also explains why no-cache does not work.

Other answers do not work because:

Caching.delete is about a new cache that you may create for off-line work, see: https://web.dev/cache-api-quick-guide/

Fragments using a # in the URL do not work because the # tells the browser to not send a request to the server.

A cache-buster with a random part added to the url works, but will also fill the browser cache. In my app, I wanted to download a 5 MB picture every few seconds from a web cam. It will take just an hour or less to completely freeze your pc. I still don't know why the browser cache is not limited to a reasonable max, but this is definitely a disadvantage.

How to change the style of a DatePicker in android?

Try this. It's the easiest & most efficient way

<style name="datepicker" parent="Theme.AppCompat.Light.Dialog">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/primary</item>
</style>

What does "Git push non-fast-forward updates were rejected" mean?

you might want to use force with push operation in this case

git push origin master --force

Increasing nesting function calls limit

Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.

I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.

How to write data with FileOutputStream without losing old data?

Use the constructor for appending material to the file:

FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

So to append to a file say "abc.txt" use

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);

Search for exact match of string in excel row using VBA Macro

Use worksheet.find (worksheet is your worksheet) and use the row-range for its range-object. You can get the rangeobject like: worksheet.rows(rowIndex) as example

Then give find the required parameters it should find it for you fine. If I recall correctly, find returns the first match per default. I have no Excel at hand, so you have to look up find for yourself, sorry

I would advise against using a for-loop it is more fragile and ages slower than find.

Excel tab sheet names vs. Visual Basic sheet names

This will change all worksheet objects' names (from the perspective of the VBA editor) to match that of their sheet names (from the perspective of Excel):

Sub ZZ_Reset_Sheet_CodeNames()
'Changes the internal object name (codename) of each sheet to it's conventional name (based on it's sheet name)

    Dim varItem As Variant

    For Each varItem In ThisWorkbook.VBProject.VBComponents
        'Type 100 is a worksheet
        If varItem.Type = 100 And varItem.Name <> "ThisWorkbook" Then
            varItem.Name = varItem.Properties("Name").Value
        End If
    Next
End Sub

It is important to note that the object name (codename) "(Name)" is being overridden by the property name "Name", and so it must be referenced as a sub-property.

When to use SELECT ... FOR UPDATE?

The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE.

However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE explicitly.


To solve this problem, Thread 1 should SELECT id FROM rooms FOR UPDATE, thereby preventing Thread 2 from deleting from rooms until Thread 1 is done. Is that correct?

This depends on the concurrency control your database system is using.

  • MyISAM in MySQL (and several other old systems) does lock the whole table for the duration of a query.

  • In SQL Server, SELECT queries place shared locks on the records / pages / tables they have examined, while DML queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT or DELETE query will lock until another session commits.

  • In databases which use MVCC (like Oracle, PostgreSQL, MySQL with InnoDB), a DML query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE would come handy: it would lock either SELECT or the DELETE query until another session commits, just as SQL Server does.

When should one use REPEATABLE_READ transaction isolation versus READ_COMMITTED with SELECT ... FOR UPDATE?

Generally, REPEATABLE READ does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)

  • In Oracle and earlier PostgreSQL versions, REPEATABLE READ is actually a synonym for SERIALIZABLE. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1 query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE

  • In InnoDB, REPEATABLE READ and SERIALIZABLE are different things: readers in SERIALIZABLE mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML on them. So you don't need a SELECT FOR UPDATE in serializable mode, but do need them in REPEATABLE READ or READ COMMITED.

Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC or otherwise).

When I say "you don't need SELECT FOR UPDATE" I really should have added "because of side effects of certain database engine implementation".

Border Radius of Table is not working

This is my solution using the wrapper, just removing border-collapse might not be helpful always, because you might want to have borders.

_x000D_
_x000D_
.wrapper {_x000D_
  overflow: auto;_x000D_
  border-radius: 6px;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-spacing: 0;_x000D_
  border-collapse: collapse;_x000D_
  border-style: hidden;_x000D_
_x000D_
  width:100%;_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
th, td {_x000D_
  padding: 10px;_x000D_
  border: 1px solid #CCCCCC;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>Column 1</th>_x000D_
        <th>Column 2</th>_x000D_
        <th>Column 3</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>Foo Bar boo</td>_x000D_
        <td>Lipsum</td>_x000D_
        <td>Beehuum Doh</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Dolor sit</td>_x000D_
        <td>ahmad</td>_x000D_
        <td>Polymorphism</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Kerbalium</td>_x000D_
        <td>Caton, gookame kyak</td>_x000D_
        <td>Corona Premium Beer</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

This article helped: https://css-tricks.com/table-borders-inside/

Determine which MySQL configuration file is being used

For people running windows server with mysql as a service, an easy way to find out what config file you are running is to open up the services control panel, find your mysql service (in my case 'MYSQL56'), right click and click properties. Then from here you can check the "Path to Executable" which should have a defaults-file switch which points to where your config file is.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

Make sure the name of the class created in the package is something like somethingTest.java Maven only picks the java files ending with Test notation.

I was getting the same error and resolving the names of all my classes by adding 'Test' at the end made it work.

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

What is the standard exception to throw in Java for not supported/implemented operations?

If you create a new (not yet implemented) function in NetBeans, then it generates a method body with the following statement:

throw new java.lang.UnsupportedOperationException("Not supported yet.");

Therefore, I recommend to use the UnsupportedOperationException.

How to get the number of days of difference between two dates on mysql?

SELECT md.*, DATEDIFF(md.end_date, md.start_date) AS days FROM  membership_dates md

output::

id  entity_id    start_date            end_date             days

1   1236      2018-01-16 00:00:00     2018-08-31 00:00:00    227
2   2876      2015-06-26 00:00:00     2019-06-30 00:00:00   1465
3   3880      1990-06-05 00:00:00     2018-07-04 00:00:00   10256
4   3882      1993-07-05 00:00:00     2018-07-04 00:00:00   9130

hope it helps someone in future

Slidedown and slideup layout with animation

I use these easy functions, it work like jquery slideUp slideDown, use it in an helper class, just pass your view :

public static void expand(final View v) {
    v.measure(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    final int targetHeight = v.getMeasuredHeight();

    // Older versions of android (pre API 21) cancel animations for views with a height of 0.
    v.getLayoutParams().height = 1;
    v.setVisibility(View.VISIBLE);
    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            v.getLayoutParams().height = interpolatedTime == 1
                    ? WindowManager.LayoutParams.WRAP_CONTENT
                    : (int)(targetHeight * interpolatedTime);
            v.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

public static void collapse(final View v) {
    final int initialHeight = v.getMeasuredHeight();

    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            if(interpolatedTime == 1){
                v.setVisibility(View.GONE);
            }else{
                v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
                v.requestLayout();
            }
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

How and when to use ‘async’ and ‘await’

Async & Await Simple Explanation

Simple Analogy

A person may wait for their morning train. This is all they are doing as this is their primary task that they are currently performing. (synchronous programming (what you normally do!))

Another person may await their morning train whilst they smoke a cigarette and then drink their coffee. (Asynchronous programming)

What is asynchronous programming?

Asynchronous programming is where a programmer will choose to run some of his code on a separate thread from the main thread of execution and then notify the main thread on it's completion.

What does the async keyword actually do?

Prefixing the async keyword to a method name like

async void DoSomething(){ . . .

allows the programmer to use the await keyword when calling asynchronous tasks. That's all it does.

Why is this important?

In a lot of software systems the main thread is reserved for operations specifically relating to the User Interface. If I am running a very complex recursive algorithm that takes 5 seconds to complete on my computer, but I am running this on the Main Thread (UI thread) When the user tries to click on anything on my application, it will appear to be frozen as my main thread has queued and is currently processing far too many operations. As a result the main thread cannot process the mouse click to run the method from the button click.

When do you use Async and Await?

Use the asynchronous keywords ideally when you are doing anything that doesn't involve the user interface.

So lets say you're writing a program that allows the user to sketch on their mobile phone but every 5 seconds it is going to be checking the weather on the internet.

We should be awaiting the call the polling calls every 5 seconds to the network to get the weather as the user of the application needs to keep interacting with the mobile touch screen to draw pretty pictures.

How do you use Async and Await

Following on from the example above, here is some pseudo code of how to write it:

    //ASYNCHRONOUS
    //this is called using the await keyword every 5 seconds from a polling timer or something.

    async Task CheckWeather()
    {
        var weather = await GetWeather();
        //do something with the weather now you have it
    }

    async Task<WeatherResult> GetWeather()
    {

        var weatherJson = await CallToNetworkAddressToGetWeather();
        return deserializeJson<weatherJson>(weatherJson);
    }

    //SYNCHRONOUS
    //This method is called whenever the screen is pressed
    void ScreenPressed()
    {
        DrawSketchOnScreen();
    }

Additional Notes - Update

I forgot to mention in my original notes that in C# you can only await methods that are wrapped in Tasks. for example you may await this method:

// awaiting this will return a string.
// calling this without await (synchronously) will result in a Task<string> object.
async Task<string> FetchHelloWorld() {..

You cannot await methods that are not tasks like this:

async string FetchHelloWorld() {..

Feel free to review the source code for the Task class here.

How to set time zone of a java.util.Date?

java.util.Calendar is the usual way to handle time zones using just JDK classes. Apache Commons has some further alternatives/utilities that may be helpful. Edit Spong's note reminded me that I've heard really good things about Joda-Time (though I haven't used it myself).

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

Type safety: Unchecked cast

Well, first of all, you're wasting memory with the new HashMap creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:

private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");

Secondly, the compiler is complaining that you cast the object to a HashMap without checking if it is a HashMap. But, even if you were to do:

if(getApplicationContext().getBean("someMap") instanceof HashMap) {
    private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
}

You would probably still get this warning. The problem is, getBean returns Object, so it is unknown what the type is. Converting it to HashMap directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a HashMap<String, String>.

HashMaps are really maps that take an object as a key and have an object as a value, HashMap<Object, Object> if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a HashMap<String, String> because you could have HashMap<Date, Calendar> because the non-generic representation that is returned can have any objects.

If the code compiles, and you can execute String value = map.get("thisString"); without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a ClassCastException at runtime, because the generics cannot block this from happening in this case.

Adding 1 hour to time variable

for this problem please follow bellow code:

$time= '10:09';
$new_time=date('H:i',strtotime($time.'+ 1 hour'));
echo $new_time;`
// now output will be: 11:09

Any reason not to use '+' to concatenate two strings?

When working with multiple people, it's sometimes difficult to know exactly what's happening. Using a format string instead of concatenation can avoid one particular annoyance that's happened a whole ton of times to us:

Say, a function requires an argument, and you write it expecting to get a string:

In [1]: def foo(zeta):
   ...:     print 'bar: ' + zeta

In [2]: foo('bang')
bar: bang

So, this function may be used pretty often throughout the code. Your coworkers may know exactly what it does, but not necessarily be fully up-to-speed on the internals, and may not know that the function expects a string. And so they may end up with this:

In [3]: foo(23)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

/home/izkata/<ipython console> in foo(zeta)

TypeError: cannot concatenate 'str' and 'int' objects

There would be no problem if you just used a format string:

In [1]: def foo(zeta):
   ...:     print 'bar: %s' % zeta
   ...:     
   ...:     

In [2]: foo('bang')
bar: bang

In [3]: foo(23)
bar: 23

The same is true for all types of objects that define __str__, which may be passed in as well:

In [1]: from datetime import date

In [2]: zeta = date(2012, 4, 15)

In [3]: print 'bar: ' + zeta
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

TypeError: cannot concatenate 'str' and 'datetime.date' objects

In [4]: print 'bar: %s' % zeta
bar: 2012-04-15

So yes: If you can use a format string do it and take advantage of what Python has to offer.

Does C# have extension properties?

Because I recently needed this, I looked at the source of the answer in:

c# extend class by adding properties

and created a more dynamic version:

public static class ObjectExtenders
{
    static readonly ConditionalWeakTable<object, List<stringObject>> Flags = new ConditionalWeakTable<object, List<stringObject>>();

    public static string GetFlags(this object objectItem, string key)
    {
        return Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value;
    }

    public static void SetFlags(this object objectItem, string key, string value)
    {
        if (Flags.GetOrCreateValue(objectItem).Any(x => x.Key == key))
        {
            Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value = value;
        }
        else
        {
            Flags.GetOrCreateValue(objectItem).Add(new stringObject()
            {
                Key = key,
                Value = value
            });
        }
    }

    class stringObject
    {
        public string Key;
        public string Value;
    }
}

It can probably be improved a lot (naming, dynamic instead of string), I currently use this in CF 3.5 together with a hacky ConditionalWeakTable (https://gist.github.com/Jan-WillemdeBruyn/db79dd6fdef7b9845e217958db98c4d4)

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

For anyone looking for a UI option using IIS Manager.

  1. Open the Website in IIS Manager
  2. Go To Request Filtering and open the Request Filtering Window.
  3. Go to Verbs Tab and Add HTTP Verbs to "Allow Verb..." or "Deny Verb...". This allow to add the HTTP Verbs in the "Deny Verb.." Collection.

Request Filtering Window in IIS Manager Request Filtering Window in IIS Manager

Add Verb... or Deny Verb... enter image description here

Import an existing git project into GitLab?

Moving a project from GitHub to GitLab including issues, pull requests Wiki, Milestones, Labels, Release notes and comments

There is a thorough instruction on GitLab Docs:

https://docs.gitlab.com/ee/user/project/import/github.html

tl;dr

  • Ensure that any GitHub users who you want to map to GitLab users have either:

    • A GitLab account that has logged in using the GitHub icon - or -
    • A GitLab account with an email address that matches the public email address of the GitHub user
  • From the top navigation bar, click + and select New project.

  • Select the Import project tab and then select GitHub.
  • Select the first button to List your GitHub repositories. You are redirected to a page on github.com to authorize the GitLab application.
  • Click Authorize gitlabhq. You are redirected back to GitLab's Import page and all of your GitHub repositories are listed.
  • Continue on to selecting which repositories to import.

But Please read the GitLab Docs page for details and hooks!

(it's not much)

Why is Git better than Subversion?

A few answers have alluded to these, but I want to make 2 points explicit:

1) The ability to do selective commits (for example, git add --patch). If your working directory contains multiple changes that are not part of the same logical change, Git makes it very easy to make a commit that includes only a portion of the changes. With Subversion, it is difficult.

2) The ability to commit without making the change public. In Subversion, any commit is immediately public, and thus irrevocable. This greatly limits the ability of the developer to "commit early, commit often".

Git is more than just a VCS; it's also a tool for developing patches. Subversion is merely a VCS.

afxwin.h file is missing in VC++ Express Edition

I encountered the same problem. The easiest thing is to install the free Visual Studio Community 2015 as answered in this question Is MFC only available with Visual Studio, and not Visual C++ Express?

Auto-Submit Form using JavaScript

This solution worked for me:

<body onload="setTimeout(function() { document.myform.submit() }, 5000)">
   <form action=TripRecorder name="myform">
      <textarea id="result1"  name="res1" value="str1" cols="20" rows="1" ></textarea> <br> <br/>
      <textarea id="result2" name="res2" value="str2" cols="20" rows="1" ></textarea>
   </form>
</body>

Is there a command like "watch" or "inotifywait" on the Mac?

Here's a simple single line alternative for users who don't have the watch command who want to execute a command every 3 seconds:

while :; do your-command; sleep 3; done

It's an infinite loop that is basically the same as doing the following:

watch -n3 your-command

How to avoid using Select in Excel VBA

Please note that in the following I'm comparing the Select approach (the one that the OP wants to avoid), with the Range approach (and this is the answer to the question). So don't stop reading when you see the first Select.

It really depends on what you are trying to do. Anyway, a simple example could be useful. Let's suppose that you want to set the value of the active cell to "foo". Using ActiveCell you would write something like this:

Sub Macro1()
    ActiveCell.Value = "foo"
End Sub

If you want to use it for a cell that is not the active one, for instance for "B2", you should select it first, like this:

Sub Macro2()
    Range("B2").Select
    Macro1
End Sub

Using Ranges you can write a more generic macro that can be used to set the value of any cell you want to whatever you want:

Sub SetValue(cellAddress As String, aVal As Variant)
    Range(cellAddress).Value = aVal
End Sub

Then you can rewrite Macro2 as:

Sub Macro2()
    SetCellValue "B2", "foo"
End Sub

And Macro1 as:

Sub Macro1()
    SetValue ActiveCell.Address, "foo"
End Sub

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

How to add a Hint in spinner in XML

For Kotlin !!

Custom Array adapter to hide the last item of the spinner

 import android.content.Context
 import android.widget.ArrayAdapter
 import android.widget.Spinner

 class HintAdapter<T>(context: Context, resource: Int, objects: Array<T>) :
    ArrayAdapter<T>(context, resource, objects) {

    override fun getCount(): Int {
        val count = super.getCount()
        // The last item will be the hint.
        return if (count > 0) count - 1 else count
    }
}

Spinner Extension function to set hint on spinner

fun Spinner.addHintWithArray(context: Context, stringArrayResId: Int) {
    val hintAdapter =
        HintAdapter<String>(
            context,
            android.R.layout.simple_spinner_dropdown_item,
            context.resources.getStringArray(stringArrayResId)
        )
    hintAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    adapter = hintAdapter
    setSelection(hintAdapter.count)
}

How to use: add the extension by passing context and array on Spinner

spinnerMonth.addHintWithArray(context, R.array.months)

Note: The hint should be the last item of your string array

<string-array name="months">
    <item>Jan</item>
    <item>Feb</item>
    <item>Mar</item>
    <item>Apr</item>
    <item>May</item>
    <item>Months</item>
</string-array>

How to use the IEqualityComparer

Just code, with implementation of GetHashCode and NULL validation:

public class Class_reglementComparer : IEqualityComparer<Class_reglement>
{
    public bool Equals(Class_reglement x, Class_reglement y)
    {
        if (x is null || y is null))
            return false;

        return x.Numf == y.Numf;
    }

    public int GetHashCode(Class_reglement product)
    {
        //Check whether the object is null 
        if (product is null) return 0;

        //Get hash code for the Numf field if it is not null. 
        int hashNumf = product.hashNumf == null ? 0 : product.hashNumf.GetHashCode();

        return hashNumf;
    }
}

Example: list of Class_reglement distinct by Numf

List<Class_reglement> items = items.Distinct(new Class_reglementComparer());

Android global variable

Easy!!!!

Those variable you wanna access as global variable, you can declare them as static variables. And now, you can access those variables by using

classname.variablename;

public class MyProperties {
private static MyProperties mInstance= null;

static int someValueIWantToKeep;

protected MyProperties(){}

public static synchronized MyProperties getInstance(){
    if(null == mInstance){
        mInstance = new MyProperties();
    }
    return mInstance;
}

}

MyProperites.someValueIWantToKeep;

Thats It! ;)

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

Somewhere, you need to tell Apache that people are allowed to see contents of this directory.

<Directory "F:/bar/public">
    Order Allow,Deny
    Allow from All
    # Any other directory-specific stuff
</Directory>

More info

Vuex - passing multiple parameters to mutation

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

Setting up Action

instead of

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

do

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

Calling (dispatching) Action

instead of

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

do

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

hope this gonna help

when exactly are we supposed to use "public static final String"?

  1. Static means..You can use it without instantiate of the class or using any object.
  2. final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:

      public class StringTest { 
               static final String str = "Hello"; 
      public static void main(String args[]) { 
               // str = "world"; // gives error 
               System.out.println(str); // called without the help of an object                       
               System.out.println(StringTest.str);// called with class name  
                 } 
             } 
    

Thanks

Are there any free Xml Diff/Merge tools available?

While this is not a GUI tool, my quick tests indicated that diffxml has some promise. The author appears to have thought about the complexities of representing diffs for nested elements in a standardized way (his DUL - Delta Update Language specification).

Installing and running his tools, I can say that the raw text output is quite clear and concise. It doesn't offer the same degree of immediate apprehension as a GUI tool, but given that the output is standardized as DUL, perhaps you would be able to take that and build a tool to generate a visual representation. I'd certainly love to see one.

The author's "links" section does reference a few other XML differencing tools, but as you mentioned in your post, they're all proprietary.

How to check if any Checkbox is checked in Angular

You can do something like:

function ChckbxsCtrl($scope, $filter) {
    $scope.chkbxs = [{
        label: "Led Zeppelin",
        val: false
    }, {
        label: "Electric Light Orchestra",
        val: false
    }, {
        label: "Mark Almond",
        val: false
    }];

    $scope.$watch("chkbxs", function(n, o) {
        var trues = $filter("filter")(n, {
            val: true
        });
        $scope.flag = trues.length;
    }, true);
}

And a template:

<div ng-controller="ChckbxsCtrl">
    <div ng-repeat="chk in chkbxs">
        <input type="checkbox" ng-model="chk.val" />
        <label>{{chk.label}}</label>
    </div>
    <div ng-show="flag">I'm ON when band choosed</div>
</div>

Working: http://jsfiddle.net/cherniv/JBwmA/

UPDATE: Or you can go little bit different way , without using $scope's $watch() method, like:

$scope.bandChoosed = function() {
    var trues = $filter("filter")($scope.chkbxs, {
        val: true
    });
    return trues.length;
}

And in a template do:

<div ng-show="bandChoosed()">I'm ON when band choosed</div>

Fiddle: http://jsfiddle.net/uzs4sgnp/

How can I create a keystore?

I followed this guide to create the debug keystore.

The command is:

keytool -genkeypair -alias androiddebugkey -keypass android -keystore debug.keystore -storepass android -dname "CN=Android Debug,O=Android,C=US" -validity 9999

How to both read and write a file in C#

you can try this:"Filename.txt" file will be created automatically in the bin->debug folder everytime you run this code or you can specify path of the file like: @"C:/...". you can check ëxistance of "Hello" by going to the bin -->debug folder

P.S dont forget to add Console.Readline() after this code snippet else console will not appear.

TextWriter tw = new StreamWriter("filename.txt");
        String text = "Hello";
        tw.WriteLine(text);
        tw.Close();

        TextReader tr = new StreamReader("filename.txt");
        Console.WriteLine(tr.ReadLine());
        tr.Close();