Programs & Examples On #Vbscript

VBScript (Visual Basic Scripting Edition) is an interpreted scripting language developed by Microsoft that is modeled on Visual Basic. VBScript is not the same thing as VBA or VB.NET. They are three different things, so use the correct tags.

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

How do I sort arrays using vbscript?

This is a vbscript implementation of merge sort.

'@Function Name: Sort
'@Author: Lewis Gordon
'@Creation Date: 4/26/12
'@Description: Sorts a given array either in ascending or descending order, as specified by the
'                order parameter.  This array is then returned at the end of the function.
'@Prerequisites:  An array must be allocated and have all its values inputted.
'@Parameters:
'    $ArrayToSort:  This is the array that is being sorted.
'    $Order:  This is the sorting order that the array will be sorted in.  This parameter 
'                can either    be "ASC" or "DESC" or ascending and descending, respectively.
'@Notes:  This uses merge sort under the hood.  Also, this function has only been tested for
'            integers and strings in the array.  However, this should work for any data type that
'            implements the greater than and less than comparators.  This function also requires
'            that the merge function is also present, as it is needed to complete the sort.
'@Examples:
'    Dim i
'    Dim TestArray(50)
'    Randomize
'    For i=0 to UBound(TestArray)
'        TestArray(i) = Int((100 - 0 + 1) * Rnd + 0)
'    Next
'    MsgBox Join(Sort(TestArray, "DESC"))
'
'@Return value:  This function returns a sorted array in the specified order.
'@Change History: None

'The merge function.
Public Function Merge(LeftArray, RightArray, Order)
    'Declared variables
    Dim FinalArray
    Dim FinalArraySize
    Dim i
    Dim LArrayPosition
    Dim RArrayPosition

    'Variable initialization
    LArrayPosition = 0
    RArrayPosition = 0

    'Calculate the expected size of the array based on the two smaller arrays.
    FinalArraySize = UBound(LeftArray) + UBound(RightArray) + 1
    ReDim FinalArray(FinalArraySize)

    'This should go until we need to exit the function.
    While True

        'If we are done with all the values in the left array.  Add the rest of the right array
        'to the final array.
        If LArrayPosition >= UBound(LeftArray)+1 Then
            For i=RArrayPosition To UBound(RightArray)
                FinalArray(LArrayPosition+i) = RightArray(i)
            Next
            Merge = FinalArray
            Exit Function

        'If we are done with all the values in the right array.  Add the rest of the left array
        'to the final array.
        ElseIf RArrayPosition >= UBound(RightArray)+1 Then
            For i=LArrayPosition To UBound(LeftArray)
                FinalArray(i+RArrayPosition) = LeftArray(i)
            Next
            Merge = FinalArray
            Exit Function

        'For descending, if the current value of the left array is greater than the right array 
        'then add it to the final array.  The position of the left array will then be incremented
        'by one.
        ElseIf LeftArray(LArrayPosition) > RightArray(RArrayPosition) And UCase(Order) = "DESC" Then
            FinalArray(LArrayPosition+RArrayPosition) = LeftArray(LArrayPosition)
            LArrayPosition = LArrayPosition + 1

        'For ascending, if the current value of the left array is less than the right array 
        'then add it to the final array.  The position of the left array will then be incremented
        'by one.
        ElseIf LeftArray(LArrayPosition) < RightArray(RArrayPosition) And UCase(Order) = "ASC" Then
            FinalArray(LArrayPosition+RArrayPosition) = LeftArray(LArrayPosition)
            LArrayPosition = LArrayPosition + 1

        'For anything else that wasn't covered, add the current value of the right array to the
        'final array.
        Else
            FinalArray(LArrayPosition+RArrayPosition) = RightArray(RArrayPosition)
            RArrayPosition = RArrayPosition + 1
        End If
    Wend
End Function

'The main sort function.
Public Function Sort(ArrayToSort, Order)
    'Variable declaration.
    Dim i
    Dim LeftArray
    Dim Modifier
    Dim RightArray

    'Check to make sure the order parameter is okay.
    If Not UCase(Order)="ASC" And Not UCase(Order)="DESC" Then
        Exit Function
    End If
    'If the array is a singleton or 0 then it is sorted.
    If UBound(ArrayToSort) <= 0 Then
        Sort = ArrayToSort
        Exit Function
    End If

    'Setting up the modifier to help us split the array effectively since the round
    'functions aren't helpful in VBScript.
    If UBound(ArrayToSort) Mod 2 = 0 Then
        Modifier = 1
    Else
        Modifier = 0
    End If

    'Setup the arrays to about half the size of the main array.
    ReDim LeftArray(Fix(UBound(ArrayToSort)/2))
    ReDim RightArray(Fix(UBound(ArrayToSort)/2)-Modifier)

    'Add the first half of the values to one array.
    For i=0 To UBound(LeftArray)
        LeftArray(i) = ArrayToSort(i)
    Next

    'Add the other half of the values to the other array.
    For i=0 To UBound(RightArray)
        RightArray(i) = ArrayToSort(i+Fix(UBound(ArrayToSort)/2)+1)
    Next

    'Merge the sorted arrays.
    Sort = Merge(Sort(LeftArray, Order), Sort(RightArray, Order), Order)
End Function

How do I rename a file using VBScript?

I see only one reason your code to not work, missed quote after file name string:

VBScript:

FSO.GetFile("MyFile.txt[missed_quote_here]).Name = "Hello.txt"

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

Getting current directory in VBScript

Your line

Directory = CurrentDirectory\attribute.exe

does not match any feature I have encountered in a vbscript instruction manual. The following works for me, tho not sure what/where you expect "attribute.exe" to reside.

dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run curDir & "\testme.bat", 1
set WinScriptHost = nothing

How to do multiple conditions for single If statement

Use the 'And' keyword for a logical and. Like this:

If Not ((filename = testFileName) And (fileName <> "")) Then

Try-Catch-End Try in VBScript doesn't seem to work

Sometimes, especially when you work with VB, you can miss obvious solutions. Like I was doing last 2 days.

the code, which generates error needs to be moved to a separate function. And in the beginning of the function you write On Error Resume Next. This is how an error can be "swallowed", without swallowing any other errors. Dividing code into small separate functions also improves readability, refactoring & makes it easier to add some new functionality.

What's the environment variable for the path to the desktop?

Not only would that not work for an International version of Windows, it would fail if the user had edited the Registry to make their Desktop folder reside somewhere else. You can query the Registry for the file location using the REG command:

REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop

To get this into a variable use something like this:

FOR /F "usebackq tokens=3 skip=4" %%i in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop`) DO SET DESKTOPDIR=%%i
FOR /F "usebackq delims=" %%i in (`ECHO %DESKTOPDIR%`) DO SET DESKTOPDIR=%%i
ECHO %DESKTOPDIR%

How can I convert a VBScript to an executable (EXE) file?

You can do this with PureBasic and MsScriptControl

All you need to do is pasting the MsScriptControl to the Purebasic editor and add something like this below

InitScriptControl()
SCtr_AddCode("MsgBox 1")

How to terminate a process in vbscript

The Win32_Process class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.

If this is not an option for you, you can try using the taskkill command:

Dim oShell : Set oShell = CreateObject("WScript.Shell")

' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000

' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True

vbscript output to console

You mean:

Wscript.Echo "Like this?"

If you run that under wscript.exe (the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe you'll get output in your console window.

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

I found the issue. This is a firewall message and an error was occurring in the VB script due to wrong data in database, but the error was not logged/caught properly.

How do I run a VBScript in 32-bit mode on a 64-bit machine?

follow http://support.microsoft.com/kb/896456

To start a 32-bit command prompt, follow these steps:

* Click Start, click Run, type %windir%\SysWoW64\cmd.exe, and then click OK.

Then type

cscript vbscriptfile.vbs

VBScript -- Using error handling

VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.

On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0

The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.

How to set delay in vbscript

Here is my solution. Worked with script, which was ran by third party program with no WScript declared and no import allowed.

Function MySleep(milliseconds)
  set WScriptShell = CreateObject("WScript.Shell")
  WScriptShell.Run "Sleep -m " & milliseconds, 0, true
end Function

Update
Looks like Microsoft removed Sleep.exe from win 8, so this doesn't work in win 8 unless you put Sleep.exe in folder defined in %path%.

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

When you run WScript.Shell it runs under the local system account, this account has full rights on the machine, but no rights in Active Directory.

http://support.microsoft.com/kb/278319

How do I get the Date & Time (VBS)

Here's various date and time information you can pull in vbscript running under Windows Script Host (WSH):

Now   = 2/29/2016 1:02:03 PM
Date  = 2/29/2016
Time  = 1:02:03 PM
Timer = 78826.31     ' seconds since midnight

FormatDateTime(Now)                = 2/29/2016 1:02:03 PM
FormatDateTime(Now, vbGeneralDate) = 2/29/2016 1:02:03 PM
FormatDateTime(Now, vbLongDate)    = Monday, February 29, 2016
FormatDateTime(Now, vbShortDate)   = 2/29/2016
FormatDateTime(Now, vbLongTime)    = 1:02:03 PM
FormatDateTime(Now, vbShortTime)   = 13:02

Year(Now)   = 2016
Month(Now)  = 2
Day(Now)    = 29
Hour(Now)   = 13
Minute(Now) = 2
Second(Now) = 3

Year(Date)   = 2016
Month(Date)  = 2
Day(Date)    = 29

Hour(Time)   = 13
Minute(Time) = 2
Second(Time) = 3

Function LPad (str, pad, length)
    LPad = String(length - Len(str), pad) & str
End Function

LPad(Month(Date), "0", 2)    = 02
LPad(Day(Date), "0", 2)      = 29
LPad(Hour(Time), "0", 2)     = 13
LPad(Minute(Time), "0", 2)   = 02
LPad(Second(Time), "0", 2)   = 03

Weekday(Now)                     = 2
WeekdayName(Weekday(Now), True)  = Mon
WeekdayName(Weekday(Now), False) = Monday
WeekdayName(Weekday(Now))        = Monday

MonthName(Month(Now), True)  = Feb
MonthName(Month(Now), False) = February
MonthName(Month(Now))        = February

Set os = GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@")
os.LocalDateTime = 20131204215346.562000-300
Left(os.LocalDateTime, 4)    = 2013 ' year
Mid(os.LocalDateTime, 5, 2)  = 12   ' month
Mid(os.LocalDateTime, 7, 2)  = 04   ' day
Mid(os.LocalDateTime, 9, 2)  = 21   ' hour
Mid(os.LocalDateTime, 11, 2) = 53   ' minute
Mid(os.LocalDateTime, 13, 2) = 46   ' second

Dim wmi : Set wmi = GetObject("winmgmts:root\cimv2")
Set timeZones = wmi.ExecQuery("SELECT Bias, Caption FROM Win32_TimeZone")
For Each tz In timeZones
    tz.Bias    = -300
    tz.Caption = (UTC-05:00) Eastern Time (US & Canada)
Next

Source

Reading and writing value from a textfile by using vbscript code

This script will read lines from large file and write to new small files. Will duplicate the header of the first line (Header) to all child files

Dim strLine
lCounter = 1
fCounter = 1
cPosition = 1
MaxLine = 1000
splitAt = MaxLine
Dim fHeader
sFile = "inputFile.txt"
dFile = LEFT(sFile, (LEN(sFile)-4))& "_0" & fCounter & ".txt"
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(sFile,1)
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
do while not objFileToRead.AtEndOfStream
        strLine = objFileToRead.ReadLine()
        objFileToWrite.WriteLine(strLine)
        If cPosition = 1 Then
            fHeader = strLine
        End If
        If cPosition = splitAt Then
            fCounter = fCounter + 1
            splitAt = splitAt + MaxLine
            objFileToWrite.Close
            Set objFileToWrite = Nothing
            If fCounter < 10 Then
                dFile=LEFT(dFile, (LEN(dFile)-5))& fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            ElseIf fCounter <100 Or fCounter = 100 Then
                dFile=LEFT(dFile, (LEN(dFile)-6))& fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            Else
                dFile=LEFT(dFile, (LEN(dFile)-7)) & fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            End If
        End If
        lCounter=lCounter + 1
        cPosition=cPosition + 1
Loop
objFileToWrite.Close
Set objFileToWrite = Nothing
objFileToRead.Close
Set objFileToRead = Nothing

How to get two or more commands together into a batch file

Try this: edited

@echo off
set "comd=dir /b /s *.zip"
set "pathName="
set /p "pathName=Enter The Value: "
cd /d "%pathName%"
%comd%
pause

Launch programs whose path contains spaces

What you're trying to achieve is simple, and the way you're going about it isn't. Try this (Works fine for me) and save the file as a batch from your text editor. Trust me, it's easier.

start firefox.exe

Check if registry key exists using VBScript

Simplest way avoiding RegRead and error handling tricks. Optional friendly consts for the registry:

Const HKEY_CLASSES_ROOT   = &H80000000
Const HKEY_CURRENT_USER   = &H80000001
Const HKEY_LOCAL_MACHINE  = &H80000002
Const HKEY_USERS          = &H80000003
Const HKEY_CURRENT_CONFIG = &H80000005

Then check with:

Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")

If oReg.EnumKey(HKEY_LOCAL_MACHINE, "SYSTEM\Example\Key\", "", "") = 0 Then
  MsgBox "Key Exists"
Else
  MsgBox "Key Not Found"
End If

IMPORTANT NOTES FOR THE ABOVE:

  • There are 4 parameters being passed to EnumKey, not the usual 3.
  • Equals zero means the key EXISTS.
  • The slash after key name is optional and not required.

How can I show a message box with two buttons?

The VBScript Messagebox is fairly limited as to the labels you can apply to the buttons, your choices are pretty much limited to:

  • OK
  • Cancel
  • Retry
  • Abort
  • Ignore
  • Yes
  • No

So you are going to have to build your own form if you want "ON"/"OFF"

Better yet, why not rephrase the prompt in the box so one of the above options works.

For example:

Do you want the light on? 
[Yes] [No]

And for God's sake don't do one of these UI monstrosities!

Switch setting? (Click "yes" for ON and "No" for Off)
[Yes] [No]

Vbscript list all PDF files in folder and subfolders

(For those who stumble upon this from your search engine of choice)

This just recursively traces down the folder, so you don't need to duplicate your code twice. Also the OPs logic is needlessly complex.

Wscript.Echo "begin."
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSuperFolder = objFSO.GetFolder(WScript.Arguments(0))
Call ShowSubfolders (objSuperFolder)

Wscript.Echo "end."

WScript.Quit 0

Sub ShowSubFolders(fFolder)
    Set objFolder = objFSO.GetFolder(fFolder.Path)
    Set colFiles = objFolder.Files
    For Each objFile in colFiles
        If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
            Wscript.Echo objFile.Name
        End If
    Next

    For Each Subfolder in fFolder.SubFolders
        ShowSubFolders(Subfolder)
    Next
End Sub

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

Is there "\n" equivalent in VBscript?

Tried and tested. I know that this works:

Replace(EmailText, vbNewLine, "<br>")

i.e. vbNewLine is also the equivalent of \n

Running command line silently with VbScript and getting output?

You can redirect output to a file and then read the file:

return = WshShell.Run("cmd /c C:\snmpset -c ... > c:\temp\output.txt", 0, true)

Set fso  = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("c:\temp\output.txt", 1)
text = file.ReadAll
file.Close

How to run VBScript from command line without Cscript/Wscript

When entering the script's full file spec or its filename on the command line, the shell will use information accessibly by

assoc | grep -i vbs
.vbs=VBSFile

ftype | grep -i vbs
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*

to decide which program to run for the script. In my case it's cscript.exe, in yours it will be wscript.exe - that explains why your WScript.Echos result in MsgBoxes.

As

cscript /?
Usage: CScript scriptname.extension [option...] [arguments...]

Options:
 //B         Batch mode: Suppresses script errors and prompts from displaying
 //D         Enable Active Debugging
 //E:engine  Use engine for executing script
 //H:CScript Changes the default script host to CScript.exe
 //H:WScript Changes the default script host to WScript.exe (default)
 //I         Interactive mode (default, opposite of //B)
 //Job:xxxx  Execute a WSF job
 //Logo      Display logo (default)
 //Nologo    Prevent logo display: No banner will be shown at execution time
 //S         Save current command line options for this user
 //T:nn      Time out in seconds:  Maximum time a script is permitted to run
 //X         Execute script in debugger
 //U         Use Unicode for redirected I/O from the console

shows, you can use //E and //S to permanently switch your default host to cscript.exe.

If you are so lazy that you don't even want to type the extension, make sure that the PATHEXT environment variable

set | grep -i vbs
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.tcl;.PSC1

contains .VBS and there is no Converter.cmd (that converts your harddisk into a washing machine) in your path.

Update wrt comment:

If you 'don't want to specify the full path of my vbscript everytime' you may:

  1. put your CONVERTER.VBS in a folder that is included in the PATH environment variable; the shell will then search all pathes - if necessary taking the PATHEXT and the ftype/assoc info into account - for a matching 'executable'.
  2. put a CONVERTER.BAT/.CMD into a path directory that contains a line like cscript p:\ath\to\CONVERTER.VBS

In both cases I would type out the extension to avoid (nasty) surprises.

Using command line arguments in VBscript

Set args = Wscript.Arguments

For Each arg In args
  Wscript.Echo arg
Next

From a command prompt, run the script like this:

CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"

Will give results like this:

1
2
A
B
Arg with spaces

How to read from a text file using VBScript?

Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")

' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close

' Write file
outFile.write (strRetVal)
outFile.Close

HTTP GET in VBS

Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

To answer your bonus question, the general answer is no, you don't need to set variables to "Nothing" in short .VBS scripts like yours, that get called by Wscript or Cscript.

The reason you might do this in the middle of a longer script is to release memory back to the operating system that VB would otherwise have been holding. These days when 8GB of RAM is typical and 16GB+ relatively common, this is unlikely to produce any measurable impact, even on a huge script that has several megabytes in a single variable. At this point it's kind of a hold-over from the days where you might have been working in 1MB or 2MB of RAM.

You're correct, the moment your .VBS script completes, all of your variables get destroyed and the memory is reclaimed anyway. Setting variables to "Nothing" simply speeds up that process, and allows you to do it in the middle of a script.

Add item to array in VBScript

Not an answer Or Why 'tricky' is bad:

>> a = Array(1)
>> a = Split(Join(a, "||") & "||2", "||")
>> WScript.Echo a(0) + a(1)
>>
12

Make a directory and copy a file

You can use the shell for this purpose.

Set shl = CreateObject("WScript.Shell") 
shl.Run "cmd mkdir YourDir" & copy "

How to stop a vb script running in windows

Create a Name.bat file that has the following line in it.

taskkill /F /IM wscript.exe /T

Be sure not to overpower your processor. If you're running long scripts, your processor speed changes and script lines will override each other.

Exit a while loop in VBS/VBA

Incredibly old question, but bearing in mind that the OP said he does not want to use Do While and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop:

This never runs anything if the status is already at "Fail"...

While (i < 20 And Not bShouldStop)
    If (Status = "Fail") Then
        bShouldStop = True
    Else
        i = i + 1
        '
        ' Do Something
        '
    End If  
Wend

Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.

While (i < 20 And Not bShouldStop)
    i = i + 1
    '
    ' Do Something
    '

    If (Status = "Fail") Then
        bShouldStop = True
    End If  
Wend

Ultimately, if the variable Status is being modified inside the While (and assuming you don't need i outside the while, it makes no difference really, but just wanted to present multiple options...

Run Excel Macro from Outside Excel Using VBScript From Command Line

I generally store my macros in xlam add-ins separately from my workbooks so I wanted to open a workbook and then run a macro stored separately.

Since this required a VBS Script, I wanted to make it "portable" so I could use it by passing arguments. Here is the final script, which takes 3 arguments.

  • Full Path to Workbook
  • Macro Name
  • [OPTIONAL] Path to separate workbook with Macro

I tested it like so:

"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlam" "Hello"

"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlsx" "Hello" "%AppData%\Microsoft\Excel\XLSTART\Book1.xlam"

runmacro.vbs:

Set args = Wscript.Arguments

ws = WScript.Arguments.Item(0)
macro = WScript.Arguments.Item(1)
If wscript.arguments.count > 2 Then
 macrowb= WScript.Arguments.Item(2)
End If

LaunchMacro

Sub LaunchMacro() 
  Dim xl
  Dim xlBook  

  Set xl = CreateObject("Excel.application")
  Set xlBook = xl.Workbooks.Open(ws, 0, True)
  If wscript.arguments.count > 2 Then
   Set macrowb= xl.Workbooks.Open(macrowb, 0, True)
  End If
  'xl.Application.Visible = True ' Show Excel Window
  xl.Application.run macro
  'xl.DisplayAlerts = False  ' suppress prompts and alert messages while a macro is running
  'xlBook.saved = True ' suppresses the Save Changes prompt when you close a workbook
  'xl.activewindow.close
  xl.Quit

End Sub 

Can Windows' built-in ZIP compression be scripted?

Here'a my attempt to summarize built-in capabilities windows for compression and uncompression - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

with a few given solutions that should work on almost every windows machine.

As regards to the shell.application and WSH I preferred the jscript as it allows a hybrid batch/jscript file (with .bat extension) that not require temp files.I've put unzip and zip capabilities in one file plus a few more features.

Is it better to use NOT or <> when comparing values?

The second example would be the one to go with, not just for readability, but because of the fact that in the first example, If NOT value1 would return a boolean value to be compared against value2. IOW, you need to rewrite that example as

If NOT (value1 = value2)

which just makes the use of the NOT keyword pointless.

VBScript How can I Format Date?

Although answer is provided I found simpler solution:

Date:

01/20/2017

By doing replace

CurrentDate = replace(date, "/", "-")

It will output:

01-20-2017

Permission denied on CopyFile in VBS

It's worth checking task manager for any stray wscript.exe tasks that are stuck. It could be one of those that's blocking access to the file.

How to pause a vbscript execution?

You can use a WScript object and call the Sleep method on it:

Set WScript = CreateObject("WScript.Shell")
WScript.Sleep 2000 'Sleeps for 2 seconds

Another option is to import and use the WinAPI function directly (only works in VBA, thanks @Helen):

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 2000

Run a vbscript from another vbscript

As Martin's Answer didn't work at all for me ("File not found") and atesio's Answer does not allow to call two scripts which include repeating variable definitions, here is another alternative which finally worked for me:

filepath =  Chr(34) & "C:\...\helloworld.vbs" & Chr(34)
Set objshell= CreateObject("WScript.Shell") 
objshell.Run "wscript " & filepath, , True
Set objshell= Nothing

(Windows 8.1)

Run Command Line & Command From VBS

The problem is on this line:

oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"

Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:

oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

You also have a typo in S:Claims\Sound.wav, should be S:\Claims\Sound.wav.

I also assume the apostrophe before Dim oShell and after Set oShell = Nothing are typos as well.

ActiveX component can't create object

I also meet the same error in vbscript.

Set objFSO = CreateObject("Scripting.FileSystemObject")

Solution:
Open command line, run :

regsvr32 /i "c:\windows\system32\scrrun.dll"

and it works

"Continue" (to next iteration) on VBScript

We can use a separate function for performing a continue statement work. suppose you have following problem:

for i=1 to 10

if(condition) then   'for loop body'
contionue
End If

Next

Here we will use a function call for for loop body:

for i=1 to 10
Call loopbody()
next

function loopbody()

if(condition) then   'for loop body'
Exit Function
End If

End Function

loop will continue for function exit statement....

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

How to set recurring schedule for xlsm file using Windows Task Scheduler

Better to use a as you indicated

  1. Create a simple vbs, which is a text file with a .vbs extension (see sample code below)
  2. Use the Task Scheduler to run the vbs
  3. Use the vbs to open the workbook at the scheduled time and then either:
    • use the Private Sub Workbook_Open() event in the ThisWorkbook module to run code when the file is opened
    • more robustly (as macros may be disabled on open), use Application.Run in the vbs to run the macro

See this example of the later approach at Running Excel on Windows Task Scheduler

sample vbs

Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("excel.application")
'vbs opens a file specified by the path below
Set ObjWB = ObjExcel.Workbooks.Open("C:\temp\rod.xlsm")
'either use the Workbook Open event (if macros are enabled), or Application.Run

ObjWB.Close False
ObjExcel.Quit
Set ObjExcel = Nothing

If file exists then delete the file

fileExists() is a method of FileSystemObject, not a global scope function.

You also have an issue with the delete, DeleteFile() is also a method of FileSystemObject.

Furthermore, it seems you are moving the file and then attempting to deal with the overwrite issue, which is out of order. First you must detect the name collision, so you can choose the rename the file or delete the collision first. I am assuming for some reason you want to keep deleting the new files until you get to the last one, which seemed implied in your question.

So you could use the block:

if NOT fso.FileExists(newname) Then  

    file.move fso.buildpath(OUT_PATH, newname)           

else

    fso.DeleteFile newname
    file.move fso.buildpath(OUT_PATH, newname)  

end if 

Also be careful that your string comparison with the = sign is case sensitive. Use strCmp with vbText compare option for case insensitive string comparison.

How do I debug a stand-alone VBScript script?

Click the mse7.exe installed along with Office typically at \Program Files\Microsoft Office\OFFICE11.

This will open up the debugger, open the file and then run the debugger in the GUI mode.

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

Read and write into a file using VBScript

This is for create a text file

For i = 1 to 10
    createFile( i )
Next

Public Sub createFile(a)

    Dim fso,MyFile
    filePath = "C:\file_name" & a & ".txt"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set MyFile = fso.CreateTextFile(filePath)
    MyFile.WriteLine("This is a separate file")
    MyFile.close

End Sub

And this for read a text file

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

For Each line in dict.Items
  WScript.Echo line
  WScript.Sleep 1000
Next

Adding quotes to a string in VBScript

You can escape by doubling the quotes

g="abcd """ & a & """"

or write an explicit chr() call

g="abcd " & chr(34) & a & chr(34)

MsgBox "" vs MsgBox() in VBScript

A callable piece of code (routine) can be a Sub (called for a side effect/what it does) or a Function (called for its return value) or a mixture of both. As the docs for MsgBox

Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.

MsgBox(prompt[, buttons][, title][, helpfile, context])

indicate, this routine is of the third kind.

The syntactical rules of VBScript are simple:

Use parameter list () when calling a (routine as a) Function

If you want to display a message to the user and need to know the user's reponse:

Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
   ' MyVar contains either 1 or 2, depending on which button is clicked.

Don't use parameter list () when calling a (routine as a) Sub

If you want to display a message to the user and are not interested in the response:

MsgBox "Hello World!", 65, "MsgBox Example"

This beautiful simplicity is messed up by:

The design flaw of using () for parameter lists and to force call-by-value semantics

>> Sub S(n) : n = n + 1 : End Sub
>> n = 1
>> S n
>> WScript.Echo n
>> S (n)
>> WScript.Echo n
>>
2
2

S (n) does not mean "call S with n", but "call S with a copy of n's value". Programmers seeing that

>> s = "value"
>> MsgBox(s)

'works' are in for a suprise when they try:

>> MsgBox(s, 65, "MsgBox Example")
>>
Error Number:       1044
Error Description:  Cannot use parentheses when calling a Sub

The compiler's leniency with regard to empty () in a Sub call. The 'pure' Sub Randomize (called for the side effect of setting the random seed) can be called by

Randomize()

although the () can neither mean "give me your return value) nor "pass something by value". A bit more strictness here would force prgrammers to be aware of the difference in

Randomize n

and

Randomize (n)

The Call statement that allows parameter list () in Sub calls:

s = "value" Call MsgBox(s, 65, "MsgBox Example")

which further encourage programmers to use () without thinking.

(Based on What do you mean "cannot use parentheses?")

Getting the Username from the HKEY_USERS values

You can use the command PSGetSid from Microsoft's SysInternals team.

Download URL: http://technet.microsoft.com/en-gb/sysinternals/bb897417.aspx

Usage:

psgetsid [\\computer[,computer[,...] | @file] [-u username [-p password]]] [account|SID]
-u  Specifies optional user name for login to remote computer.
-p  Specifies optional password for user name. If you omit this you will be prompted to enter a hidden password.
Account PsGetSid will report the SID for the specified user account rather than the computer.
SID PsGetSid will report the account for the specified SID.
Computer    Direct PsGetSid to perform the command on the remote computer or computers specified. If you omit the computer name PsGetSid runs the command on the local system, and if you specify a wildcard (\\*), PsGetSid runs the command on all computers in the current domain.
@file   PsGetSid will execute the command on each of the computers listed in the file.

Example:

psgetsid S-1-5-21-583907252-682003330-839522115-63941

NB:

  • Where the user is a domain/AD(LDAP) user, running this on any computer on the domain should give the same results.
  • Where the user is local to the machine the command should either be run on that machine, or you should specify the computer via the optional parameter.

Update

If you use PowerShell, the following may be useful for resolving any AD users listed:

#create a drive for HKEY USERS:
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS -ErrorAction SilentlyContinue

#List all immediate subfolders
#where they're a folder (not a key)
#and they's an SID (i.e. exclude .DEFAULT and SID_Classes entries)
#return the SID
#and return the related AD entry (should one exist).
Get-ChildItem -Path 'HKU:\' `
| ?{($_.PSIsContainer -eq $true) `
-and ($_.PSChildName -match '^S-[\d-]+$')} `
| select @{N='SID';E={$_.PSChildName}} `
, @{N='Name';E={Get-ADUser $_.PSChildName | select -expand Name}}

You could also refine the SID filter further to only pull back those SIDs which will resolve to an AD account if you wished; more on the SID structure here: https://technet.microsoft.com/en-us/library/cc962011.aspx

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

What does the "On Error Resume Next" statement do?

It means, when an error happens on the line, it is telling vbscript to continue execution without aborting the script. Sometimes, the On Error follows the Goto label to alter the flow of execution, something like this in a Sub code block, now you know why and how the usage of GOTO can result in spaghetti code:

Sub MySubRoutine()
   On Error Goto ErrorHandler

   REM VB code...

   REM More VB Code...

Exit_MySubRoutine:

   REM Disable the Error Handler!

   On Error Goto 0

   REM Leave....
   Exit Sub

ErrorHandler:

   REM Do something about the Error

   Goto Exit_MySubRoutine
End Sub

Running vbscript from batch file

Batch files are processed row by row and terminate whenever you call an executable directly.
- To make the batch file wait for the process to terminate and continue, put call in front of it.
- To make the batch file continue without waiting, put start "" in front of it.

I recommend using this single line script to accomplish your goal:

@call cscript "%~dp0necdaily.vbs"

(because this is a single line, you can use @ instead of @echo off)

If you believe your script can only be called from the SysWOW64 versions of cmd.exe, you might try:

@%WINDIR%\SysWOW64\cmd.exe /c call cscript "%~dp0necdaily.vbs"

If you need the window to remain, you can replace /c with /k

Automatic login script for a website on windows machine?

Well, its true that we can use Vb Script for what you intended to do. We can open an application through the code like Internet Explorer. We can navigate to site you intend for. Later we can check the element names of Text Boxes which require username and password; can set then and then Login. It works fine all of using code.

No manual interaction with the website. And eventually you will end up signing in by just double clicking the file.

To get you started :

Set objIE = CreateObject("InternetExplorer.Application")

Call objIE.Navigate("https://gmail.com")

This will open an instance of internet explore and navigate to gmail. Rest you can learn and apply.

VBScript - How to make program wait until process has finished?

Probably something like this? (UNTESTED)

Sub Sample()
    Dim strWB4, strMyMacro
    strMyMacro = "Sheet1.my_macro_name"

    '
    '~~> Rest of Code
    '

    'loop through the folder and get the file names
    For Each Fil In FLD.Files
        Set x4WB = x1.Workbooks.Open(Fil)
        x4WB.Application.Visible = True

        x1.Run strMyMacro

        x4WB.Close

        Do Until IsWorkBookOpen(Fil) = False
            DoEvents
        Loop
    Next

    '
    '~~> Rest of Code
    '
End Sub

'~~> Function to check if the file is open
Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

How to call a VbScript from a Batch File without opening an additional command prompt

rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"

OR

rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"

You can also add the option //e:vbscript to make sure the scripting engine will recognize your script as a vbscript.

Windows/DOS batch files doesn't require escaping \ like *nix.

You can still use "C:\Users\guest\Desktop\123\MyScript.vbs", but this requires the user has *.vbs associated to wscript.

Create an Excel file using vbscripts

Here is a sample code

strFileName = "c:\test.xls"

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True

Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strFileName)

objExcel.Quit

How to check for registry value using VbScript

Try this. This script gets current logged in user's name & home directory:

On Error Resume Next

Dim objShell, strTemp
Set objShell = WScript.CreateObject("WScript.Shell")

strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERNAME"
WScript.Echo "Logged in User: " & objShell.RegRead(strTemp) 

strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERPROFILE"
WScript.Echo "User Home: " & objShell.RegRead(strTemp) 

Copy a file from one folder to another using vbscripting

Just posted my finished code for a similar project. It copies files of certain extensions in my code its pdf tif and tiff you can change them to whatever you want copied or delete the if statements if you only need 1 or 2 types. When a file is created or modified it gets the archive attribute this code also looks for that attribute and only copies it if it exists and then removes it after its copied so you dont copy unneeded files. It also has a log setup in it so that you will see a log of what time and day evetrything was transfered from the last time you ran the script. Hope it helps! the link is Error: Object Required; 'objDIR' Code: 800A01A8

Error checking for NULL in VBScript

I will just add a blank ("") to the end of the variable and do the comparison. Something like below should work even when that variable is null. You can also trim the variable just in case of spaces.

If provider & "" <> "" Then 
    url = url & "&provider=" & provider 
End if

How to run vbs as administrator from vbs?

This is the universal and best solution for this:

If WScript.Arguments.Count <> 1 Then WScript.Quit 1
RunAsAdmin
Main

Sub RunAsAdmin()
    Set Shell = CreateObject("WScript.Shell")
    Set Env = Shell.Environment("VOLATILE")
    If Shell.Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
        Env("CurrentDirectory") = Shell.CurrentDirectory
        ArgsList = ""
        For i = 1 To WScript.Arguments.Count
            ArgsList = ArgsList & """ """ & WScript.Arguments(i - 1)
        Next
        CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & ArgsList & """", , "runas", 5
        WScript.Sleep 100
        Env.Remove("CurrentDirectory")
        WScript.Quit
    End If
    If Env("CurrentDirectory") <> "" Then Shell.CurrentDirectory = Env("CurrentDirectory")
End Sub

Sub Main()
    'Your code here!
End Sub

Advantages:

1) The parameter injection is not possible.
2) The number of arguments does not change after the elevation to administrator and then you can check them before you elevate yourself.
3) You know for real and immediately if the script runs as an administrator. For example, if you call it from a control panel uninstallation entry, the RunAsAdmin function will not run unnecessarily because in that case you are already an administrator. Same thing if you call it from a script already elevated to administrator.
4) The window is kept at its current size and position, as it should be.
5) The current directory doesn't change after obtained administrative privileges.

Disadvantages: Nobody

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

how can I check if a file exists?

For anyone who is looking a way to watch a specific file to exist in VBS:

Function bIsFileDownloaded(strPath, timeout)
  Dim FSO, fileIsDownloaded
  set FSO = CreateObject("Scripting.FileSystemObject")
  fileIsDownloaded = false
  limit = DateAdd("s", timeout, Now)
  Do While Now < limit
    If FSO.FileExists(strPath) Then : fileIsDownloaded = True : Exit Do : End If
    WScript.Sleep 1000      
  Loop
  Set FSO = Nothing
  bIsFileDownloaded = fileIsDownloaded
End Function

Usage:

FileName = "C:\test.txt"
fileIsDownloaded = bIsFileDownloaded(FileName, 5) ' keep watching for 5 seconds

If fileIsDownloaded Then
  WScript.Echo Now & " File is Downloaded: " & FileName
Else
  WScript.Echo Now & " Timeout, file not found: " & FileName 
End If

Find specific string in a text file with VBS script

I'd recommend using a regular expressions instead of string operations for this:

Set fso = CreateObject("Scripting.FileSystemObject")

filename = "C:\VBS\filediprova.txt"

newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"

Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global  = False
re.IgnoreCase = True

text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")

The regular expression will match a line feed (\n) followed by a line containing the string Test Case followed by a number (\d), and the replacement will prepend that with the text you want to insert (variable newtext). Setting re.Global = False makes the replacement stop after the first match.

If the line breaks in your text file are encoded as CR-LF (carriage return + line feed) you'll have to change \n into \r\n and vbLf into vbCrLf.

If you have to modify several text files, you could do it in a loop like this:

For Each f In fso.GetFolder("C:\VBS").Files
  If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
    text = f.OpenAsTextStream.ReadAll
    f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
  End If
Next

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

Plotting in a non-blocking way with Matplotlib

I spent a long time looking for solutions, and found this answer.

It looks like, in order to get what you (and I) want, you need the combination of plt.ion(), plt.show() (not with block=False) and, most importantly, plt.pause(.001) (or whatever time you want). The pause is needed because the GUI events happen while the main code is sleeping, including drawing. It's possible that this is implemented by picking up time from a sleeping thread, so maybe IDEs mess with that—I don't know.

Here's an implementation that works for me on python 3.5:

import numpy as np
from matplotlib import pyplot as plt

def main():
    plt.axis([-50,50,0,10000])
    plt.ion()
    plt.show()

    x = np.arange(-50, 51)
    for pow in range(1,5):   # plot x^1, x^2, ..., x^4
        y = [Xi**pow for Xi in x]
        plt.plot(x, y)
        plt.draw()
        plt.pause(0.001)
        input("Press [enter] to continue.")

if __name__ == '__main__':
    main()

Generate a random point within a circle (uniformly)

I used once this method: This may be totally unoptimized (ie it uses an array of point so its unusable for big circles) but gives random distribution enough. You could skip the creation of the matrix and draw directly if you wish to. The method is to randomize all points in a rectangle that fall inside the circle.

bool[,] getMatrix(System.Drawing.Rectangle r) {
    bool[,] matrix = new bool[r.Width, r.Height];
    return matrix;
}

void fillMatrix(ref bool[,] matrix, Vector center) {
    double radius = center.X;
    Random r = new Random();
    for (int y = 0; y < matrix.GetLength(0); y++) {
        for (int x = 0; x < matrix.GetLength(1); x++)
        {
            double distance = (center - new Vector(x, y)).Length;
            if (distance < radius) {
                matrix[x, y] = r.NextDouble() > 0.5;
            }
        }
    }

}

private void drawMatrix(Vector centerPoint, double radius, bool[,] matrix) {
    var g = this.CreateGraphics();

    Bitmap pixel = new Bitmap(1,1);
    pixel.SetPixel(0, 0, Color.Black);

    for (int y = 0; y < matrix.GetLength(0); y++)
    {
        for (int x = 0; x < matrix.GetLength(1); x++)
        {
            if (matrix[x, y]) {
                g.DrawImage(pixel, new PointF((float)(centerPoint.X - radius + x), (float)(centerPoint.Y - radius + y)));
            }
        }
    }

    g.Dispose();
}

private void button1_Click(object sender, EventArgs e)
{
    System.Drawing.Rectangle r = new System.Drawing.Rectangle(100,100,200,200);
    double radius = r.Width / 2;
    Vector center = new Vector(r.Left + radius, r.Top + radius);
    Vector normalizedCenter = new Vector(radius, radius);
    bool[,] matrix = getMatrix(r);
    fillMatrix(ref matrix, normalizedCenter);
    drawMatrix(center, radius, matrix);
}

enter image description here

Understanding the difference between Object.create() and new SomeFunction()

This:

var foo = new Foo();

and

var foo = Object.create(Foo.prototype);

are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as

function Foo() {
    alert("This constructor does not run with Object.create");
}

Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.

What does [object Object] mean?

[object Object] is the default toString representation of an object in javascript.

If you want to know the properties of your object, just foreach over it like this:

for(var property in obj) {
    alert(property + "=" + obj[property]);
}

In your particular case, you are getting a jQuery object. Try doing this instead:

$('#senddvd').click(function ()
{
   alert('hello');
   var a=whichIsVisible();
   alert(whichIsVisible().attr("id"));
});

This should alert the id of the visible element.

ORACLE IIF Statement

In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE function.

SET SERVEROUTPUT ON

DECLARE
    x   VARCHAR2(10);
BEGIN
    x := owa_util.ite('a' = 'b','T','F');
    dbms_output.put_line(x);
END;
/

F

PL/SQL procedure successfully completed.

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

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

If you want to use calc in your CSS file use a polyfill like PolyCalc. Should be light enough to work on mobile browsers (e.g. below iOS 6 and below Android 4.4 phones).

How do I do redo (i.e. "undo undo") in Vim?

First press the Esc key to exit from edit mode.

Then,

For undo, use u key as many times you want to undo.

For redo, use Ctrl +r key

Disabling and enabling a html input button

You can do this fairly easily with just straight JavaScript, no libraries required.

Enable a button

document.getElementById("Button").disabled=false;

Disable a button

 document.getElementById("Button").disabled=true;

No external libraries necessary.

Reading data from DataGridView in C#

If you wish, you can also use the column names instead of column numbers.

For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.

dataGridView.Rows[4].Cells["Name"].Value.ToString();

Hope it helps.

HTTP Error 503, the service is unavailable

Also check the address bar and make sure the page is in the right location.

This error can be returned instead of the 404 (Page not found). In my case, it was a bad link on the page that didn't have a subfolder included.

Mongoose, update values in array of objects

In mongoose we can update, like simple array

user.updateInfoByIndex(0,"test")

User.methods.updateInfoByIndex = function(index, info) ={
    this.arrayField[index]=info
    this.save()
}

How to call C++ function from C?

Assuming the C++ API is C-compatible (no classes, templates, etc.), you can wrap it in extern "C" { ... }, just as you did when going the other way.

If you want to expose objects and other cute C++ stuff, you'll have to write a wrapper API.

jQuery "blinking highlight" effect on div?

If you don't want the overhead of jQuery UI, I recently wrote a recursive solution using .animate(). You can customize the delays and colors as you need.

function doBlink(id, count) {
    $(id).animate({ backgroundColor: "#fee3ea" }, {
        duration: 100, 
        complete: function() {

            // reset
            $(id).delay(100).animate({ backgroundColor: "#ffffff" }, {
                duration: 100,
                complete: function() {

                    // maybe call next round
                    if(count > 1) {
                        doBlink(id, --count);
                    }
                }
            });

        }
    });
}

Of course you'll need the color plugin to get backgroundColor to work with .animate(). https://github.com/jquery/jquery-color

And to provide a bit of context this is how I called it. I needed to scroll the page to my target div and then blink it.

$(window).load(function(){
    $('html,body').animate({
        scrollTop: $(scrollToId).offset().top - 50
    }, {
        duration: 400,
        complete: function() { doBlink(scrollToId, 5); }
    });
});

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

How to decrypt hash stored by bcrypt

You simply can't.

bcrypt uses salting, of different rounds, I use 10 usually.

bcrypt.hash(req.body.password,10,function(error,response){ }

This 10 is salting random string into your password.

How can I read and parse CSV files in C++?

Another CSV I/O library can be found here:

http://code.google.com/p/fast-cpp-csv-parser/

#include "csv.h"

int main(){
  io::CSVReader<3> in("ram.csv");
  in.read_header(io::ignore_extra_column, "vendor", "size", "speed");
  std::string vendor; int size; double speed;
  while(in.read_row(vendor, size, speed)){
    // do stuff with the data
  }
}

Java Regex to Validate Full Name allow only Spaces and Letters

My personal choice is: ^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$, Where:

^\p{L}+ - It should start with 1 or more letters.

[\p{Pd}\p{Zs}'\p{L}]* - It can have letters, space character (including invisible), dash or hyphen characters and ' in any order 0 or more times.

\p{L}+$ - It should finish with 1 or more letters.

|^\p{L}+$ - Or it just should contain 1 or more letters (It is done to support single letter names).

Support for dots (full stops) was dropped, as in British English it can be dropped in Mr or Mrs, for example.

CSS Auto hide elements after 5 seconds

Of course you can, just use setTimeout to change a class or something to trigger the transition.

HTML:

<p id="aap">OHAI!</p>

CSS:

p {
    opacity:1;
    transition:opacity 500ms;
}
p.waa {
    opacity:0;
}

JS to run on load or DOMContentReady:

setTimeout(function(){
    document.getElementById('aap').className = 'waa';
}, 5000);

Example fiddle here.

how to Call super constructor in Lombok

As an option you can use com.fasterxml.jackson.databind.ObjectMapper to initialize a child class from parent

public class A {
    int x;
    int y;
}

public class B extends A {
    int z;
}

ObjectMapper MAPPER = new ObjectMapper(); //it's configurable
MAPPER.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
MAPPER.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );

//Then wherever you need to initialize child from parent:
A parent = new A(x, y);
B child = MAPPER.convertValue( parent, B.class);
child.setZ(z);

You can still use any lombok annotations on A and B if you need.

What causes javac to issue the "uses unchecked or unsafe operations" warning

This warning means that your code operates on a raw type, recompile the example with the

-Xlint:unchecked 

to get the details

like this:

javac YourFile.java -Xlint:unchecked

Main.java:7: warning: [unchecked] unchecked cast
        clone.mylist = (ArrayList<String>)this.mylist.clone();
                                                           ^
  required: ArrayList<String>
  found:    Object
1 warning

docs.oracle.com talks about it here: http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html

How can I do an UPDATE statement with JOIN in SQL Server?

For SQLite use the RowID property to make the update:

update Table set column = 'NewValue'
where RowID = 
(select t1.RowID from Table t1
join Table2 t2 on t1.JoinField = t2.JoinField
where t2.SelectValue = 'FooMyBarPlease');

Remove Null Value from String array in java

If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:

import java.util.ArrayList;
import java.util.List;

public class RemoveNullValue {
  public static void main( String args[] ) {
    String[] firstArray = {"test1", "", "test2", "test4", "", null};

    List<String> list = new ArrayList<String>();

    for(String s : firstArray) {
       if(s != null && s.length() > 0) {
          list.add(s);
       }
    }

    firstArray = list.toArray(new String[list.size()]);
  }
}

Added null to show the difference between an empty String instance ("") and null.

Since this answer is around 4.5 years old, I'm adding a Java 8 example:

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveNullValue {
    public static void main( String args[] ) {
        String[] firstArray = {"test1", "", "test2", "test4", "", null};

        firstArray = Arrays.stream(firstArray)
                     .filter(s -> (s != null && s.length() > 0))
                     .toArray(String[]::new);    

    }
}

java.lang.RuntimeException: Unable to start activity ComponentInfo

After trying few answers they are either not related to my project or , I have tried cleaning and rebuilding (https://stackoverflow.com/a/48760966/8463813). But it didn't work for me directly. I have compared it with older version of code, in which i observed some library files(jars and aars in External Libraries directory) are missing. Tried Invalidate Cache and Restart worked, which created all the libraries and working fine.

Is there a "not equal" operator in Python?

Seeing as everyone else has already listed most of the other ways to say not equal I will just add:

if not (1) == (1): # This will eval true then false
    # (ie: 1 == 1 is true but the opposite(not) is false)
    print "the world is ending" # This will only run on a if true
elif (1+1) != (2): #second if
    print "the world is ending"
    # This will only run if the first if is false and the second if is true
else: # this will only run if the if both if's are false
    print "you are good for another day"

in this case it is simple switching the check of positive == (true) to negative and vise versa...

How to beautifully update a JPA entity in Spring Data?

Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)

Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);

Is's better because getOne(ID id) gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find() like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.

Instantiate and Present a viewController in Swift

No matter what I tried, it just wouldn't work for me - no errors, but no new view controller on my screen either. Don't know why, but wrapping it in timeout function finally made it work:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.0) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "TabletViewController")
    self.present(controller, animated: true, completion: nil)
}

rand() between 0 and 1

It doesn't. It makes 0 <= r < 1, but your original is 0 <= r <= 1.

Note that this can lead to undefined behavior if RAND_MAX + 1 overflows.

Internet Explorer 11 detection

I found IE11 is giving more than one user agent strings in different environments.

Instead of relying on MSIE, and other approaches, It's better to rely on Trident version

const isIE11 = userAgent => userAgent.match(/Trident\/([\d.]+)/) ? +userAgent.match(/Trident\/([\d.]+)/)[1] >= 7;

Hope this helps :)

Express-js can't GET my static files, why?

i just try this code and working

const exp = require('express');
const app = exp();

app.use(exp.static("public"));

and working,

before (not working) :

const express = require('express');
const app = express();
app.use(express.static("public"));

just try

What is lazy loading in Hibernate?

Hiberante supports the feature of lazy initialization for both entities and collections. Hibernate engine loads only those objects that we are querying for does not other entites or collections.

lazy="false" by default loading initialization mention for the only child is lazy.in case of true that is parent is loading does not support child

Pandas group-by and sum

Use GroupBy.sum:

df.groupby(['Fruit','Name']).sum()

Out[31]: 
               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Grapes  Bob        35
        Tom        87
        Tony       15
Oranges Bob        67
        Mike       57
        Tom        15
        Tony        1

bootstrap button shows blue outline when clicked

This may help if someone still has this question unresolved.

_x000D_
_x000D_
(function() {_x000D_
  $('button').on('click', function() {_x000D_
    $("#action").html("button was clicked");_x000D_
    console.log("the button was clicked");_x000D_
  });_x000D_
})();
_x000D_
.btn-clear {_x000D_
  background-color: transparent !important;_x000D_
  border-style: none !important;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.btn-clear:active,_x000D_
.btn-clear:focus {_x000D_
  outline-style: none !important;_x000D_
  outline-color: transparent;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<!-- this button has default style -->_x000D_
<button>Action</button>_x000D_
<!-- this button is clear of style -->_x000D_
<button class="btn-clear">Action</button>_x000D_
_x000D_
<label id="action"></label>
_x000D_
_x000D_
_x000D_

Fatal error: Call to undefined function socket_create()

Open the php.ini file in your server environment and remove ; from ;extension=sockets. if it's doesn't work, you have to download the socket extension for PHP and put it into ext directory in the php installation path. Restart your http server and everything should work.

How to change screen resolution of Raspberry Pi

TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the

resolution 82   1920x1080   60Hz    1080p

hdmi_ignore_edid=0xa5000080
hdmi_force_hotplug=1
hdmi_boost=7
hdmi_group=2
hdmi_mode=82
hdmi_drive=1

Number prime test in JavaScript

function isPrime(num) {
        if(num < 2) return false;
        for (var i = 2; i <= num/2; i++) {
            if(num%i==0)
                return false;
        }
        return true;
    }

If we want the prime number between two number we have to add this code only

for(var i = 0; i < 100; i++){
        if(isPrime(i))
            console.log(i);
    }

How can I get a resource content from a static context?

My Kotlin solution is to use a static Application context:

class App : Application() {
    companion object {
        lateinit var instance: App private set
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }
}

And the Strings class, that I use everywhere:

object Strings {
    fun get(@StringRes stringRes: Int, vararg formatArgs: Any = emptyArray()): String {
        return App.instance.getString(stringRes, *formatArgs)
    }
}

So you can have a clean way of getting resource strings

Strings.get(R.string.some_string)
Strings.get(R.string.some_string_with_arguments, "Some argument")

Please don't delete this answer, let me keep one.

How to export JavaScript array info to csv (on client side)?

In case anyone needs this for knockout js, it works ok with basically the proposed solution:

html:

<a data-bind="attr: {download: filename, href: csvContent}">Download</a>

view model:

// for the download link
this.filename = ko.computed(function () {
    return ko.unwrap(this.id) + '.csv';
}, this);
this.csvContent = ko.computed(function () {
    if (!this.csvLink) {
        var data = ko.unwrap(this.data),
            ret = 'data:text/csv;charset=utf-8,';

        ret += data.map(function (row) {
            return row.join(',');
        }).join('\n');

        return encodeURI(ret);
    }
}, this);

Moment.js - two dates difference in number of days

const FindDate = (date, allDate) => {
        
    // moment().diff only works on moment(). Make sure both date and elements in allDate array are in moment format
    let nearestDate = -1; 
    
    allDate.some(d => {
        const currentDate = moment(d)
        const difference = currentDate.diff(d); // Or d.diff(date) depending on what you're trying to find
        if(difference >= 0){
            nearestDate = d
        }
    });
    
    console.log(nearestDate)
}

How to select the row with the maximum value in each group

Here's another data.table solution, since which.max does not work on characters

library(data.table)
group <- data.table(Subject=ID, pt=Value, Event=Event)

group[, .SD[order(pt, decreasing = TRUE) == 1], by = Subject]

Java string split with "." (dot)

The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:

final String extensionRemoved = filename.split("\\.")[0];

I hope this helps

How can I auto hide alert box after it showing it?

impossible with javascript. Just as another alternative to suggestions from other answers: consider using jGrowl: http://archive.plugins.jquery.com/project/jGrowl

JBoss debugging in Eclipse

What @VonC says is correct, but you can put the commands to set debug directly into VM arguments on jBoss Launch.

To do that, open jBoss server inside Eclipse, go to Open launch configuration and put this in VM arguments textbox: vm args

Reading/parsing Excel (xls) files with Python

If the file is really an old .xls, this works for me on python3 just using base open() and pandas:

df = pandas.read_csv(open(f, encoding = 'UTF-8'), sep='\t')

Note that the file I'm using is tab delimited. less or a text editor should be able to read .xls so that you can sniff out the delimiter.

I did not have a lot of luck with xlrd because of – I think – UTF-8 issues.

Close Bootstrap Modal

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script>_x000D_
$(window).load(function(){_x000D_
      $('#myModal').modal('show');_x000D_
});_x000D_
$(function () {_x000D_
   $('#modal').modal('toggle');_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Modal Example</h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

installing apache: no VCRUNTIME140.dll

Also, please make sure you installed the correct version of apache on your computer. For example, not install a x86 on a 64bit system. Vice versa.

Capturing image from webcam in java?

FMJ can do this, as can the supporting library it uses, LTI-CIVIL. Both are on sourceforge.

How do I auto size a UIScrollView to fit its content

Great & best solution from @leviathan. Just translating to swift using FP (functional programming) approach.

self.scrollView.contentSize = self.scrollView.subviews.reduce(CGRect(), { 
  CGRectUnion($0, $1.frame) 
}.size

What does "int 0x80" mean in assembly code?

int is nothing but an interruption i.e the processor will put its current execution to hold.

0x80 is nothing but a system call or the kernel call. i.e the system function will be executed.

To be specific 0x80 represents rt_sigtimedwait/init_module/restart_sys it varies from architecture to architecture.

For more details refer https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md

How do I access nested HashMaps in Java?

You can get the nested value by repeating .get(), but with deeply nested maps you have to do a lot of casting into Map. An easier way is to use a generic method for getting a nested value.

Implementation

public static <T> T getNestedValue(Map map, String... keys) {
    Object value = map;

    for (String key : keys) {
        value = ((Map) value).get(key);
    }

    return (T) value;
}

Usage

// Map contents with string and even a list:
{
  "data": {
    "vehicles": {
      "list": [
        {
          "registration": {
            "owner": {
              "id": "3643619"
            }
          }
        }
      ]
    }
  }
}
List<Map> list = getNestedValue(mapContents, "data", "vehicles", "list");
Map first = list.get(0);
String id = getNestedValue(first, "registration", "owner", "id");

Get week number (in the year) from a date PHP

try this solution

date( 'W', strtotime( "2017-01-01 + 1 day" ) );

Get pixel's RGB using PIL

Yes, this way:

im = Image.open('image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))

print(r, g, b)
(65, 100, 137)

The reason you were getting a single value before with pix[1, 1] is because GIF pixels refer to one of the 256 values in the GIF color palette.

See also this SO post: Python and PIL pixel values different for GIF and JPEG and this PIL Reference page contains more information on the convert() function.

By the way, your code would work just fine for .jpg images.

"Integer number too large" error message for 600851475143

The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.

To tell the compiler that you want the number interpretet as a long you have to add either l or L after it. Your number should then look like this 600851475143L.

Since some Fonts make it hard to distinguish "1" and lower case "l" from each other you should always use the upper case "L".

Can't find/install libXtst.so.6?

This worked for me in Luna elementary OS

sudo apt-get install libxtst6:i386

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

herein lies the answer... IIS Settings

IIS-->Default SMTP Virtual Server-->Properties-->Access-->Relay restrictions just add or exclude the IPs you care about, should resolve the issue.

node.js http 'get' request with query string parameters

I have been struggling with how to add query string parameters to my URL. I couldn't make it work until I realized that I needed to add ? at the end of my URL, otherwise it won't work. This is very important as it will save you hours of debugging, believe me: been there...done that.

Below, is a simple API Endpoint that calls the Open Weather API and passes APPID, lat and lon as query parameters and return weather data as a JSON object. Hope this helps.

//Load the request module
var request = require('request');

//Load the query String module
var querystring = require('querystring');

// Load OpenWeather Credentials
var OpenWeatherAppId = require('../config/third-party').openWeather;

router.post('/getCurrentWeather', function (req, res) {
    var urlOpenWeatherCurrent = 'http://api.openweathermap.org/data/2.5/weather?'
    var queryObject = {
        APPID: OpenWeatherAppId.appId,
        lat: req.body.lat,
        lon: req.body.lon
    }
    console.log(queryObject)
    request({
        url:urlOpenWeatherCurrent,
        qs: queryObject
    }, function (error, response, body) {
        if (error) {
            console.log('error:', error); // Print the error if one occurred

        } else if(response && body) {
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            res.json({'body': body}); // Print JSON response.
        }
    })
})  

Or if you want to use the querystring module, make the following changes

var queryObject = querystring.stringify({
    APPID: OpenWeatherAppId.appId,
    lat: req.body.lat,
    lon: req.body.lon
});

request({
   url:urlOpenWeatherCurrent + queryObject
}, function (error, response, body) {...})

What does ':' (colon) do in JavaScript?

Let's not forget the switch statement, where colon is used after each "case".

Structs data type in php?

Only associative arrays are structs in PHP.

And you can't make them strict on their own.

But you can sort of fake structure strictness with classes and interfaces, but beware that unlike structures, class instances are not passed in arguments, their identifiers are!


You can define a struct through an interface (or at least close to it)

Structs enforce a certain structure on an object.

PHP (<= 7.3) does not have native structs, but you can get around it with interfaces and type hinting:

interface FooStruct 
{
    public function name() : string;
}
interface BarStruct 
{
    public function id() : int;
}
interface MyStruct 
{
   public function foo() : FooStruct;
   public function bar() : BarStruct;
}

Any class implementing MyStruct will be a MyStruct.

The way it's build up is not up to the struct, it just ensures that the data returned is correct.


What about setting data?

Setting struct data is problematic as we end up with getters and setters and it's something that is close to an anemic object or a DTO and is considered an anti-pattern by some people

Wrong example:

interface FooStruct 
{
    public function getName() : string;
    public function setName(string $value) : FooStruct;
}
interface BarStruct 
{
    public function getId() : int;
    public function setId(int $value) : BarStruct;
}
interface MyStruct 
{
   public function getFoo() : FooStruct;
   public function setFoo(FooStruct $value) : MyStruct;
   public function getBar() : BarStruct;
   public function setBar(BarStruct $value) : MyStruct;
}

Then we end up with class implementations that might be mutable, and a struct must not mutate, this is to make it a "data type", just like int, string. Yet there's no way to restrict that with interfaces in PHP, meaning people will be able to implement your struct interface in a class that is not a struct. Make sure to keep the instance immutable

Also a struct may then be instantiated without the correct data and trigger errors when trying to access the data.

An easy and reliable way to set data in a PHP struct class is through its constructor

interface FooStruct 
{
    public function name() : string;
}
interface BarStruct 
{
    public function id() : int;
}
interface MyStruct 
{
   public function foo() : FooStruct;
   public function bar() : BarStruct;
}

class Foo implements FooStruct 
{
   protected $name;
   public function __construct(string $name)
   {
       $this->name = $name;
   }
   public function name() : string
   {
       return $this->name;
   }
}

class Bar implements BarStruct 
{
   protected $id;
   public function __construct(string $id)
   {
       $this->id = $id;
   }
   public function id() : int
   {
       return $this->id;
   }
}

class My implements MyStruct 
{
   protected $foo, $bar;
   public function __construct(FooStruct $foo, BarStruct $bar)
   {
       $this->foo = $foo;
       $this->bar = $bar;
   }
   public function foo() : FooStruct
   {
       return $this->foo;
   }
   public function bar() : BarStruct
   {
       return $this->bar;
   }
}

Type hinting using interfaces: (if your IDE supports it)

If you don't mind not having the strict type checking, then another way would be using interfaces or classes with comments for the IDE.

/**
 * Interface My
 * @property Foo $foo
 * @property Bar $bar
 */
interface My 
{

}

/**
 * Interface Foo
 * @property string|integer $id
 * @property string $name
 */
interface Foo 
{

}

/**
 * Interface Bar
 * @property integer $id
 */
interface Bar
{

}

The reason to use interfaces instead of classes is for the same reason why interfaces exist in the first place, because then many classes with many implementations can have this same structure and each method/function that uses it will support every class with this interface.

This depends on your IDE, so you might need to use classes instead or just live without it.

Note: Remember that you have to validate/sanitize the data in the instance elsewhere in the code to match the comment.

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

Select * from table
where CONTAINS([Column], '"A00*"')  

will act as % same as

where [Column] Like 'A00%'

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

Another solution you can try that worked for me when I received this error is to clean the solution, then do a rebuild. As the other solutions did not help me, I thought this might help someone else in the same boat.

Execute a terminal command from a Cocoa app

Or since Objective C is just C with some OO layer on top you can use the posix conterparts:

int execl(const char *path, const char *arg0, ..., const char *argn, (char *)0);
int execle(const char *path, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
int execlp(const char *file, const char *arg0, ..., const char *argn, (char *)0);
int execlpe(const char *file, const char *arg0, ..., const char *argn, (char *)0, char *const envp[]);
int execv(const char *path, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]); 

They are included from unistd.h header file.

How to recover MySQL database from .myd, .myi, .frm files

Simple! Create a dummy database (say abc)

Copy all these .myd, .myi, .frm files to mysql\data\abc wherein mysql\data\ is the place where .myd, .myi, .frm for all databases are stored.

Then go to phpMyadmin, go to db abc and you find your database.

How to convert a char array to a string?

The string class has a constructor that takes a NULL-terminated C-string:

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

// or
str = arr;

How to load Spring Application Context

package com.dataload;

    public class insertCSV 
    {
        public static void main(String args[])
        {
            ApplicationContext context =
        new ClassPathXmlApplicationContext("applicationcontext.xml");


            // retrieve configured instance
            JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
            Job job = context.getBean("job", Job.class);
            JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
        }
    }

How do I change data-type of pandas data frame to string with a defined format?

I'm unable to reproduce your problem but have you tried converting it to an integer first?

image_name_data['id'] = image_name_data['id'].astype(int).astype('str')

Then, regarding your more general question you could use map (as in this answer). In your case:

image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)

PHP substring extraction. Get the string before the first '/' or the whole string

The function strstr() in PHP 5.3 should do this job.. The third parameter however should be set to true..

But if you're not using 5.3, then the function below should work accurately:

function strbstr( $str, $char, $start=0 ){
    if ( isset($str[ $start ]) && $str[$start]!=$char ){
        return $str[$start].strbstr( $str, $char, $start+1 );
    }
}

I haven't tested it though, but this should work just fine.. And it's pretty fast as well

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

php.ini:

xdebug.max_nesting_level = -1

I'm not entirely sure if the value will ever overflow and reach -1, but it'll either never reach -1, or it'll set the max_nesting_level pretty high.

Stop Excel from automatically converting certain text values to dates

I do this for credit card numbers which keep converting to scientific notation: I end up importing my .csv into Google Sheets. The import options now allow to disable automatic formatting of numeric values. I set any sensitive columns to Plain Text and download as xlsx.

It's a terrible workflow, but at least my values are left the way they should be.

How can I pass variable to ansible playbook in the command line?

Reading the docs I find the section Passing Variables On The Command Line, that gives this example:

ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"

Others examples demonstrate how to load from JSON string (=1.2) or file (=1.3)

How do I get HTTP Request body content in Laravel?

For those who are still getting blank response with $request->getContent(), you can use:

$request->all()

e.g:

public function foo(Request $request){
   $bodyContent = $request->all();
}

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

span with onclick event inside a tag

When you click on hide me, both a and span clicks are triggering. Since the page is redirecting to another, you cannot see the working of hide()

You can see this for more clarification

http://jsfiddle.net/jzn82/

Prevent Caching in ASP.NET MVC for specific actions using an attribute

Correct attribute value for Asp.Net MVC Core to prevent browser caching (including Internet Explorer 11) is:

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]

as described in Microsoft documentation:

Response caching in ASP.NET Core - NoStore and Location.None

What does "select 1 from" do?

The statement SELECT 1 FROM SomeTable just returns a column containing the value 1 for each row in your table. If you add another column in, e.g. SELECT 1, cust_name FROM SomeTable then it makes it a little clearer:

            cust_name
----------- ---------------
1           Village Toys
1           Kids Place
1           Fun4All
1           Fun4All
1           The Toy Store

Change size of text in text input tag?

To change the font size of the <input /> tag in HTML, use this:

<input style="font-size:20px" type="text" value="" />

It will create a text input box and the text inside the text box will be 20 pixels.

How to check Spark Version

Addition to @Binary Nerd

If you are using Spark, use the following to get the Spark version:

spark-submit --version

or

Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

.loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

ImportError: no module named win32api

According to pywin32 github you must run

    pip install pywin32

and after that, you must run

    python Scripts/pywin32_postinstall.py -install

I know I'm reviving an old thread, but I just had this problem and this was the only way to solve it.

Centering floating divs within another div

In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.

All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!

The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.

Ex.(each element has 2 sides so border, margin and padding get multiplied x2)

So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32

Then add all of your element's totaled widths together.

Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24

In this example the width for the "outer" div would be 112.

_x000D_
_x000D_
.outer {_x000D_
  /* floats + margins + borders = 270 */_x000D_
  max-width: 270px;_x000D_
  margin: auto;_x000D_
  height: 80px;_x000D_
  border: 1px;_x000D_
  border-style: solid;_x000D_
}_x000D_
_x000D_
.myFloat {_x000D_
    /* 3 floats x 50px = 150px */_x000D_
    width: 50px;_x000D_
    /* 6 margins x 10px = 60 */_x000D_
    margin: 10px;_x000D_
    /* 6 borders x 10px = 60 */_x000D_
    border: 10px solid #6B6B6B;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    height: 40px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="myFloat">Float 1</div>_x000D_
  <div class="myFloat">Float 2</div>_x000D_
  <div class="myFloat">Float 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Switch tabs using Selenium WebDriver with Java

Set<String> tabs = driver.getWindowHandles();
Iterator<String> it = tabs.iterator();
tab1 = it.next();
tab2 = it.next();
driver.switchTo().window(tab1);
driver.close();
driver.switchTo().window(tab2);

Try this. It should work

how to set select element as readonly ('disabled' doesnt pass select value on server)

To be able to pass the select, I just set it back to :

  $('#selectID').prop('disabled',false);

or

  $('#selectID').attr('disabled',false);

when passing the request.

How do I exit a while loop in Java?

Take a look at the Java™ Tutorials by Oracle.

But basically, as dacwe said, use break.

If you can it is often clearer to avoid using break and put the check as a condition of the while loop, or using something like a do while loop. This isn't always possible though.

'this' implicitly has type 'any' because it does not have a type annotation

The error is indeed fixed by inserting this with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:

foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS

It should've been this:

foo.on('error', function(this: Foo, err: any) {

or this:

foo.on('error', function(this: typeof foo, err: any) {

A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this and arrow-functions.

How to install and run Typescript locally in npm?

tsc requires a config file or .ts(x) files to compile.

To solve both of your issues, create a file called tsconfig.json with the following contents:

{
    "compilerOptions": {
        "outFile": "../../built/local/tsc.js"
    },
    "exclude": [
        "node_modules"
    ]
}

Also, modify your npm run with this

tsc --config /path/to/a/tsconfig.json

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

What is the difference between “int” and “uint” / “long” and “ulong”?

uint and ulong are the unsigned versions of int and long. That means they can't be negative. Instead they have a larger maximum value.

Type    Min                           Max                           CLS-compliant
int     -2,147,483,648                2,147,483,647                 Yes
uint    0                             4,294,967,295                 No
long    –9,223,372,036,854,775,808    9,223,372,036,854,775,807     Yes
ulong   0                             18,446,744,073,709,551,615    No

To write a literal unsigned int in your source code you can use the suffix u or U for example 123U.

You should not use uint and ulong in your public interface if you wish to be CLS-Compliant.

Read the documentation for more information:

By the way, there is also short and ushort and byte and sbyte.

How can I pass a username/password in the header to a SOAP WCF Service

There is probably a smarter way, but you can add the headers manually like this:

var client = new IdentityProofingService.IdentityProofingWSClient();

using (new OperationContextScope(client.InnerChannel))
{
    OperationContext.Current.OutgoingMessageHeaders.Add(
        new SecurityHeader("UsernameToken-49", "12345/userID", "password123"));
    client.invokeIdentityService(new IdentityProofingRequest());
}

Here, SecurityHeader is a custom implemented class, which needs a few other classes since I chose to use attributes to configure the XML serialization:

public class SecurityHeader : MessageHeader
{
    private readonly UsernameToken _usernameToken;

    public SecurityHeader(string id, string username, string password)
    {
        _usernameToken = new UsernameToken(id, username, password);
    }

    public override string Name
    {
        get { return "Security"; }
    }

    public override string Namespace
    {
        get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
    }

    protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(UsernameToken));
        serializer.Serialize(writer, _usernameToken);
    }
}


[XmlRoot(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")]
public class UsernameToken
{
    public UsernameToken()
    {
    }

    public UsernameToken(string id, string username, string password)
    {
        Id = id;
        Username = username;
        Password = new Password() {Value = password};
    }

    [XmlAttribute(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")]
    public string Id { get; set; }

    [XmlElement]
    public string Username { get; set; }

    [XmlElement]
    public Password Password { get; set; }
}

public class Password
{
    public Password()
    {
        Type = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";
    }

    [XmlAttribute]
    public string Type { get; set; }

    [XmlText]
    public string Value { get; set; }
}

I have not added the Nonce bit to the UsernameToken XML, but it is very similar to the Password one. The Created element also needs to be added still, but it's a simple [XmlElement].

Uri not Absolute exception getting while calling Restful Webservice

The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.

Disable/Enable button in Excel/VBA

This is working for me (Excel 2016) with a new ActiveX button, assign a control to you button and you're all set.

Sub deactivate_buttons()

     ActiveSheet.Shapes.Item("CommandButton1").ControlFormat.Enabled = False

End Sub

It changes the "Enabled" property in the ActiveX button Properties box to False and the button becomes inactive and greyed out.

Converting HTML to Excel?

So long as Excel can open the file, the functionality to change the format of the opened file is built in.

To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).

To do it using VBA, the code would look like this:

Sub Open_HTML_Save_XLSX()

    Workbooks.Open Filename:="C:\Temp\Example.html"
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Temp\Example.xlsx", FileFormat:= _
        xlOpenXMLWorkbook

End Sub

Removing u in list

For python datasets you can use an index.

tmpColumnsSQL = ("show columns in dim.date_dim")
hiveCursor.execute(tmpColumnsSQL)
columnlist = hiveCursor.fetchall()

for columns in jayscolumnlist:
    print columns[0]

for i in range(len(jayscolumnlist)):    
    print columns[i][0])

Use multiple custom fonts using @font-face?

You simply add another @font-face rule:

@font-face {
    font-family: CustomFont;
    src: url('CustomFont.ttf');
}

@font-face {
    font-family: CustomFont2;
    src: url('CustomFont2.ttf');
}

If your second font still doesn't work, make sure you're spelling its typeface name and its file name correctly, your browser caches are behaving, your OS isn't messing around with a font of the same name, etc.

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

Because python checks in the directories in sequential order starting at the first directory in sys.path list, till it find the .py file it was looking for.

Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

So, most probably, you had a .py file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).

Also, a thing to note about ImportErrors , lets say the import error says - ImportError: No module named main - it doesn't mean the main.py is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py or some other file.

Example -

My directory structure looks like -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py

Now From testmain.py , I call from shared import phtest , it works fine.

Now lets say I introduce a shared.py in test directory` , example -

 - test
    - shared
         - __init__.py
         - phtest.py
  - testmain.py 
  - shared.py

Now when I try to do from shared import phtest from testmain.py , I will get the error -

ImportError: cannot import name 'phtest'

As you can see above, the file that is causing the issue is shared.py , not phtest.py .

Make a phone call programmatically

Tried the Swift 3 option above, but it didnt work. I think you need the following if you are to run against iOS 10+ on Swift 3:

Swift 3 (iOS 10+):

let phoneNumber = mymobileNO.titleLabel.text       
UIApplication.shared.open(URL(string: phoneNumber)!, options: [:], completionHandler: nil)

Javadoc link to method in other class

So the solution to the original problem is that you don't need both the "@see" and the "{@link...}" references on the same line. The "@link" tag is self-sufficient and, as noted, you can put it anywhere in the javadoc block. So you can mix the two approaches:

/**
 * some javadoc stuff
 * {@link com.my.package.Class#method()}
 * more stuff
 * @see com.my.package.AnotherClass
 */

Adding a directory to the PATH environment variable in Windows

In a command prompt you tell Cmd to use Windows Explorer's command line by prefacing it with start.

So start Yourbatchname.

Note you have to register as if its name is batchfile.exe.

Programs and documents can be added to the registry so typing their name without their path in the Start - Run dialog box or shortcut enables Windows to find them.

This is a generic reg file. Copy the lines below to a new Text Document and save it as anyname.reg. Edit it with your programs or documents.

In paths, use \\ to separate folder names in key paths as regedit uses a single \ to separate its key names. All reg files start with REGEDIT4. A semicolon turns a line into a comment. The @ symbol means to assign the value to the key rather than a named value.

The file doesn't have to exist. This can be used to set Word.exe to open Winword.exe.

Typing start batchfile will start iexplore.exe.

REGEDIT4
;The bolded name below is the name of the document or program, <filename>.<file extension>

[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\Batchfile.exe]

; The @ means the path to the file is assigned to the default value for the key.
; The whole path in enclosed in a quotation mark ".

@="\"C:\\Program Files\\Internet Explorer\\iexplore.exe\""

; Optional Parameters. The semicolon means don't process the line. Remove it if you want to put it in the registry

; Informs the shell that the program accepts URLs.

;"useURL"="1"

; Sets the path that a program will use as its' default directory. This is commented out.

;"Path"="C:\\Program Files\\Microsoft Office\\Office\\"

You've already been told about path in another answer. Also see doskey /? for cmd macros (they only work when typing).

You can run startup commands for CMD. From Windows Resource Kit Technical Reference

AutoRun

HKCU\Software\Microsoft\Command Processor

Data type Range Default value
REG_SZ  list of commands  There is no default value for this entry.

Description

Contains commands which are executed each time you start Cmd.exe.

How to convert a boolean array to an int array

The 1*y method works in Numpy too:

>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False,  True,  True], dtype=bool)
>>> 1*y                      # Method 1
array([0, 0, 1, 1])
>>> y.astype(int)            # Method 2
array([0, 0, 1, 1]) 

If you are asking for a way to convert Python lists from Boolean to int, you can use map to do it:

>>> testList = [False, False,  True,  True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]

Or using list comprehensions:

>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]

Curl command without using cache

I know this is an older question, but I wanted to post an answer for users with the same question:

curl -H 'Cache-Control: no-cache' http://www.example.com

This curl command servers in its header request to return non-cached data from the web server.

Setting width/height as percentage minus pixels

You can use calc:

height: calc(100% - 18px);

Note that some old browsers don't support the CSS3 calc() function, so implementing the vendor-specific versions of the function may be required:

/* Firefox */
height: -moz-calc(100% - 18px);
/* WebKit */
height: -webkit-calc(100% - 18px);
/* Opera */
height: -o-calc(100% - 18px);
/* Standard */
height: calc(100% - 18px);

Key Presses in Python

PyAutoGui also lets you press a button multiple times:

pyautogui.press('tab', presses=5)   # press TAB five times in a row

pyautogui.press('A', presses=1000)   # press A a thousand times in a row

Is it possible to embed animated GIFs in PDFs?

It's not really possible. You could, but if you're going to it would be useless without appropriate plugins. You'd be better using some other form. PDF's are used to have a consolidated output to printers and the screen, so animations won't work without other resources, and then it's not really a PDF.

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

This worked for me

<p:column headerText="name" style="width:20px;"/>

Write applications in C or C++ for Android?

Take a look at google ndk group it looks promising, first version of the NDK will be available in 1H2009.

Update: And it is released http://android-developers.blogspot.com/2009/06/introducing-android-15-ndk-release-1.html

Writing List of Strings to Excel CSV File in Python

Very simple to fix, you just need to turn the parameter to writerow into a list.

for item in RESULTS:
     wr.writerow([item,])

Determine Pixel Length of String in Javascript/jQuery?

First replicate the location and styling of the text and then use Jquery width() function. This will make the measurements accurate. For example you have css styling with a selector of:

.style-head span
{
  //Some style set
}

You would need to do this with Jquery already included above this script:

var measuringSpan = document.createElement("span");
measuringSpan.innerText = 'text to measure';
measuringSpan.style.display = 'none'; /*so you don't show that you are measuring*/
$('.style-head')[0].appendChild(measuringSpan);
var theWidthYouWant = $(measuringSpan).width();

Needless to say

theWidthYouWant

will hold the pixel length. Then remove the created elements after you are done or you will get several if this is done a several times. Or add an ID to reference instead.

UIView background color in Swift

self.view.backgroundColor = UIColor.redColor()

In Swift 3:

self.view.backgroundColor = UIColor.red

How do I clone a Django model instance object and save it to the database?

To clone a model with multiple inheritance levels, i.e. >= 2, or ModelC below

class ModelA(models.Model):
    info1 = models.CharField(max_length=64)

class ModelB(ModelA):
    info2 = models.CharField(max_length=64)

class ModelC(ModelB):
    info3 = models.CharField(max_length=64)

Please refer the question here.

What are forward declarations in C++?

One problem is, that the compiler does not know, which kind of value is delivered by your function; is assumes, that the function returns an int in this case, but this can be as correct as it can be wrong. Another problem is, that the compiler does not know, which kind of arguments your function expects, and cannot warn you, if you are passing values of the wrong kind. There are special "promotion" rules, which apply when passing, say floating point values to an undeclared function (the compiler has to widen them to type double), which is often not, what the function actually expects, leading to hard to find bugs at run-time.

ImportError: No module named 'Queue'

It's because of the Python version. In Python 3 it's import Queue as queue; on the contrary in Python 2.x it's import queue. If you want it for both environments you may use something below as mentioned here

try:
   import queue
except ImportError:
   import Queue as queue

How to set delay in android?

Using the Thread.sleep(millis) method.

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

Can you use if/else conditions in CSS?

I am surprised that nobody has mentioned CSS pseudo-classes, which are also a sort-of conditionals in CSS. You can do some pretty advanced things with this, without a single line of JavaScript.

Some pseudo-classes:

  • :active - Is the element being clicked?
  • :checked - Is the radio/checkbox/option checked? (This allows for conditional styling through the use of a checkbox!)
  • :empty - Is the element empty?
  • :fullscreen - Is the document in full-screen mode?
  • :focus - Does the element have keyboard focus?
  • :focus-within - Does the element, or any of its children, have keyboard focus?
  • :has([selector]) - Does the element contain a child that matches [selector]? (Sadly, not supported by any of the major browsers.)
  • :hover - Does the mouse hover over this element?
  • :in-range/:out-of-range - Is the input value between/outside min and max limits?
  • :invalid/:valid - Does the form element have invalid/valid contents?
  • :link - Is this an unvisited link?
  • :not() - Invert the selector.
  • :target - Is this element the target of the URL fragment?
  • :visited - Has the user visited this link before?

Example:

_x000D_
_x000D_
div { color: white; background: red }_x000D_
input:checked + div { background: green }
_x000D_
<input type=checkbox>Click me!_x000D_
<div>Red or green?</div>
_x000D_
_x000D_
_x000D_

catch specific HTTP error in python

Tims answer seems to me as misleading. Especially when urllib2 does not return expected code. For example this Error will be fatal (believe or not - it is not uncommon one when downloading urls):

AttributeError: 'URLError' object has no attribute 'code'

Fast, but maybe not the best solution would be code using nested try/except block:

import urllib2
try:
    urllib2.urlopen("some url")
except urllib2.HTTPError, err:
    try:
        if err.code == 404:
            # Handle the error
        else:
            raise
    except:
        ...

More information to the topic of nested try/except blocks Are nested try/except blocks in python a good programming practice?

How to print a double with two decimals in Android?

use this one:

DecimalFormat form = new DecimalFormat("0.00");
etToll.setText(form.format(tvTotalAmount) );

Note: Data must be in decimal format (tvTotalAmount)

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

I was getting this error too, although my issue was that I kept switching between two corporate networks via my Virtual Machine, with different access credentials. I had to run the command prompt:

ipconfig /renew

After this my network issues were resolved and I could connect once again to SQL.

Exit Shell Script Based on Process Exit Code

#
#------------------------------------------------------------------------------
# purpose: to run a command, log cmd output, exit on error
# usage:
# set -e; do_run_cmd_or_exit "$cmd" ; set +e
#------------------------------------------------------------------------------
do_run_cmd_or_exit(){
    cmd="$@" ;

    do_log "DEBUG running cmd or exit: \"$cmd\""
    msg=$($cmd 2>&1)
    export exit_code=$?

    # If occurred during the execution, exit with error
    error_msg="Failed to run the command:
        \"$cmd\" with the output:
        \"$msg\" !!!"

    if [ $exit_code -ne 0 ] ; then
        do_log "ERROR $msg"
        do_log "FATAL $msg"
        do_exit "$exit_code" "$error_msg"
    else
        # If no errors occurred, just log the message
        do_log "DEBUG : cmdoutput : \"$msg\""
    fi

}

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

various option are available such as:

 Double d= 123.12;
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64); // b = 123.1200000
b = b.setScale(2, BigDecimal.ROUND_HALF_UP);  // b = 123.12

BigDecimal b1 =new BigDecimal(collectionFileData.getAmount(), MathContext.DECIMAL64).setScale(2, BigDecimal.ROUND_HALF_UP)  // b1= 123.12

 d = (double) Math.round(d * 100) / 100;
BigDecimal b2 = new BigDecimal(d.toString());  // b2= 123.12



Right query to get the current number of connections in a PostgreSQL DB

Aggregation of all postgres sessions per their status (how many are idle, how many doing something...)

select state, count(*) from pg_stat_activity  where pid <> pg_backend_pid() group by 1 order by 1;

Combine :after with :hover

in scss

&::after{
content: url(images/RelativeProjectsArr.png);
margin-left:30px;
}

&:hover{
    background-color:$turkiz;
    color:#e5e7ef;

    &::after{
    content: url(images/RelativeProjectsArrHover.png);
    }
}

WSDL validator?

If you're using Eclipse, just have your WSDL in a .wsdl file, eclipse will validate it automatically.

From the Doc

The WSDL validator handles validation according to the 4 step process defined above. Steps 1 and 2 are both delegated to Apache Xerces (and XML parser). Step 3 is handled by the WSDL validator and any extension namespace validators (more on extensions below). Step 4 is handled by any declared custom validators (more on this below as well). Each step must pass in order for the next step to run.

Android selector & text color

In order to make it work on selection in a list view use the following code:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#fff"/>
    <item android:state_activated="true" android:color="#fff"/>
    <item android:color="#000" />
</selector>

Apparently the key is state_activated="true" state.

how to remove only one style property with jquery

The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

Since your styles are inline, you can write:

$(selector).css("-moz-user-select", "");

javascript filter array of objects

You can do this very easily with the [].filter method:

var filterednames = names.filter(function(obj) {
    return (obj.name === "Joe") && (obj.age < 30);
});

You will need to add a shim for browsers that don't support the [].filter method: this MDN page gives such code.

How can I access getSupportFragmentManager() in a fragment?

do this in your fragment

getActivity().getSupportFragmentManager()

How to move table from one tablespace to another in oracle 11g

I tried many scripts but they didn't work for all objects. You can't move clustered objects from one tablespace to another. For that you will have to use expdp, so I will suggest expdp is the best option to move all objects to a different tablespace.

Below is the command:

nohup expdp \"/ as sysdba\" DIRECTORY=test_dir DUMPFILE=users.dmp LOGFILE=users.log TABLESPACES=USERS &

You can check this link for details.

Using PowerShell credentials without being prompted for a password

why dont you try something very simple?

use psexec with command 'shutdown /r /f /t 0' and a PC list from CMD.

Setting a spinner onClickListener() in Android

The following works how you want it, but it is not ideal.

public class Tester extends Activity {

    String[] vals = { "here", "are", "some", "values" };
    Spinner spinner;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        spinner = (Spinner) findViewById(R.id.spin);
        ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, vals);
        spinner.setAdapter(ad);
        Log.i("", "" + spinner.getChildCount());
        Timer t = new Timer();
        t.schedule(new TimerTask() {

            @Override
            public void run() {
                int a = spinner.getCount();
                int b = spinner.getChildCount();
                System.out.println("Count =" + a);
                System.out.println("ChildCount =" + b);
                for (int i = 0; i < b; i++) {
                    View v = spinner.getChildAt(i);
                    if (v == null) {
                        System.out.println("View not found");
                    } else {
                        v.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                        Log.i("","click");
                                        }
                        });
                    }
                }
            }
        }, 500);
    }
}

Let me know exactly how you need the spinner to behave, and we can work out a better solution.

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

Could not resolve Spring property placeholder

You may have more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer in your application. Try setting a breakpoint on the setLocations method of the superclass and see if it's called more than once at application startup. If there is more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer, you might need to look at configuring the ignoreUnresolvablePlaceholders property so that your application will start up cleanly.

Configuration with name 'default' not found. Android Studio

Step.1 $ git submodule update

Step.2 To be commented out the dependences of classpass

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Rather than using Absolute path for IEDriverServer.exe, its better to use relative path in accordance to the project.

        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
        File fil = new File("iDrivers\\IEDriverServer.exe");
        System.setProperty("webdriver.ie.driver", fil.getAbsolutePath());
        WebDriver driver = new InternetExplorerDriver(capabilities);        
        driver.get("https://www.irctc.co.in");          

Go to "next" iteration in JavaScript forEach loop

You can simply return if you want to skip the current iteration.

Since you're in a function, if you return before doing anything else, then you have effectively skipped execution of the code below the return statement.

Gradle build without tests

Using -x test skip test execution but this also exclude test code compilation.

gradle build -x test 

In our case, we have a CI/CD process where one goal is compilation and next goal is testing (Build -> Test).

So, for our first Build goal we wanted to ensure that the whole project compiles well. For this we have used:

./gradlew build testClasses -x test

On the next goal we simply execute tests.

How to use a variable from a cursor in the select statement of another cursor in pl/sql

Use alter session set current_schema = <username>, in your case as an execute immediate.

See Oracle's documentation for further information.

In your case, that would probably boil down to (untested)

DECLARE

   CURSOR client_cur IS
     SELECT  distinct username 
       from all_users 
      where length(username) = 3;

   -- client cursor 
   CURSOR emails_cur IS
   SELECT id, name 
     FROM org;

BEGIN

   FOR client IN client_cur LOOP

   -- ****
      execute immediate 
     'alter session set current_schema = ' || client.username;
   -- ****

      FOR email_rec in client_cur LOOP

         dbms_output.put_line(
             'Org id is ' || email_rec.id || 
             ' org nam '  || email_rec.name);

      END LOOP;

  END LOOP;
END;
/

What does it mean when a PostgreSQL process is "idle in transaction"?

The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.

If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.

Pretty Printing JSON with React

const getJsonIndented = (obj) => JSON.stringify(newObj, null, 4).replace(/["{[,\}\]]/g, "")

const JSONDisplayer = ({children}) => (
    <div>
        <pre>{getJsonIndented(children)}</pre>
    </div>
)

Then you can easily use it:

const Demo = (props) => {
   ....
   return <JSONDisplayer>{someObj}<JSONDisplayer>
}

How to getText on an input in protractor

You can try something like this

var access_token = driver.findElement(webdriver.By.name("AccToken"))

        var access_token_getTextFunction = function() {
            access_token.getText().then(function(value) {
                console.log(value);
                return value;
            });
        }

Than you can call this function where you want to get the value..

How to assign colors to categorical variables in ggplot2 that have stable mapping?

For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are not all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.

One way to address this is to create a custom manual colour scale as follows:

#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
        grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)

#Create a custom color scale
library(RColorBrewer)
myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(dat$grp)
colScale <- scale_colour_manual(name = "grp",values = myColors)

and then add the color scale onto the plot as needed:

#One plot with all the data
p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
p1 <- p + colScale

#A second plot with only four of the levels
p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale

The first plot looks like this:

enter image description here

and the second plot looks like this:

enter image description here

This way you don't need to remember or check each data frame to see that they have the appropriate levels.

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

try this

echo $sqlupdate1 = "UPDATE table SET commodity_quantity=$qty WHERE user='".$rows['user']."' ";

Expand a div to fill the remaining width

Thanks for the plug of Simpl.css!

remember to wrap all your columns in ColumnWrapper like so.

<div class="ColumnWrapper">
    <div class="Colum­nOne­Half">Tree</div>
    <div class="Colum­nOne­Half">View</div>
</div>

I am about to release version 1.0 of Simpl.css so help spread the word!

How do I get the function name inside a function in PHP?

You can use the magic constants __METHOD__ (includes the class name) or __FUNCTION__ (just function name) depending on if it's a method or a function... =)

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

Just add these to libraries to your project:

<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"></link>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>

Save and reload. You're good to go.

Disable cache for some images

I checked all the answers and the best one seemed to be (which isn't):

<img src="image.png?cache=none">

at first.

However, if you add cache=none parameter (which is static "none" word), it doesn't effect anything, browser still loads from cache.

Solution to this problem was:

<img src="image.png?nocache=<?php echo time(); ?>">

where you basically add unix timestamp to make the parameter dynamic and no cache, it worked.

However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change.

To solve this problem, I needed to hash $_GET but since it is array here is the solution:

$chart_hash = md5(implode('-', $_GET));
echo "<img src='/images/mychart.png?hash=$chart_hash'>";

Edit:

Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use:

echo "<img src='/images/mychart.png?hash=" . filemtime('mychart.png') . "'>";

filemtime() gets file modification time.

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

our problem was that the hard drive was down to zero space available.

Loop timer in JavaScript

Here the Automatic loop function with html code. I hope this may be useful for someone.

<!DOCTYPE html>
<html>
<head>
<style>
div {
position: relative;
background-color: #abc;
width: 40px;
height: 40px;
float: left;
margin: 5px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p><button id="go">Run »</button></p>
<div class="block"></div>
<script>

function test() {
$(".block").animate({left: "+=50", opacity: 1}, 500 );
   setTimeout(mycode, 2000);
};
$( "#go" ).click(function(){
test();
});
</script>
</body>
</html>

Fiddle: DEMO

SQL changing a value to upper or lower case

SELECT UPPER(firstname) FROM Person

SELECT LOWER(firstname) FROM Person

How to convert an int to string in C?

The short answer is:

snprintf( str, size, "%d", x );

The longer is: first you need to find out sufficient size. snprintf tells you length if you call it with NULL, 0 as first parameters:

snprintf( NULL, 0, "%d", x );

Allocate one character more for null-terminator.

#include <stdio.h> 
#include <stdlib.h>

int x = -42;
int length = snprintf( NULL, 0, "%d", x );
char* str = malloc( length + 1 );
snprintf( str, length + 1, "%d", x );
...
free(str);

If works for every format string, so you can convert float or double to string by using "%g", you can convert int to hex using "%x", and so on.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

I just needed to parse a nested dictionary, like

{
    "x": {
        "a": 1,
        "b": 2,
        "c": 3
    }
}

where JsonConvert.DeserializeObject doesn't help. I found the following approach:

var dict = JObject.Parse(json).SelectToken("x").ToObject<Dictionary<string, int>>();

The SelectToken lets you dig down to the desired field. You can even specify a path like "x.y.z" to step further down into the JSON object.

How do you change Background for a Button MouseOver in WPF?

To remove the default MouseOver behaviour on the Button you will need to modify the ControlTemplate. Changing your Style definition to the following should do the trick:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Green"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

EDIT: It's a few years late, but you are actually able to set the border brush inside of the border that is in there. Idk if that was pointed out but it doesn't seem like it was...

Best way to script remote SSH commands in Batch (Windows)

As an alternative option you could install OpenSSH http://www.mls-software.com/opensshd.html and then simply ssh user@host -pw password -m command_run

Edit: After a response from user2687375 when installing, select client only. Once this is done you should be able to initiate SSH from command.

Then you can create an ssh batch script such as

ECHO OFF
CLS
:MENU
ECHO.
ECHO ........................
ECHO SSH servers
ECHO ........................
ECHO.
ECHO 1 - Web Server 1
ECHO 2 - Web Server 2
ECHO E - EXIT
ECHO.

SET /P M=Type 1 - 2 then press ENTER:
IF %M%==1 GOTO WEB1
IF %M%==2 GOTO WEB2
IF %M%==E GOTO EOF

REM ------------------------------
REM SSH Server details
REM ------------------------------

:WEB1
CLS
call ssh [email protected]
cmd /k

:WEB2
CLS
call ssh [email protected]
cmd /k

Static methods - How to call a method from another method?

You can’t call non-static methods from static methods, but by creating an instance inside the static method.

It should work like that

class test2(object):
    def __init__(self):
        pass

    @staticmethod
    def dosomething():
        print "do something"
        # Creating an instance to be able to
        # call dosomethingelse(), or you
        # may use any existing instance
        a = test2()
        a.dosomethingelse()

    def dosomethingelse(self):
        print "do something else"

test2.dosomething()

Change URL without refresh the page

Update

Based on Manipulating the browser history, passing the empty string as second parameter of pushState method (aka title) should be safe against future changes to the method, so it's better to use pushState like this:

history.pushState(null, '', '/en/step2');    

You can read more about that in mentioned article

Original Answer

Use history.pushState like this:

history.pushState(null, null, '/en/step2');

Update 2 to answer Idan Dagan's comment:

Why not using history.replaceState()?

From MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

That means if you use replaceState, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState doesn't add new entry to history) and it's not recommended and provide bad UX.

Update 3 to add window.onpopstate

So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState, you can detect the back/forward button navigation by using window.onpopstate like this:

window.onpopstate = function(e) {
    // ... 
};

As the first argument of pushState is an object, if you passed an object instead of null, you can access that object in onpopstate which is very handy, here is how:

window.onpopstate = function(e) {
    if(e.state) {
        console.log(e.state);
    }
};

Update 4 to add Reading the current state:

When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate event using the history.state property like this:

console.log(history.state);

Bonus: Use following to check history.pushState support:

if (history.pushState) {
  // \o/
}

Make TextBox uneditable

Just set in XAML:

        <TextBox IsReadOnly="True" Style="{x:Null}" />

So that text will not be grayed-out.

How can I find all *.js file in directory recursively in Linux?

Use find on the command line:

find /my/directory -name '*.js'

When do we need curly braces around shell variables?

Curly braces are always needed for accessing array elements and carrying out brace expansion.

It's good to be not over-cautious and use {} for shell variable expansion even when there is no scope for ambiguity.

For example:

dir=log
prog=foo
path=/var/${dir}/${prog}      # excessive use of {}, not needed since / can't be a part of a shell variable name
logfile=${path}/${prog}.log   # same as above, . can't be a part of a shell variable name
path_copy=${path}             # {} is totally unnecessary
archive=${logfile}_arch       # {} is needed since _ can be a part of shell variable name

So, it is better to write the three lines as:

path=/var/$dir/$prog
logfile=$path/$prog.log
path_copy=$path

which is definitely more readable.

Since a variable name can't start with a digit, shell doesn't need {} around numbered variables (like $1, $2 etc.) unless such expansion is followed by a digit. That's too subtle and it does make to explicitly use {} in such contexts:

set app      # set $1 to app
fruit=$1le   # sets fruit to apple, but confusing
fruit=${1}le # sets fruit to apple, makes the intention clear

See:

How to work offline with TFS

There are couple of little visual studio extensions for this purpose:

  1. For VS2010 & TFS 2010, try this
  2. For VS2012 & TFS 2010, use this

In case of TFS 2012, looks like there is no need for 'Go offline' extensions. I read something about a new feature called local workspace for the similar purpose.

Alternatively I had good success with Git-TF. All the goodness of git and when you are ready, you can push it to TFS.

Eclipse "Invalid Project Description" when creating new project from existing source

I got rid of my issue by changing File > Workspace and then, after the restart, reset the Workspace again.

Extract XML Value in bash script

I agree with Charles Duffy that a proper XML parser is the right way to go.

But as to what's wrong with your sed command (or did you do it on purpose?).

  • $data was not quoted, so $data is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.

So given your specific XML structure, this modified sed command should work

title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")

Basically for the line that contains title, extract the text between the tags, then quit (so you don't extract the 2nd <title>)

Formatting PowerShell Get-Date inside string

You can use the -f operator

$a = "{0:D}" -f (get-date)
$a = "{0:dddd}" -f (get-date)

Spécificator    Type                                Example (with [datetime]::now)
d   Short date                                        26/09/2002
D   Long date                                       jeudi 26 septembre 2002
t   Short Hour                                      16:49
T   Long Hour                                       16:49:31
f   Date and hour                                   jeudi 26 septembre 2002 16:50
F   Long Date and hour                              jeudi 26 septembre 2002 16:50:51
g   Default Date                                    26/09/2002 16:52
G   Long default Date and hour                      26/09/2009 16:52:12
M   Month Symbol                                    26 septembre
r   Date string RFC1123                             Sat, 26 Sep 2009 16:54:50 GMT
s   Sortable string date                            2009-09-26T16:55:58
u   Sortable string date universal local hour       2009-09-26 16:56:49Z
U   Sortable string date universal GMT hour         samedi 26 septembre 2009 14:57:22 (oups)
Y   Year symbol                                     septembre 2002

Spécificator    Type                       Example      Output Example
dd              Jour                       {0:dd}       10
ddd             Name of the day            {0:ddd}      Jeu.
dddd            Complet name of the day    {0:dddd}     Jeudi
f, ff, …        Fractions of seconds       {0:fff}      932
gg, …           position                   {0:gg}       ap. J.-C.
hh              Hour two digits            {0:hh}       10
HH              Hour two digits (24 hours) {0:HH}       22
mm              Minuts 00-59               {0:mm}       38
MM              Month 01-12                {0:MM}       12
MMM             Month shortcut             {0:MMM}      Sep.
MMMM            complet name of the month  {0:MMMM}     Septembre
ss              Seconds 00-59              {0:ss}       46
tt              AM or PM                   {0:tt}       ““
yy              Years, 2 digits            {0:yy}       02
yyyy            Years                      {0:yyyy}     2002
zz              Time zone, 2 digits        {0:zz}       +02
zzz             Complete Time zone         {0:zzz}      +02:00
:               Separator                  {0:hh:mm:ss}     10:43:20
/               Separator                  {0:dd/MM/yyyy}   10/12/2002

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The min sdk version is the earliest release of the Android SDK that your application can run on. Usually this is because of a problem with the earlier APIs, lacking functionality, or some other behavioural issue.

The target sdk version is the version your application was targeted to run on. Ideally, this is because of some sort of optimal run conditions. If you were to "make your app for version 19", this is where that would be specified. It may run on earlier or later releases, but this is what you were aiming for. This is mostly to indicate how current your application is for use in the marketplace, etc.

The compile sdk version is the version of android your IDE (or other means of compiling I suppose) uses to make your app when you publish a .apk file. This is useful for testing your application as it is a common need to compile your app as you develop it. As this will be the version to compile to an APK, it will naturally be the version of your release. Likewise, it is advisable to have this match your target sdk version.

How to customize an end time for a YouTube video?

I just found out that the following works:

https://www.youtube.com/embed/[video_id]?start=[start_at_second]&end=[end_at_second]

Note: the time must be an integer number of seconds (e.g. 119, not 1m59s).

Passing a variable to a powershell script via command line

Passed parameter like below,

Param([parameter(Mandatory=$true,
   HelpMessage="Enter name and key values")]
   $Name,
   $Key)

.\script_name.ps1 -Name name -Key key

Angularjs how to upload multipart form data and a file?

First of all

  1. You don't need any special changes in the structure. I mean: html input tags.

_x000D_
_x000D_
<input accept="image/*" name="file" ng-value="fileToUpload"_x000D_
       value="{{fileToUpload}}" file-model="fileToUpload"_x000D_
       set-file-data="fileToUpload = value;" _x000D_
       type="file" id="my_file" />
_x000D_
_x000D_
_x000D_

1.2 create own directive,

_x000D_
_x000D_
.directive("fileModel",function() {_x000D_
 return {_x000D_
  restrict: 'EA',_x000D_
  scope: {_x000D_
   setFileData: "&"_x000D_
  },_x000D_
  link: function(scope, ele, attrs) {_x000D_
   ele.on('change', function() {_x000D_
    scope.$apply(function() {_x000D_
     var val = ele[0].files[0];_x000D_
     scope.setFileData({ value: val });_x000D_
    });_x000D_
   });_x000D_
  }_x000D_
 }_x000D_
})
_x000D_
_x000D_
_x000D_

  1. In module with $httpProvider add dependency like ( Accept, Content-Type etc) with multipart/form-data. (Suggestion would be, accept response in json format) For e.g:

$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';

  1. Then create separate function in controller to handle form submit call. like for e.g below code:

  2. In service function handle "responseType" param purposely so that server should not throw "byteerror".

  3. transformRequest, to modify request format with attached identity.

  4. withCredentials : false, for HTTP authentication information.

_x000D_
_x000D_
in controller:_x000D_
_x000D_
  // code this accordingly, so that your file object _x000D_
  // will be picked up in service call below._x000D_
  fileUpload.uploadFileToUrl(file); _x000D_
_x000D_
_x000D_
in service:_x000D_
_x000D_
  .service('fileUpload', ['$http', 'ajaxService',_x000D_
    function($http, ajaxService) {_x000D_
_x000D_
      this.uploadFileToUrl = function(data) {_x000D_
        var data = {}; //file object _x000D_
_x000D_
        var fd = new FormData();_x000D_
        fd.append('file', data.file);_x000D_
_x000D_
        $http.post("endpoint server path to whom sending file", fd, {_x000D_
            withCredentials: false,_x000D_
            headers: {_x000D_
              'Content-Type': undefined_x000D_
            },_x000D_
            transformRequest: angular.identity,_x000D_
            params: {_x000D_
              fd_x000D_
            },_x000D_
            responseType: "arraybuffer"_x000D_
          })_x000D_
          .then(function(response) {_x000D_
            var data = response.data;_x000D_
            var status = response.status;_x000D_
            console.log(data);_x000D_
_x000D_
            if (status == 200 || status == 202) //do whatever in success_x000D_
            else // handle error in  else if needed _x000D_
          })_x000D_
          .catch(function(error) {_x000D_
            console.log(error.status);_x000D_
_x000D_
            // handle else calls_x000D_
          });_x000D_
      }_x000D_
    }_x000D_
  }])
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
_x000D_
_x000D_
_x000D_

Is there an equivalent for var_dump (PHP) in Javascript?

If you use Firebug, you can use console.log to output an object and get a hyperlinked, explorable item in the console.

Can Python test the membership of multiple values in a list?

If you want to check all of your input matches,

>>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])

if you want to check at least one match,

>>> any(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])

Setting the number of map tasks and reduce tasks

The first part has already been answered, "just a suggestion" The second part has also been answered, "remove extra spaces around =" If both these didnt work, are you sure you have implemented ToolRunner ?

How to catch integer(0)?

Inspired by Andrie's answer, you could use identical and avoid any attribute problems by using the fact that it is the empty set of that class of object and combine it with an element of that class:

attr(a, "foo") <- "bar"

identical(1L, c(a, 1L))
#> [1] TRUE

Or more generally:

is.empty <- function(x, mode = NULL){
    if (is.null(mode)) mode <- class(x)
    identical(vector(mode, 1), c(x, vector(class(x), 1)))
}

b <- numeric(0)

is.empty(a)
#> [1] TRUE
is.empty(a,"numeric")
#> [1] FALSE
is.empty(b)
#> [1] TRUE
is.empty(b,"integer")
#> [1] FALSE

DateDiff to output hours and minutes

No need to jump through hoops. Subtracting Start from End essentially gives you the timespan (combining Vignesh Kumar's and Carl Nitzsche's answers) :

SELECT *,
    --as a time object
    TotalHours = CONVERT(time, EndDate - StartDate),
    --as a formatted string
    TotalHoursText = CONVERT(varchar(20), EndDate - StartDate, 114)
FROM (
    --some test values (across days, but OP only cares about the time, not date)
    SELECT
        StartDate = CONVERT(datetime,'20090213 02:44:37.923'),
        EndDate   = CONVERT(datetime,'20090715 13:24:45.837')
) t

Ouput

StartDate               EndDate                 TotalHours       TotalHoursText
----------------------- ----------------------- ---------------- --------------------
2009-02-13 02:44:37.923 2009-07-15 13:24:45.837 10:40:07.9130000 10:40:07:913

See the full cast and convert options here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

how to get the child node in div using javascript

If you give your table a unique id, its easier:

<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
    onmouseup="checkMultipleSelection(this,event);">
       <table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table" 
              cellpadding="0" cellspacing="0" border="0" width="100%">
           <tr>
              <td style="width:50px; text-align:left;">09:15 AM</td>
              <td style="width:50px; text-align:left;">Item001</td>
              <td style="width:50px; text-align:left;">10</td>
              <td style="width:50px; text-align:left;">Address1</td>
              <td style="width:50px; text-align:left;">46545465</td>
              <td style="width:50px; text-align:left;">ref1</td>
           </tr>
       </table>
</div>


var multiselect = 
    document.getElementById(
               'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
            ).rows[0].cells,
    timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];

//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];

What is difference between Lightsail and EC2?

Lightsail VPSs are bundles of existing AWS products, offered through a significantly simplified interface. The difference is that Lightsail offers you a limited and fixed menu of options but with much greater ease of use. Other than the narrower scope of Lightsail in order to meet the requirements for simplicity and low cost, the underlying technology is the same.

The pre-defined bundles can be described:

% aws lightsail --region us-east-1 get-bundles
{
    "bundles": [
        {
            "name": "Nano",
            "power": 300,
            "price": 5.0,
            "ramSizeInGb": 0.5,
            "diskSizeInGb": 20,
            "transferPerMonthInGb": 1000,
            "cpuCount": 1,
            "instanceType": "t2.nano",
            "isActive": true,
            "bundleId": "nano_1_0"
        },
        ...
    ]
}

It's worth reading through the Amazon EC2 T2 Instances documentation, particularly the CPU Credits section which describes the base and burst performance characteristics of the underlying instances.

Importantly, since your Lightsail instances run in VPC, you still have access to the full spectrum of AWS services, e.g. S3, RDS, and so on, as you would from any EC2 instance.

MySQL date formats - difficulty Inserting a date

Looks like you've not encapsulated your string properly. Try this:

INSERT INTO custorder VALUES ('Kevin','yes'), STR_TO_DATE('1-01-2012', '%d-%m-%Y');

Alternatively, you can do the following but it is not recommended. Make sure that you use STR_TO-DATE it is because when you are developing web applications you have to explicitly convert String to Date which is annoying. Use first One.

INSERT INTO custorder VALUES ('Kevin','yes'), '2012-01-01';

I'm not confident that the above SQL is valid, however, and you may want to move the date part into the brackets. If you can provide the exact error you're getting, I might be able to more directly help with the issue.

How to add footnotes to GitHub-flavoured Markdown?

Although the question is about GitHub flavored Markdown, I think it's worth mentioning that as of 2013, GitHub supports AsciiDoc which has this feature builtin. You only need to rename your file with a .adoc extension and use:

A statement.footnote:[Clarification about this statement.]

A bold statement!footnote:disclaimer[Opinions are my own.]

Another bold statement.footnote:disclaimer[]

Documentation along with the final result is here.

How do I delete a Git branch locally and remotely?

I created the following convenient function in my .bash_aliases file:

git-delete-branch() 
{ 
    if [[ -n $1 ]]; then
        git checkout master > /dev/null;
        branch_name="$1";
        echo "Deleting local $branch_name branch...";
        git branch -D "$branch_name";
        echo "Deleting remote $branch_name branch...";
        git push origin --delete "$branch_name";
        git remote prune origin;
        echo "Your current branches are:";
        git branch -a;
    else
        echo "Usage: git-delete-branch <branch_name>";
    fi
}

How to show soft-keyboard when edittext is focused

I made this help class. Just pass the context and the View you want to focus and show keyboard and after hide keyboard. I hope it Helps.

public class FocusKeyboardHelper {

private View view;
private Context context;
private InputMethodManager imm;

public FocusKeyboardHelper(Context context, View view){
    this.view = view;
    this.context = context;
    imm = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
}

public void focusAndShowKeyboard(){

    view.requestFocus();
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

}

public void hideKeyBoard(){
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

}

How to put an image next to each other

Check this out. Just use float and get rid of relative.

http://jsfiddle.net/JhpRk/

#icons{float:left;}

Ball to Ball Collision - Detection and Handling

You have two easy ways to do this. Jay has covered the accurate way of checking from the center of the ball.

The easier way is to use a rectangle bounding box, set the size of your box to be 80% the size of the ball, and you'll simulate collision pretty well.

Add a method to your ball class:

public Rectangle getBoundingRect()
{
   int ballHeight = (int)Ball.Height * 0.80f;
   int ballWidth = (int)Ball.Width * 0.80f;
   int x = Ball.X - ballWidth / 2;
   int y = Ball.Y - ballHeight / 2;

   return new Rectangle(x,y,ballHeight,ballWidth);
}

Then, in your loop:

// Checks every ball against every other ball. 
// For best results, split it into quadrants like Ryan suggested. 
// I didn't do that for simplicity here.
for (int i = 0; i < balls.count; i++)
{
    Rectangle r1 = balls[i].getBoundingRect();

    for (int k = 0; k < balls.count; k++)
    {

        if (balls[i] != balls[k])
        {
            Rectangle r2 = balls[k].getBoundingRect();

            if (r1.Intersects(r2))
            {
                 // balls[i] collided with balls[k]
            }
        }
    }
}

What is the command to exit a Console application in C#?

You can use Environment.Exit(0) and Application.Exit.

Environment.Exit(): terminates this process and gives the underlying operating system the specified exit code.

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

How do you clone a Git repository into a specific folder?

Although all of the answers above are good, I would like to propose a new method instead of using the symbolic link method in public html directory as proposed BEST in the accepted answer. You need to have access to your server virtual host configurations.

It is about configuring virtual host of your web server directly pointing to the repository directory. In Apache you can do it like:

DocumentRoot /var/www/html/website/your-git-repo

Here is an example of a virtual host file:

<VirtualHost *:443>
    ServerName example.com

    DocumentRoot /path/to/your-git-repo
    ...
    ...
    ...
    ...
</VirtualHost>

TABLOCK vs TABLOCKX

This is more of an example where TABLOCK did not work for me and TABLOCKX did.

I have 2 sessions, that both use the default (READ COMMITTED) isolation level:

Session 1 is an explicit transaction that will copy data from a linked server to a set of tables in a database, and takes a few seconds to run. [Example, it deletes Questions] Session 2 is an insert statement, that simply inserts rows into a table that Session 1 doesn't make changes to. [Example, it inserts Answers].

(In practice there are multiple sessions inserting multiple records into the table, simultaneously, while Session 1 is running its transaction).

Session 1 has to query the table Session 2 inserts into because it can't delete records that depend on entries that were added by Session 2. [Example: Delete questions that have not been answered].

So, while Session 1 is executing and Session 2 tries to insert, Session 2 loses in a deadlock every time.

So, a delete statement in Session 1 might look something like this: DELETE tblA FROM tblQ LEFT JOIN tblX on ... LEFT JOIN tblA a ON tblQ.Qid = tblA.Qid WHERE ... a.QId IS NULL and ...

The deadlock seems to be caused from contention between querying tblA while Session 2, [3, 4, 5, ..., n] try to insert into tblA.

In my case I could change the isolation level of Session 1's transaction to be SERIALIZABLE. When I did this: The transaction manager has disabled its support for remote/network transactions.

So, I could follow instructions in the accepted answer here to get around it: The transaction manager has disabled its support for remote/network transactions

But a) I wasn't comfortable with changing the isolation level to SERIALIZABLE in the first place- supposedly it degrades performance and may have other consequences I haven't considered, b) didn't understand why doing this suddenly caused the transaction to have a problem working across linked servers, and c) don't know what possible holes I might be opening up by enabling network access.

There seemed to be just 6 queries within a very large transaction that are causing the trouble.

So, I read about TABLOCK and TabLOCKX.

I wasn't crystal clear on the differences, and didn't know if either would work. But it seemed like it would. First I tried TABLOCK and it didn't seem to make any difference. The competing sessions generated the same deadlocks. Then I tried TABLOCKX, and no more deadlocks.

So, in six places, all I needed to do was add a WITH (TABLOCKX).

So, a delete statement in Session 1 might look something like this: DELETE tblA FROM tblQ q LEFT JOIN tblX x on ... LEFT JOIN tblA a WITH (TABLOCKX) ON tblQ.Qid = tblA.Qid WHERE ... a.QId IS NULL and ...

How to access pandas groupby dataframe by key

Wes McKinney (pandas' author) in Python for Data Analysis provides the following recipe:

groups = dict(list(gb))

which returns a dictionary whose keys are your group labels and whose values are DataFrames, i.e.

groups['foo']

will yield what you are looking for:

     A         B   C
0  foo  1.624345   5
2  foo -0.528172  11
4  foo  0.865408  14

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

I know this is not fully relevant, but since this answer is ranked first many a times when you search 'how to display images in Jupyter', please consider this answer as well.

You could use matplotlib to show an image as follows.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread("your_image.png")
plt.imshow(image)
plt.show()

Count how many rows have the same value

If you want to have the result for all values of NUM:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
GROUP BY `NUM`

Or just for one specific:

SELECT `NUM`, COUNT(*) AS `count` 
FROM yourTable
WHERE `NUM`=1

PHP 7 simpleXML

For Alpine (in docker), you can use apk add php7-simplexml.

If that doesn't work for you, you can run apk add --no-cache php7-simplexml. This is in case you aren't updating the package index first.

typeof !== "undefined" vs. != null

_x000D_
_x000D_
function greet(name, greeting) {_x000D_
  name = (typeof name !== 'undefined') ?  name : 'Student';_x000D_
  greeting = (typeof greeting !== 'undefined') ?  greeting : 'Welcome';_x000D_
_x000D_
  console.log(greeting,name);_x000D_
}_x000D_
_x000D_
greet(); // Welcome Student!_x000D_
greet('James'); // Welcome James!_x000D_
greet('Richard', 'Howdy'); // Howdy Richard!_x000D_
_x000D_
//ES6 provides new ways of introducing default function parameters this way:_x000D_
_x000D_
function greet2(name = 'Student', greeting = 'Welcome') {_x000D_
//  return '${greeting} ${name}!';_x000D_
console.log(greeting,name);_x000D_
}_x000D_
_x000D_
greet2(); // Welcome Student!_x000D_
greet2('James'); // Welcome James!_x000D_
greet2('Richard', 'Howdy'); // Howdy Richard!
_x000D_
_x000D_
_x000D_

Editing in the Chrome debugger

Chrome DevTools has a Snippets panel where you can create and edit JavaScript code as you would in an editor, and execute it. Open DevTools, then select the Sources panel, then select the Snippets tab.

https://developers.google.com/web/tools/chrome-devtools/snippets

enter image description here

A python class that acts like dict

Check the documentation on emulating container types. In your case, the first parameter to add should be self.

is there any alternative for ng-disabled in angular2?

[attr.disabled]="valid == true ? true : null"

You have to use null to remove attr from html element.