Programs & Examples On #Sensitive data

Remove folder and its contents from git/GitHub's history

It appears that the up-to-date answer to this is to not use filter-branch directly (at least git itself does not recommend it anymore), and defer that work to an external tool. In particular, git-filter-repo is currently recommended. The author of that tool provides arguments on why using filter-branch directly can lead to issues.

Most of the multi-line scripts above to remove dir from the history could be re-written as:

git filter-repo --path dir --invert-paths

The tool is more powerful than just that, apparently. You can apply filters by author, email, refname and more (full manpage here). Furthermore, it is fast. Installation is easy - it is distributed in a variety of formats.

Ant if else condition?

The if attribute does not exist for <copy>. It should be applied to the <target>.

Below is an example of how you can use the depends attribute of a target and the if and unless attributes to control execution of dependent targets. Only one of the two should execute.

<target name="prepare-copy" description="copy file based on condition"
    depends="prepare-copy-true, prepare-copy-false">
</target>

<target name="prepare-copy-true" description="copy file based on condition"
    if="copy-condition">
    <echo>Get file based on condition being true</echo>
    <copy file="${some.dir}/true" todir="." />
</target>

<target name="prepare-copy-false" description="copy file based on false condition" 
    unless="copy-condition">
    <echo>Get file based on condition being false</echo>
    <copy file="${some.dir}/false" todir="." />
</target>

If you are using ANT 1.8+, then you can use property expansion and it will evaluate the value of the property to determine the boolean value. So, you could use if="${copy-condition}" instead of if="copy-condition".

In ANT 1.7.1 and earlier, you specify the name of the property. If the property is defined and has any value (even an empty string), then it will evaluate to true.

How can I change the Java Runtime Version on Windows (7)?

Update your environment variables

Ensure the reference to java/bin is up to date in 'Path'; This may be automatic if you have JAVA_HOME or equivalent set. If JAVA_HOME is set, simply update it to refer to the older JRE installation.

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Further reading for any of the topics here: The Definitive Guide to Linux System Calls


I verified these using GNU Assembler (gas) on Linux.

Kernel Interface

x86-32 aka i386 Linux System Call convention:

In x86-32 parameters for Linux system call are passed using registers. %eax for syscall_number. %ebx, %ecx, %edx, %esi, %edi, %ebp are used for passing 6 parameters to system calls.

The return value is in %eax. All other registers (including EFLAGS) are preserved across the int $0x80.

I took following snippet from the Linux Assembly Tutorial but I'm doubtful about this. If any one can show an example, it would be great.

If there are more than six arguments, %ebx must contain the memory location where the list of arguments is stored - but don't worry about this because it's unlikely that you'll use a syscall with more than six arguments.

For an example and a little more reading, refer to http://www.int80h.org/bsdasm/#alternate-calling-convention. Another example of a Hello World for i386 Linux using int 0x80: Hello, world in assembly language with Linux system calls?

There is a faster way to make 32-bit system calls: using sysenter. The kernel maps a page of memory into every process (the vDSO), with the user-space side of the sysenter dance, which has to cooperate with the kernel for it to be able to find the return address. Arg to register mapping is the same as for int $0x80. You should normally call into the vDSO instead of using sysenter directly. (See The Definitive Guide to Linux System Calls for info on linking and calling into the vDSO, and for more info on sysenter, and everything else to do with system calls.)

x86-32 [Free|Open|Net|DragonFly]BSD UNIX System Call convention:

Parameters are passed on the stack. Push the parameters (last parameter pushed first) on to the stack. Then push an additional 32-bit of dummy data (Its not actually dummy data. refer to following link for more info) and then give a system call instruction int $0x80

http://www.int80h.org/bsdasm/#default-calling-convention


x86-64 Linux System Call convention:

(Note: x86-64 Mac OS X is similar but different from Linux. TODO: check what *BSD does)

Refer to section: "A.2 AMD64 Linux Kernel Conventions" of System V Application Binary Interface AMD64 Architecture Processor Supplement. The latest versions of the i386 and x86-64 System V psABIs can be found linked from this page in the ABI maintainer's repo. (See also the tag wiki for up-to-date ABI links and lots of other good stuff about x86 asm.)

Here is the snippet from this section:

  1. User-level applications use as integer registers for passing the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9. The kernel interface uses %rdi, %rsi, %rdx, %r10, %r8 and %r9.
  2. A system-call is done via the syscall instruction. This clobbers %rcx and %r11 as well as the %rax return value, but other registers are preserved.
  3. The number of the syscall has to be passed in register %rax.
  4. System-calls are limited to six arguments, no argument is passed directly on the stack.
  5. Returning from the syscall, register %rax contains the result of the system-call. A value in the range between -4095 and -1 indicates an error, it is -errno.
  6. Only values of class INTEGER or class MEMORY are passed to the kernel.

Remember this is from the Linux-specific appendix to the ABI, and even for Linux it's informative not normative. (But it is in fact accurate.)

This 32-bit int $0x80 ABI is usable in 64-bit code (but highly not recommended). What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? It still truncates its inputs to 32-bit, so it's unsuitable for pointers, and it zeros r8-r11.

User Interface: function calling

x86-32 Function Calling convention:

In x86-32 parameters were passed on stack. Last parameter was pushed first on to the stack until all parameters are done and then call instruction was executed. This is used for calling C library (libc) functions on Linux from assembly.

Modern versions of the i386 System V ABI (used on Linux) require 16-byte alignment of %esp before a call, like the x86-64 System V ABI has always required. Callees are allowed to assume that and use SSE 16-byte loads/stores that fault on unaligned. But historically, Linux only required 4-byte stack alignment, so it took extra work to reserve naturally-aligned space even for an 8-byte double or something.

Some other modern 32-bit systems still don't require more than 4 byte stack alignment.


x86-64 System V user-space Function Calling convention:

x86-64 System V passes args in registers, which is more efficient than i386 System V's stack args convention. It avoids the latency and extra instructions of storing args to memory (cache) and then loading them back again in the callee. This works well because there are more registers available, and is better for modern high-performance CPUs where latency and out-of-order execution matter. (The i386 ABI is very old).

In this new mechanism: First the parameters are divided into classes. The class of each parameter determines the manner in which it is passed to the called function.

For complete information refer to : "3.2 Function Calling Sequence" of System V Application Binary Interface AMD64 Architecture Processor Supplement which reads, in part:

Once arguments are classified, the registers get assigned (in left-to-right order) for passing as follows:

  1. If the class is MEMORY, pass the argument on the stack.
  2. If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9 is used

So %rdi, %rsi, %rdx, %rcx, %r8 and %r9 are the registers in order used to pass integer/pointer (i.e. INTEGER class) parameters to any libc function from assembly. %rdi is used for the first INTEGER parameter. %rsi for 2nd, %rdx for 3rd and so on. Then call instruction should be given. The stack (%rsp) must be 16B-aligned when call executes.

If there are more than 6 INTEGER parameters, the 7th INTEGER parameter and later are passed on the stack. (Caller pops, same as x86-32.)

The first 8 floating point args are passed in %xmm0-7, later on the stack. There are no call-preserved vector registers. (A function with a mix of FP and integer arguments can have more than 8 total register arguments.)

Variadic functions (like printf) always need %al = the number of FP register args.

There are rules for when to pack structs into registers (rdx:rax on return) vs. in memory. See the ABI for details, and check compiler output to make sure your code agrees with compilers about how something should be passed/returned.


Note that the Windows x64 function calling convention has multiple significant differences from x86-64 System V, like shadow space that must be reserved by the caller (instead of a red-zone), and call-preserved xmm6-xmm15. And very different rules for which arg goes in which register.

Declare a dictionary inside a static class

You can use the static/class constructor to initialize your dictionary:

public static class ErrorCode
{
    public const IDictionary<string, string> ErrorCodeDic;
    public static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

How to use radio buttons in ReactJS?

I also got confused in radio, checkbox implementation. What we need is, listen change event of the radio, and then set the state. I have made small example of gender selection.

_x000D_
_x000D_
/*_x000D_
 * A simple React component_x000D_
 */_x000D_
class App extends React.Component {_x000D_
  constructor(params) {_x000D_
     super(params) _x000D_
     // initial gender state set from props_x000D_
     this.state = {_x000D_
       gender: this.props.gender_x000D_
     }_x000D_
     this.setGender = this.setGender.bind(this)_x000D_
  }_x000D_
  _x000D_
  setGender(e) {_x000D_
    this.setState({_x000D_
      gender: e.target.value_x000D_
    })_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const {gender} = this.state_x000D_
    return  <div>_x000D_
        Gender:_x000D_
        <div>_x000D_
          <input type="radio" checked={gender == "male"} _x000D_
onClick={this.setGender} value="male" /> Male_x000D_
          <input type="radio" checked={gender == "female"} _x000D_
onClick={this.setGender} value="female"  /> Female_x000D_
        </div>_x000D_
        { "Select Gender: " } {gender}_x000D_
      </div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
/*_x000D_
 * Render the above component into the div#app_x000D_
 */_x000D_
ReactDOM.render(<App gender="male" />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

How to concatenate a std::string and an int?

If you'd like to use + for concatenation of anything which has an output operator, you can provide a template version of operator+:

template <typename L, typename R> std::string operator+(L left, R right) {
  std::ostringstream os;
  os << left << right;
  return os.str();
}

Then you can write your concatenations in a straightforward way:

std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);    
std::cout << bar << std::endl;

Output:

the answer is 42

This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.

VB.net: Date without time

FormatDateTime(Now, DateFormat.ShortDate)

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

My problem was solved after turning Off Windows Firewall Defender in public network as I was connected with that network.

How to get key names from JSON using jq

To get the keys on a deeper node in an JSON:

echo '{"data": "1", "user": { "name": 2, "phone": 3 } }' | jq '.user | keys[]'
"name"
"phone"

Iterating through all nodes in XML file

To iterate through all elements

XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
    Console.WriteLine(element.Name);
}

Windows 7 - Add Path

Try this in cmd:

cd address_of_sumatrapdf.exe_file && sumatrapdf.exe

Where you should put the address of your .exe file instead of adress_of_sumatrapdf.exe_file.

How to Get JSON Array Within JSON Object?

Your int length = jsonObj.length(); should be int length = ja_data.length();

How can I set the aspect ratio in matplotlib?

What is the matplotlib version you are running? I have recently had to upgrade to 1.1.0, and with it, add_subplot(111,aspect='equal') works for me.

Angularjs: input[text] ngChange fires while the value is changing

In case anyone else looking for additional "enter" keypress support, here's an update to the fiddle provided by Gloppy

Code for keypress binding:

elm.bind("keydown keypress", function(event) {
    if (event.which === 13) {
        scope.$apply(function() {
            ngModelCtrl.$setViewValue(elm.val());
        });
    }
});

Getting HTTP code in PHP using curl

use this hitCurl method for fetch all type of api response i.e. Get / Post

        function hitCurl($url,$param = [],$type = 'POST'){
        $ch = curl_init();
        if(strtoupper($type) == 'GET'){
            $param = http_build_query((array)$param);
            $url = "{$url}?{$param}";
        }else{
            curl_setopt_array($ch,[
                CURLOPT_POST => (strtoupper($type) == 'POST'),
                CURLOPT_POSTFIELDS => (array)$param,
            ]);
        }
        curl_setopt_array($ch,[
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
        ]);
        $resp = curl_exec($ch);
        $statusCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        return [
            'statusCode' => $statusCode,
            'resp' => $resp
        ];
    }

Demo function to test api

 function fetchApiData(){
        $url = 'https://postman-echo.com/get';
        $resp = $this->hitCurl($url,[
            'foo1'=>'bar1',
            'foo2'=>'bar2'
        ],'get');
        $apiData = "Getting header code {$resp['statusCode']}";
        if($resp['statusCode'] == 200){
            $apiData = json_decode($resp['resp']);
        }
        echo "<pre>";
        print_r ($apiData);
        echo "</pre>";
    }

sendKeys() in Selenium web driver

List<WebElement>itemNames = wd.findElements(By.cssSelector("a strong")); 
System.out.println("No items in Catalog page: " + itemNames.size());
   for (WebElement itemName:itemNames)
    {  
       System.out.println(itemName.getText());
    }

How to find NSDocumentDirectory in Swift?

Xcode 8.2.1 • Swift 3.0.2

let documentDirectoryURL =  try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

Xcode 7.1.1 • Swift 2.1

let documentDirectoryURL =  try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)

jQuery: how to find first visible input/select/textarea excluding buttons?

This is my summary of the above and works perfectly for me. Thanks for the info!

<script language='javascript' type='text/javascript'>
    $(document).ready(function () {
        var firstInput = $('form').find('input[type=text],input[type=password],input[type=radio],input[type=checkbox],textarea,select').filter(':visible:first');
        if (firstInput != null) {
            firstInput.focus();
        }
    });
</script>

Random integer in VB.NET

Just for reference, VB NET Fuction definition for RND and RANDOMIZE (which should give the same results of BASIC (1980 years) and all versions after is:

Public NotInheritable Class VBMath
    ' Methods
    Private Shared Function GetTimer() As Single
        Dim now As DateTime = DateTime.Now
        Return CSng((((((60 * now.Hour) + now.Minute) * 60) + now.Second) + (CDbl(now.Millisecond) / 1000)))
    End Function

    Public Shared Sub Randomize()
        Dim timer As Single = VBMath.GetTimer
        Dim projectData As ProjectData = ProjectData.GetProjectData
        Dim rndSeed As Integer = projectData.m_rndSeed
        Dim num3 As Integer = BitConverter.ToInt32(BitConverter.GetBytes(timer), 0)
        num3 = (((num3 And &HFFFF) Xor (num3 >> &H10)) << 8)
        rndSeed = ((rndSeed And -16776961) Or num3)
        projectData.m_rndSeed = rndSeed
    End Sub

    Public Shared Sub Randomize(ByVal Number As Double)
        Dim num2 As Integer
        Dim projectData As ProjectData = ProjectData.GetProjectData
        Dim rndSeed As Integer = projectData.m_rndSeed
        If BitConverter.IsLittleEndian Then
            num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 4)
        Else
            num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 0)
        End If
        num2 = (((num2 And &HFFFF) Xor (num2 >> &H10)) << 8)
        rndSeed = ((rndSeed And -16776961) Or num2)
        projectData.m_rndSeed = rndSeed
    End Sub

    Public Shared Function Rnd() As Single
        Return VBMath.Rnd(1!)
    End Function

    Public Shared Function Rnd(ByVal Number As Single) As Single
        Dim projectData As ProjectData = ProjectData.GetProjectData
        Dim rndSeed As Integer = projectData.m_rndSeed
        If (Number <> 0) Then
            If (Number < 0) Then
                Dim num1 As UInt64 = (BitConverter.ToInt32(BitConverter.GetBytes(Number), 0) And &HFFFFFFFF)
                rndSeed = CInt(((num1 + (num1 >> &H18)) And CULng(&HFFFFFF)))
            End If
            rndSeed = CInt((((rndSeed * &H43FD43FD) + &HC39EC3) And &HFFFFFF))
        End If
        projectData.m_rndSeed = rndSeed
        Return (CSng(rndSeed) / 1.677722E+07!)
    End Function

End Class

While the Random CLASS is:

Public Class Random
    ' Methods
    <__DynamicallyInvokable> _
    Public Sub New()
        Me.New(Environment.TickCount)
    End Sub

    <__DynamicallyInvokable> _
    Public Sub New(ByVal Seed As Integer)
        Me.SeedArray = New Integer(&H38  - 1) {}
        Dim num4 As Integer = If((Seed = -2147483648), &H7FFFFFFF, Math.Abs(Seed))
        Dim num2 As Integer = (&H9A4EC86 - num4)
        Me.SeedArray(&H37) = num2
        Dim num3 As Integer = 1
        Dim i As Integer
        For i = 1 To &H37 - 1
            Dim index As Integer = ((&H15 * i) Mod &H37)
            Me.SeedArray(index) = num3
            num3 = (num2 - num3)
            If (num3 < 0) Then
                num3 = (num3 + &H7FFFFFFF)
            End If
            num2 = Me.SeedArray(index)
        Next i
        Dim j As Integer
        For j = 1 To 5 - 1
            Dim k As Integer
            For k = 1 To &H38 - 1
                Me.SeedArray(k) = (Me.SeedArray(k) - Me.SeedArray((1 + ((k + 30) Mod &H37))))
                If (Me.SeedArray(k) < 0) Then
                    Me.SeedArray(k) = (Me.SeedArray(k) + &H7FFFFFFF)
                End If
            Next k
        Next j
        Me.inext = 0
        Me.inextp = &H15
        Seed = 1
    End Sub

    Private Function GetSampleForLargeRange() As Double
        Dim num As Integer = Me.InternalSample
        If ((Me.InternalSample Mod 2) = 0) Then
            num = -num
        End If
        Dim num2 As Double = num
        num2 = (num2 + 2147483646)
        Return (num2 / 4294967293)
    End Function

    Private Function InternalSample() As Integer
        Dim inext As Integer = Me.inext
        Dim inextp As Integer = Me.inextp
        If (++inext >= &H38) Then
            inext = 1
        End If
        If (++inextp >= &H38) Then
            inextp = 1
        End If
        Dim num As Integer = (Me.SeedArray(inext) - Me.SeedArray(inextp))
        If (num = &H7FFFFFFF) Then
            num -= 1
        End If
        If (num < 0) Then
            num = (num + &H7FFFFFFF)
        End If
        Me.SeedArray(inext) = num
        Me.inext = inext
        Me.inextp = inextp
        Return num
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Function [Next]() As Integer
        Return Me.InternalSample
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Function [Next](ByVal maxValue As Integer) As Integer
        If (maxValue < 0) Then
            Dim values As Object() = New Object() { "maxValue" }
            Throw New ArgumentOutOfRangeException("maxValue", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", values))
        End If
        Return CInt((Me.Sample * maxValue))
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Function [Next](ByVal minValue As Integer, ByVal maxValue As Integer) As Integer
        If (minValue > maxValue) Then
            Dim values As Object() = New Object() { "minValue", "maxValue" }
            Throw New ArgumentOutOfRangeException("minValue", Environment.GetResourceString("Argument_MinMaxValue", values))
        End If
        Dim num As Long = (maxValue - minValue)
        If (num <= &H7FFFFFFF) Then
            Return (CInt((Me.Sample * num)) + minValue)
        End If
        Return (CInt(CLng((Me.GetSampleForLargeRange * num))) + minValue)
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Sub NextBytes(ByVal buffer As Byte())
        If (buffer Is Nothing) Then
            Throw New ArgumentNullException("buffer")
        End If
        Dim i As Integer
        For i = 0 To buffer.Length - 1
            buffer(i) = CByte((Me.InternalSample Mod &H100))
        Next i
    End Sub

    <__DynamicallyInvokable> _
    Public Overridable Function NextDouble() As Double
        Return Me.Sample
    End Function

    <__DynamicallyInvokable> _
    Protected Overridable Function Sample() As Double
        Return (Me.InternalSample * 4.6566128752457969E-10)
    End Function


    ' Fields
    Private inext As Integer
    Private inextp As Integer
    Private Const MBIG As Integer = &H7FFFFFFF
    Private Const MSEED As Integer = &H9A4EC86
    Private Const MZ As Integer = 0
    Private SeedArray As Integer()
End Class

How can I detect keydown or keypress event in angular.js?

You were on the right track with your "ng-keydown" attribute on the input, but you missed a simple step. Just because you put the ng-keydown attribute there, doesn't mean angular knows what to do with it. That's where "directives" come into play. You used the attribute correctly, but you now need to write a directive that will tell angular what to do when it sees that attribute on an html element.

The following is an example of how you would do that. We'll rename the directive from ng-keydown to on-keydown (to avoid breaking the "best practice" found here):

var mod = angular.module('mydirectives');
mod.directive('onKeydown', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
             // this next line will convert the string
             // function name into an actual function
             var functionToCall = scope.$eval(attrs.ngKeydown);
             elem.on('keydown', function(e){
                  // on the keydown event, call my function
                  // and pass it the keycode of the key
                  // that was pressed
                  // ex: if ENTER was pressed, e.which == 13
                  functionToCall(e.which);
             });
        }
    };
});

The directive simple tells angular that when it sees an HTML attribute called "ng-keydown", it should listen to the element that has that attribute and call whatever function is passed to it. In the html you would have the following:

<input type="text" on-keydown="onKeydown">

And then in your controller (just like you already had), you would add a function to your controller's scope that is called "onKeydown", like so:

$scope.onKeydown = function(keycode){
    // do something with the keycode
}

Hopefully that helps either you or someone else who wants to know

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

Display current time in 12 hour format with AM/PM

If you want current time with AM, PM in Android use

String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime());

If you want current time with am, pm

String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime()).toLowerCase();

OR

From API level 26

LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
String time = localTime.format(dateTimeFormatter);

Stacked Tabs in Bootstrap 3

Left, Right and Below tabs were removed from Bootstrap 3, but you can add custom CSS to achieve this..

.tabs-below > .nav-tabs,
.tabs-right > .nav-tabs,
.tabs-left > .nav-tabs {
  border-bottom: 0;
}

.tab-content > .tab-pane,
.pill-content > .pill-pane {
  display: none;
}

.tab-content > .active,
.pill-content > .active {
  display: block;
}

.tabs-below > .nav-tabs {
  border-top: 1px solid #ddd;
}

.tabs-below > .nav-tabs > li {
  margin-top: -1px;
  margin-bottom: 0;
}

.tabs-below > .nav-tabs > li > a {
  -webkit-border-radius: 0 0 4px 4px;
     -moz-border-radius: 0 0 4px 4px;
          border-radius: 0 0 4px 4px;
}

.tabs-below > .nav-tabs > li > a:hover,
.tabs-below > .nav-tabs > li > a:focus {
  border-top-color: #ddd;
  border-bottom-color: transparent;
}

.tabs-below > .nav-tabs > .active > a,
.tabs-below > .nav-tabs > .active > a:hover,
.tabs-below > .nav-tabs > .active > a:focus {
  border-color: transparent #ddd #ddd #ddd;
}

.tabs-left > .nav-tabs > li,
.tabs-right > .nav-tabs > li {
  float: none;
}

.tabs-left > .nav-tabs > li > a,
.tabs-right > .nav-tabs > li > a {
  min-width: 74px;
  margin-right: 0;
  margin-bottom: 3px;
}

.tabs-left > .nav-tabs {
  float: left;
  margin-right: 19px;
  border-right: 1px solid #ddd;
}

.tabs-left > .nav-tabs > li > a {
  margin-right: -1px;
  -webkit-border-radius: 4px 0 0 4px;
     -moz-border-radius: 4px 0 0 4px;
          border-radius: 4px 0 0 4px;
}

.tabs-left > .nav-tabs > li > a:hover,
.tabs-left > .nav-tabs > li > a:focus {
  border-color: #eeeeee #dddddd #eeeeee #eeeeee;
}

.tabs-left > .nav-tabs .active > a,
.tabs-left > .nav-tabs .active > a:hover,
.tabs-left > .nav-tabs .active > a:focus {
  border-color: #ddd transparent #ddd #ddd;
  *border-right-color: #ffffff;
}

.tabs-right > .nav-tabs {
  float: right;
  margin-left: 19px;
  border-left: 1px solid #ddd;
}

.tabs-right > .nav-tabs > li > a {
  margin-left: -1px;
  -webkit-border-radius: 0 4px 4px 0;
     -moz-border-radius: 0 4px 4px 0;
          border-radius: 0 4px 4px 0;
}

.tabs-right > .nav-tabs > li > a:hover,
.tabs-right > .nav-tabs > li > a:focus {
  border-color: #eeeeee #eeeeee #eeeeee #dddddd;
}

.tabs-right > .nav-tabs .active > a,
.tabs-right > .nav-tabs .active > a:hover,
.tabs-right > .nav-tabs .active > a:focus {
  border-color: #ddd #ddd #ddd transparent;
  *border-left-color: #ffffff;
}

Working example: http://bootply.com/74926

UPDATE

If you don't need the exact look of a tab (bordered appropriately on the left or right as each tab is activated), you can simple use nav-stacked, along with Bootstrap col-* to float the tabs to the left or right...

nav-stacked demo: http://codeply.com/go/rv3Cvr0lZ4

<ul class="nav nav-pills nav-stacked col-md-3">
    <li><a href="#a" data-toggle="tab">1</a></li>
    <li><a href="#b" data-toggle="tab">2</a></li>
    <li><a href="#c" data-toggle="tab">3</a></li>
</ul>

VSCode regex find & replace submatch math?

For beginners, the accepted answer is correct, but a little terse if you're not that familiar with either VSC or Regex.

So, in case this is your first contact with either:

To find and modify text,

  1. In the "Find" step, you can use regex with "capturing groups," e.g. I want to find (group1) and (group2), using parentheses. This would find the same text as I want to find group1 and group2, but with the difference that you can then reference group1 and group2 in the next step:

  2. In the "Replace" step, you can refer to the capturing groups via $1, $2 etc, so you could change the sentence to I found $1 and $2 having a picnic, which would output I found group1 and group2 having a picnic.

Notes:

  • Instead of just a string, anything inside or outside the () can be a regular expression.

  • $0 refers to the whole match

How to create a GUID/UUID using iOS

[[UIDevice currentDevice] uniqueIdentifier]

Returns the Unique ID of your iPhone.

EDIT: -[UIDevice uniqueIdentifier] is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.

If you need to create several UUID, just use this method (with ARC):

+ (NSString *)GetUUID
{
  CFUUIDRef theUUID = CFUUIDCreate(NULL);
  CFStringRef string = CFUUIDCreateString(NULL, theUUID);
  CFRelease(theUUID);
  return (__bridge NSString *)string;
}

EDIT: Jan, 29 2014: If you're targeting iOS 6 or later, you can now use the much simpler method:

NSString *UUID = [[NSUUID UUID] UUIDString];

Android: how to refresh ListView contents?

I'm doing the same thing using invalidateViews() and that works for me. If you want it to invalidate immediately you could try calling postInvalidate after calling invalidateViews.

How to get a dependency tree for an artifact?

1) Use maven dependency plugin

Create a simple project with pom.xml only. Add your dependency and run:

mvn dependency:tree

Unfortunately dependency mojo must use pom.xml or you get following error:

Cannot execute mojo: tree. It requires a project with an existing pom.xml, but the build is not using one.

2) Find pom.xml of your artifact in maven central repository

Dependencies are described In pom.xml of your artifact. Find it using maven infrastructure.

Go to https://search.maven.org/ and enter your groupId and artifactId.

Or you can go to https://repo1.maven.org/maven2/ and navigate first using plugins groupId, later using artifactId and finally using its version.

For example see org.springframework:spring-core

3) Use maven dependency plugin against your artifact

Part of dependency artifact is a pom.xml. That specifies it's dependency. And you can execute mvn dependency:tree on this pom.

Python pandas Filtering out nan from a data selection of a column of strings

df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],'rating': [3., 4., 5., np.nan, np.nan, np.nan],'name': ['John','James', np.nan, np.nan, np.nan,np.nan]})

for col in df.columns:
    df = df[~pd.isnull(df[col])]

PDO Prepared Inserts multiple rows in single query

My real world example to insert all german postcodes into an empty table (to add town names later):

// obtain column template
$stmt = $db->prepare('SHOW COLUMNS FROM towns');
$stmt->execute();
$columns = array_fill_keys(array_values($stmt->fetchAll(PDO::FETCH_COLUMN)), null);
// multiple INSERT
$postcode = '01000';// smallest german postcode
while ($postcode <= 99999) {// highest german postcode
    $values = array();
    while ($postcode <= 99999) {
        // reset row
        $row = $columns;
        // now fill our row with data
        $row['postcode'] = sprintf('%05d', $postcode);
        // build INSERT array
        foreach ($row as $value) {
            $values[] = $value;
        }
        $postcode++;
        // avoid memory kill
        if (!($postcode % 10000)) {
            break;
        }
    }
    // build query
    $count_columns = count($columns);
    $placeholder = ',(' . substr(str_repeat(',?', $count_columns), 1) . ')';//,(?,?,?)
    $placeholder_group = substr(str_repeat($placeholder, count($values) / $count_columns), 1);//(?,?,?),(?,?,?)...
    $into_columns = implode(',', array_keys($columns));//col1,col2,col3
    // this part is optional:
    $on_duplicate = array();
    foreach ($columns as $column => $row) {
        $on_duplicate[] = $column;
        $on_duplicate[] = $column;
    }
    $on_duplicate = ' ON DUPLICATE KEY UPDATE' . vsprintf(substr(str_repeat(', %s = VALUES(%s)', $count_columns), 1), $on_duplicate);
    // execute query
    $stmt = $db->prepare('INSERT INTO towns (' . $into_columns . ') VALUES' . $placeholder_group . $on_duplicate);//INSERT INTO towns (col1,col2,col3) VALUES(?,?,?),(?,?,?)... {ON DUPLICATE...}
    $stmt->execute($values);
}

As you can see its fully flexible. You don't need to check the amount of columns or check on which position your column is. You only need to set the insert data:

    $row['postcode'] = sprintf('%05d', $postcode);

I'm proud of some of the query string constructors as they work without heavy array-functions like array_merge. Especially vsprintf() was a good find.

Finally I needed to add 2x while() to avoid exceeding the memory limit. This depends on your memory limit but at all its a good general solution to avoid problems (and having 10 queries is still much better than 10.000).

Difference between BYTE and CHAR in column datatypes

Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.

If you define the field as VARCHAR2(11 BYTE), Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.

By defining the field as VARCHAR2(11 CHAR) you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.

How to use Greek symbols in ggplot2?

Use expression(delta) where 'delta' for lowercase d and 'Delta' to get capital ?.

Here's full list of Greek characters:

? a alpha
? ß beta
G ? gamma
? d delta
? e epsilon
? ? zeta
? ? eta
T ? theta
? ? iota
? ? kappa
? ? lambda
? µ mu
? ? nu
? ? xi
? ? omicron
? p pi
? ? rho
S s sigma
? t tau
? ? upsilon
F f phi
? ? chi
? ? psi
O ? omega

EDIT: Copied from comments, when using in conjunction with other words use like: expression(Delta*"price")

How to pass a value from Vue data to href?

You need to use v-bind: or its alias :. For example,

<a v-bind:href="'/job/'+ r.id">

or

<a :href="'/job/' + r.id">

What is the best way to give a C# auto-property an initial value?

You can simple put like this

public sealed  class Employee
{
    public int Id { get; set; } = 101;
}

Obtain smallest value from array in Javascript?

Possibly an easier way?

Let's say justPrices is mixed up in terms of value, so you don't know where the smallest value is.

justPrices[0] = 4.5
justPrices[1] = 9.9
justPrices[2] = 1.5

Use sort.

justPrices.sort();

It would then put them in order for you. (Can also be done alphabetically.) The array then would be put in ascending order.

justPrices[0] = 1.5
justPrices[1] = 4.5
justPrices[2] = 9.9

You can then easily grab by the first index.

justPrices[0]

I find this is a bit more useful than what's proposed above because what if you need the lowest 3 numbers as an example? You can also switch which order they're arranged, more info at http://www.w3schools.com/jsref/jsref_sort.asp

How to get the focused element with jQuery?

$(':focus')[0] will give you the actual element.

$(':focus') will give you an array of elements, usually only one element is focused at a time so this is only better if you somehow have multiple elements focused.

Get single row result with Doctrine NativeQuery

->getSingleScalarResult() will return a single value, instead of an array.

How to write and save html file in python?

You can create multi-line strings by enclosing them in triple quotes. So you can store your HTML in a string and pass that string to write():

html_str = """
<table border=1>
     <tr>
       <th>Number</th>
       <th>Square</th>
     </tr>
     <indent>
     <% for i in range(10): %>
       <tr>
         <td><%= i %></td>
         <td><%= i**2 %></td>
       </tr>
     </indent>
</table>
"""

Html_file= open("filename","w")
Html_file.write(html_str)
Html_file.close()

Switch php versions on commandline ubuntu 16.04

When installing laravel on Ubuntu 18.04, be default PHP 7.3.0RC3 install selected, but laravel and symfony will not install properly complaining about missin php-xml and php-zip, even though they are installed. You need to switch to php 7.1, using the instructions above or,

 sudo update-alternatives --set php /usr/bin/php7.1

now, running laravel new blog, will proceed correctly

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

How do I center content in a div using CSS?

with all the adjusting css. if possible, wrap it with a table with height and width as 100% and td set it to vertical align to middle, text-align to center

PHP and MySQL Select a Single Value

try this

session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
      $_SESSION['myid'] = $row['id'];
}

What is @RenderSection in asp.net MVC

Here the defination of Rendersection from MSDN

In layout pages, renders the content of a named section.MSDN

In _layout.cs page put

@RenderSection("Bottom",false)

Here render the content of bootom section and specifies false boolean property to specify whether the section is required or not.

@section Bottom{
       This message form bottom.
}

That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.

convert iso date to milliseconds in javascript

Yes, you can do this in a single line

let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673

How to set String's font size, style in Java using the Font class?

Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29

JComponent has a setFont() method. You will control the font there, not on the String.

Such as

JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));

How to read if a checkbox is checked in PHP?

I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.

HTML Code: (for Add Page)

<input name="status" type="checkbox" value="1" checked>

Hint: remove "checkbox" if you want to show it as unchecked by default

HTML Code: (for Edit Page)

<input name="status" type="checkbox" value="1" 
<?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>

PHP Code: (use for Add/Edit pages)

$status = $_POST['status'];
if ($status == 1) {
$status = 1;
} else {
$status = 0;
}

Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.

What's the fastest way to do a bulk insert into Postgres?

PostgreSQL has a guide on how to best populate a database initially, and they suggest using the COPY command for bulk loading rows. The guide has some other good tips on how to speed up the process, like removing indexes and foreign keys before loading the data (and adding them back afterwards).

Comments in Android Layout xml

<!-- comment here -->

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

Add these lines in your .htaccess file and it will work for all browsers. Works for me.

AddType video/ogg .ogv
AddType video/mp4 .mp4
AddType video/webm .webm

If you dun have .htaccess file in your site then create new one :) its obvious i guess.

Lists in ConfigParser

There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:

[Section 3]
barList=item1,item2

It's not pretty but it's functional for most simple lists.

How to change a string into uppercase

For questions on simple string manipulation the dir built-in function comes in handy. It gives you, among others, a list of methods of the argument, e.g., dir(s) returns a list containing upper.

Dropping Unique constraint from MySQL table

The indexes capable of placing a unique key constraint on a table are PRIMARY and UNIQUE indexes.

To remove the unique key constraint on a column but keep the index, you could remove and recreate the index with type INDEX.

Note that it is a good idea for all tables to have an index marked PRIMARY.

How can I output a UTF-8 CSV in PHP that Excel will read properly?

EASY solution for Mac Excel 2008: I struggled with this soo many times, but here was my easy fix: Open the .csv file in Textwrangler which should open your UTF-8 chars correctly. Now in the bottom status bar change the file format from "Unicode (UTF-8)" to "Western (ISO Latin 1)" and save the file. Now go to your Mac Excel 2008 and select File > Import > Select csv > Find your file > in File origin select "Windows (ANSI)" and voila the UTF-8 chars are showing correctly. At least it does for me...

How to display two digits after decimal point in SQL Server

You can also Make use of the Following if you want to Cast and Round as well. That may help you or someone else.

SELECT CAST(ROUND(Column_Name, 2) AS DECIMAL(10,2), Name FROM Table_Name

How to use conditional breakpoint in Eclipse?

Put your breakpoint. Right-click the breakpoint image on the margin and choose Breakpoint Properties:

enter image description here

Configure condition as you see fit:

enter image description here

document.createElement("script") synchronously

This looks like a decent overview of dynamic script loading: http://unixpapa.com/js/dyna.html

How to get Last record from Sqlite?

in sqlite, there is a table called sqlite_sequence, this table contains the table name and it's last id number (if the id is auto incremented).

So, to get the last row in a table just put :

Select * from TABLENAME where id=(SELECT * from sqlite_sequence where name ='TABLENAME')

Using Jquery Ajax to retrieve data from Mysql

Please make sure your $row[1] , $row[2] contains correct value, we do assume here that 1 = Name , and 2 here is your Address field ?

Assuming you have correctly fetched your records from your Records.php, You can do something like this:

$(document).ready(function()
{
    $('#getRecords').click(function()
    {
        var response = '';
        $.ajax({ type: 'POST',   
                 url: "Records.php",   
                 async: false,
                 success : function(text){
                               $('#table1').html(text);
                           }
           });
    });

}

In your HTML

<table id="table1"> 
    //Let jQuery AJAX Change This Text  
</table>
<button id='getRecords'>Get Records</button>

A little note:

Try learing PDO http://php.net/manual/en/class.pdo.php since mysql_* functions are no longer encouraged..

Center Align on a Absolutely Positioned Div

Your problem may be solved if you give your div a fixed width, as follows:

div#thing {
    position: absolute;
    top: 0px;
    z-index: 2;
    width:400px;
    margin-left:-200px;
    left:50%;
}

How can I get double quotes into a string literal?

Escape the quotes with backslashes:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

Disable all table constraints in Oracle

Use following cursor to disable all constraint.. And alter query for enable constraints...

DECLARE

cursor r1 is select * from user_constraints;
cursor r2 is select * from user_tables;

BEGIN
  FOR c1 IN r1
  loop
    for c2 in r2
    loop
       if c1.table_name = c2.table_name and c1.status = 'ENABLED' THEN
        dbms_utility.exec_ddl_statement('alter table ' || c1.owner || '.' || c1.table_name || ' disable constraint ' || c1.constraint_name);
       end if;
    end loop;
  END LOOP;
END;
/

How do I set a variable to the output of a command in Bash?

You need to use either

$(command-here)

or

`command-here`

Example

#!/bin/bash

VAR1="$1"
VAR2="$2"

MOREF="$(sudo run command against "$VAR1" | grep name | cut -c7-)"

echo "$MOREF"

Bootstrap 3 and Youtube in Modal

If you don't want to edit the bootstrap CSS or all of the above doesn't help you at all (like in my case), there's an easy fix to get the video running in a modal on Firefox.

You just need to remove the "fade" class from the modal and as it opens the "in" class, too:

$('#myModal').on('shown.bs.modal', function () {
    $('#myModal').removeClass('in');
});

What is a daemon thread in Java?

A few more points (Reference: Java Concurrency in Practice)

  • When a new thread is created it inherits the daemon status of its parent.
  • When all non-daemon threads finish, the JVM halts, and any remaining daemon threads are abandoned:

    • finally blocks are not executed,
    • stacks are not unwound - the JVM just exits.

    Due to this reason daemon threads should be used sparingly, and it is dangerous to use them for tasks that might perform any sort of I/O.

How to construct a REST API that takes an array of id's for the resources

 api.com/users?id=id1,id2,id3,id4,id5
 api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

IMO, above calls does not looks RESTful, however these are quick and efficient workaround (y). But length of the URL is limited by webserver, eg tomcat.

RESTful attempt:

POST http://example.com/api/batchtask

   [
    {
      method : "GET",
      headers : [..],
      url : "/users/id1"
    },
    {
      method : "GET",
      headers : [..],
      url : "/users/id2"
    }
   ]

Server will reply URI of newly created batchtask resource.

201 Created
Location: "http://example.com/api/batchtask/1254"

Now client can fetch batch response or task progress by polling

GET http://example.com/api/batchtask/1254


This is how others attempted to solve this issue:

<script> tag vs <script type = 'text/javascript'> tag

You only need <script></script> Tag that's it. <script type="text/javascript"></script> is not a valid HTML tag, so for best SEO practice use <script></script>

How to suppress binary file matching results in grep

This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:

bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk  ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$

How to check if a String contains only ASCII?

Here is another way not depending on a library but using a regex.

You can use this single line:

text.matches("\\A\\p{ASCII}*\\z")

Whole example program:

public class Main {
    public static void main(String[] args) {
        char nonAscii = 0x00FF;
        String asciiText = "Hello";
        String nonAsciiText = "Buy: " + nonAscii;
        System.out.println(asciiText.matches("\\A\\p{ASCII}*\\z"));
        System.out.println(nonAsciiText.matches("\\A\\p{ASCII}*\\z"));
    }
}

How to find elements with 'value=x'?

$(selector).filter(function(){return this.value==yourval}).remove();

How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

You probably haven't installed GLUT:

  1. Install GLUT If you do not have GLUT installed on your machine you can download it from: http://www.xmission.com/~nate/glut/glut-3.7.6-bin.zip (or whatever version) GLUT Libraries and header files are • glut32.lib • glut.h

Source: http://cacs.usc.edu/education/cs596/OGL_Setup.pdf

EDIT:

The quickest way is to download the latest header, and compiled DLLs for it, place it in your system32 folder or reference it in your project. Version 3.7 (latest as of this post) is here: http://www.opengl.org/resources/libraries/glut/glutdlls37beta.zip

Folder references:

glut.h: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\GL\'
glut32.lib: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\'
glut32.dll: 'C:\Windows\System32\'

For 64-bit machines, you will want to do this.
glut32.dll: 'C:\Windows\SysWOW64\'

Same pattern applies to freeglut and GLEW files with the header files in the GL folder, lib in the lib folder, and dll in the System32 (and SysWOW64) folder.
1. Under Visual C++, select Empty Project.
2. Go to Project -> Properties. Select Linker -> Input then add the following to the Additional Dependencies field:
opengl32.lib
glu32.lib
glut32.lib

Reprinted from here

Getting number of days in a month

You want DateTime.DaysInMonth:

int days = DateTime.DaysInMonth(year, month);

Obviously it varies by year, as sometimes February has 28 days and sometimes 29. You could always pick a particular year (leap or not) if you want to "fix" it to one value or other.

How to specify the port an ASP.NET Core application is hosted on?

Above .net core 2.2 the method Main support args with WebHost.CreateDefaultBuilder(args)

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

You can build your project and go to bin run command like this

dotnet <yours>.dll --urls=http://localhost:5001

or with multi-urls

dotnet <yours>.dll --urls="http://localhost:5001,https://localhost:5002"

How can I delay a :hover effect in CSS?

For a more aesthetic appearance :) can be:

left:-9999em; 
top:-9999em; 

position for .sNv2 .nav UL can be replaced by z-index:-1 and z-index:1 for .sNv2 .nav LI:Hover UL

How do I overload the square-bracket operator in C#?

That would be the item property: http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx

Maybe something like this would work:

public T Item[int index, int y]
{ 
    //Then do whatever you need to return/set here.
    get; set; 
}

Simple way to sort strings in the (case sensitive) alphabetical order

I recently answered a similar question here. Applying the same approach to your problem would yield following solution:

list.sort(
  p2Ord(stringOrd, stringOrd).comap(new F<String, P2<String, String>>() {
    public P2<String, String> f(String s) {
      return p(s.toLowerCase(), s);
    }
  })
);

php exec command (or similar) to not wait for result

I know this question has been answered but the answers i found here didn't work for my scenario ( or for Windows ).

I am using windows 10 laptop with PHP 7.2 in Xampp v3.2.4.

$command = 'php Cron.php send_email "'. $id .'"';
if ( substr(php_uname(), 0, 7) == "Windows" )
{
    //windows
    pclose(popen("start /B " . $command . " 1> temp/update_log 2>&1 &", "r"));
}
else
{
    //linux
    shell_exec( $command . " > /dev/null 2>&1 &" );
}

This worked perfectly for me.

I hope it will help someone with windows. Cheers.

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

The excellent library Type::Tiny provides an framework with which to build type-checking into your Perl code. What I show here is only the thinnest tip of the iceberg and is using Type::Tiny in the most simplistic and manual way.

Be sure to check out the Type::Tiny::Manual for more information.

use Types::Common::String qw< NonEmptyStr >;

if ( NonEmptyStr->check($name) ) {
    # Do something here.
}

NonEmptyStr->($name);  # Throw an exception if validation fails

What does this format means T00:00:00.000Z?

As one person may have already suggested,

I passed the ISO 8601 date string directly to moment like so...

`moment.utc('2019-11-03T05:00:00.000Z').format('MM/DD/YYYY')`

or

`moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')`

either of these solutions will give you the same result.

`console.log(moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')) // 11/3/2019`

What is uintptr_t data type

Running the risk of getting another Necromancer badge, I would like to add one very good use for uintptr_t (or even intptr_t) and that is writing testable embedded code. I write mostly embedded code targeted at various arm and currently tensilica processors. These have various native bus width and the tensilica is actually a Harvard architecture with separate code and data buses that can be different widths. I use a test driven development style for much of my code which means I do unit tests for all the code units I write. Unit testing on actual target hardware is a hassle so I typically write everything on an Intel based PC either in Windows or Linux using Ceedling and GCC. That being said, a lot of embedded code involves bit twiddling and address manipulations. Most of my Intel machines are 64 bit. So if you are going to test address manipulation code you need a generalized object to do math on. Thus the uintptr_t give you a machine independent way of debugging your code before you try deploying to target hardware. Another issue is for the some machines or even memory models on some compilers, function pointers and data pointers are different widths. On those machines the compiler may not even allow casting between the two classes, but uintptr_t should be able to hold either. -- Edit -- Was pointed out by @chux, this is not part of the standard and functions are not objects in C. However it usually works and since many people don't even know about these types I usually leave a comment explaining the trickery. Other searches in SO on uintptr_t will provide further explanation. Also we do things in unit testing that we would never do in production because breaking things is good.

How to check if a table contains an element in Lua?

I can't think of another way to compare values, but if you use the element of the set as the key, you can set the value to anything other than nil. Then you get fast lookups without having to search the entire table.

Why is the console window closing immediately once displayed my output?

If you want to keep your application opened, you have to do something in order to keep its process alive. The below example is the simplest one, to be put at the end of your program:

while (true) ;

However, it'll cause the CPU to overload, as it's therefore forced to iterate infinitely.

At this point, you can opt to use System.Windows.Forms.Application class (but it requires you to add System.Windows.Forms reference):

Application.Run();

This doesn't leak CPU and works successfully.

In order to avoid to add System.Windows.Forms reference, you can use a simple trick, the so-called spin waiting, importing System.Threading:

SpinWait.SpinUntil(() => false);

This also works perfectly, and it basically consists of a while loop with a negated condition that is returned by the above lambda method. Why isn't this overloading CPU? You can look at the source code here; anyway, it basically waits some CPU cycle before iterating over.

You can also create a message looper, which peeks the pending messages from the system and processes each of them before passing to the next iteration, as follows:

[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "PeekMessage")]
public static extern int PeekMessage(out NativeMessage lpMsg, IntPtr hWnd, int wMsgFilterMin, int wMsgFilterMax, int wRemoveMsg);

[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "GetMessage")]
public static extern int GetMessage(out NativeMessage lpMsg, IntPtr hWnd, int wMsgFilterMin, int wMsgFilterMax);

[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "TranslateMessage")]
public static extern int TranslateMessage(ref NativeMessage lpMsg);

[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode, DllImport("user32.dll", EntryPoint = "DispatchMessage")]
public static extern int DispatchMessage(ref NativeMessage lpMsg);

[DebuggerHidden, DebuggerStepperBoundary, DebuggerNonUserCode]
public static bool ProcessMessageOnce()
{
    NativeMessage message = new NativeMessage();

    if (!IsMessagePending(out message))
        return true;

    if (GetMessage(out message, IntPtr.Zero, 0, 0) == -1)
        return true;

    Message frameworkMessage = new Message()
    {
        HWnd = message.handle,
        LParam = message.lParam,
        WParam = message.wParam,
        Msg = (int)message.msg
    };

    if (Application.FilterMessage(ref frameworkMessage))
        return true;

    TranslateMessage(ref message);
    DispatchMessage(ref message);

    return false;
}

Then, you can loop safely by doing something like this:

while (true)
    ProcessMessageOnce();

How to get info on sent PHP curl request

The request is printed in a request.txt with details

$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL            => $url, 
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE        => 1,
CURLOPT_STDERR         => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);

You can also use curl_getinfo() function.

Add column with number of days between dates in DataFrame pandas

A list comprehension is your best bet for the most Pythonic (and fastest) way to do this:

[int(i.days) for i in (df.B - df.A)]
  1. i will return the timedelta(e.g. '-58 days')
  2. i.days will return this value as a long integer value(e.g. -58L)
  3. int(i.days) will give you the -58 you seek.

If your columns aren't in datetime format. The shorter syntax would be: df.A = pd.to_datetime(df.A)

What is the difference between application server and web server?

In Java terms, there's one more: web container (or more strictly, servlet container). It's, say, in between web server and application server.

A web container in Java terms is an application server that basically only implements the JSP/Servlet part of Java EE and lacks several core parts of Java EE, such as EJB support. An example is Apache Tomcat.

getResources().getColor() is deprecated

You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).

ContextCompat.getColor(context, R.color.my_color)

As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.

You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:

compile 'com.android.support:support-v4:23.0.1'

Check for database connection, otherwise display message

Try this:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

Get GPS location from the web browser

To give a bit more specific answer. HTML5 allows you to get the geo coordinates, and it does a pretty decent job. Overall the browser support for geolocation is pretty good, all major browsers except ie7 and ie8 (and opera mini). IE9 does the job but is the worst performer. Checkout caniuse.com:

http://caniuse.com/#search=geol

Also you need the approval of your user to access their location, so make sure you check for this and give some decent instructions in case it's turned off. Especially for Iphone turning permissions on for Safari is a bit cumbersome.

How to display image from database using php

instead of print $image; you should go for print "<img src=<?$image;?>>"

and note that $image should contain the path of your image.

So, If you are only storing the name of your image in database then instead of that you have to store the full path of your image in the database like /root/user/Documents/image.jpeg.

PHP foreach with Nested Array?

foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

What is the difference between java and core java?

Java has mainly three sub categories :

  1. Java Standard Edition (JSE) or Core Java
  2. Java Enterprise Edition (JEE)
  3. Java Mobile Edition (JME)

where core java is the first and basic step of all to start or learn java from beginning.

Android EditText Hint

et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            et.setHint(temp +" Characters");
        }
    });

How do I vertically center an H1 in a div?

This is the jQuery method. Looks like overkill but it calculates the offset.

<html>
<head>
<title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://raw.github.com/dreamerslab/jquery.center/master/jquery.center.js"></script>
    <script type="text/javascript">
        $(function(){

            $('#jquery-center').center();

        });
    </script>

</head>
<body>
    <div id="jquery-center" style="position:absolute;">
       <h1>foo</h1>
    </div>
</body>
</html>

How to run a specific Android app using Terminal?

I used all the above answers and it was giving me errors so I tried

adb shell monkey -p com.yourpackage.name -c android.intent.category.LAUNCHER 1

and it worked. One advantage is you dont have to specify your launcher activity if you use this command.

Visual Studio Code: format is not using indent settings

The number of spaces to use for formatting is taken from a different location. I'm using version 1.0 and this is what I've done to fix it (I'm assuming your using spaces instead of tabs):

At the bottom of the editor on the right hand click "Spaces: #":

status bar on the right

Then a menu will appear up top. Select "Indent Using Spaces":

select indentation type

Finally you can select by how many spaces you want your files to be indented.

select tab size

The next time you format a file you should be able to get the spacing you configured.

Application_Start not firing?

Did you check the Project settings? I had this problem and I had the Start URL going to a different port than my server specific port. It took me too long to figure out...

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

Spring JPA @Query with LIKE

@Query("select b.equipSealRegisterId from EquipSealRegister b where b.sealName like %?1% and b.deleteFlag = '0'" )
    List<String>findBySeal(String sealname);

I have tried this code and it works.

ES6 exporting/importing in index file

Nav.js comp inside components folder

export {Nav}

index.js in component folder

export {Nav} from './Nav';
export {Another} from './Another';

import anywhere

import {Nav, Another} from './components'

Keeping session alive with Curl and PHP

Yup, often called a 'cookie jar' Google should provide many examples:

http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/

http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO

Copying that last one here so it does not go away...

Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell

<?php
/*
This script is an example of using curl in php to log into on one page and 
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into 
thinking its netscape and even pass a fake referer, yo look like it surfed 
from a local page.
*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo "<PRE>".htmlentities($buf2);
?>  

Connection refused to MongoDB errno 111

In my case previous version was 3.2. I have upgraded to 3.6 but data files was not compatible to new version so I removed all data files as it was not usable for me and its works.

You can check logs using /var/log/mongodb

How to create a custom-shaped bitmap marker with Android map API v2

The alternative and easier solution that i also use is to create custom marker layout and convert it into a bitmap.

view_custom_marker.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_marker_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/marker_mask">

    <ImageView
        android:id="@+id/profile_image"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="center_horizontal"
        android:contentDescription="@null"
        android:src="@drawable/avatar" />
</FrameLayout>

Convert this view into bitmap by using the code below

 private Bitmap getMarkerBitmapFromView(@DrawableRes int resId) {

        View customMarkerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.view_custom_marker, null);
        ImageView markerImageView = (ImageView) customMarkerView.findViewById(R.id.profile_image);
        markerImageView.setImageResource(resId);
        customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
        customMarkerView.buildDrawingCache();
        Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
        Drawable drawable = customMarkerView.getBackground();
        if (drawable != null)
            drawable.draw(canvas);
        customMarkerView.draw(canvas);
        return returnedBitmap;
    }

Add your custom marker in on Map ready callback.

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.d(TAG, "onMapReady() called with");
    mGoogleMap = googleMap;
    MapsInitializer.initialize(this);
    addCustomMarker();
}
private void addCustomMarker() {
    Log.d(TAG, "addCustomMarker()");
    if (mGoogleMap == null) {
        return;
    }

    // adding a marker on map with image from  drawable
   mGoogleMap.addMarker(new MarkerOptions()
            .position(mDummyLatLng)
            .icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(R.drawable.avatar))));
}

For more details please follow the link below

How to create custom marker using layout?

Operation Not Permitted when on root - El Capitan (rootless disabled)

Nvm. For anyone else having this problem you need to reboot your mac and press ?+R when booting up. Then go into Utilities > Terminal and type the following commands:

csrutil disable
reboot 

This is a result of System Integrity Protection. More info here.

EDIT

If you know what you are doing and are used to running Linux, you should use the above solution as many of the SIP restrictions are a complete pain in the ass.

However, if you are a tinkerer/noob/"poweruser" and don't know what you are doing, this can be very dangerous and you are better off using the answer below.

Can there exist two main methods in a Java program?

Yes! Any class in Java can have multiple main methods. It's called Overloading (Overloaded methods are methods with same name but with different signatures) but there should only be one main method with parameters like this :- (String[] args) or (String args[])

For example :-public class E {

public static void main(String args){
    System.out.println("Print A");
}
public static void main(String [] args){
    System.out.println("Print B");
}
public static void main(int garbage){
    System.out.println("Print C");
}
public static void main(int i){
    System.out.println("Print D")
}

}

The output of the above program will be "Print B" as only that main method contains the correct method signature identified by the Javac compiler and it compiles that only and leaves the rest.

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

Insert text with single quotes in PostgreSQL

This is so many worlds of bad, because your question implies that you probably have gaping SQL injection holes in your application.

You should be using parameterized statements. For Java, use PreparedStatement with placeholders. You say you don't want to use parameterised statements, but you don't explain why, and frankly it has to be a very good reason not to use them because they're the simplest, safest way to fix the problem you are trying to solve.

See Preventing SQL Injection in Java. Don't be Bobby's next victim.

There is no public function in PgJDBC for string quoting and escaping. That's partly because it might make it seem like a good idea.

There are built-in quoting functions quote_literal and quote_ident in PostgreSQL, but they are for PL/PgSQL functions that use EXECUTE. These days quote_literal is mostly obsoleted by EXECUTE ... USING, which is the parameterised version, because it's safer and easier. You cannot use them for the purpose you explain here, because they're server-side functions.


Imagine what happens if you get the value ');DROP SCHEMA public;-- from a malicious user. You'd produce:

insert into test values (1,'');DROP SCHEMA public;--');

which breaks down to two statements and a comment that gets ignored:

insert into test values (1,'');
DROP SCHEMA public;
--');

Whoops, there goes your database.

Is ncurses available for windows?

Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.

ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.

The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).

A better option

Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses (and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.

How to sort a data frame by alphabetic order of a character variable in R?

This really belongs with @Ramnath's answer but I can't comment as I don't have enough reputation yet. You can also use the arrange function from the dplyr package in the same way as the plyr package.

library(dplyr)
arrange(DF, ID, desc(num))

Run ssh and immediately execute command

This isn't quite what you're looking for, but I've found it useful in similar circumstances.

I recently added the following to my $HOME/.bashrc (something similar should be possible with shells other than bash):

if [ -f $HOME/.add-screen-to-history ] ; then
    history -s 'screen -dr'
fi

I keep a screen session running on one particular machine, and I've had problems with ssh connections to that machine being dropped, requiring me to re-run screen -dr every time I reconnect.

With that addition, and after creating that (empty) file in my home directory, I automatically have the screen -dr command in my history when my shell starts. After reconnecting, I can just type Control-P Enter and I'm back in my screen session -- or I can ignore it. It's flexible, but not quite automatic, and in your case it's easier than typing tmux list-sessions.

You might want to make the history -s command unconditional.

This does require updating your $HOME/.bashrc on each of the target systems, which might or might not make it unsuitable for your purposes.

Google Authenticator available as a public service?

Not LAMP but if you use C# this is the code I use:

Code originally from:

https://github.com/kspearrin/Otp.NET

The Base32Encoding class is from this answer:

https://stackoverflow.com/a/7135008/3850405

Example program:

class Program
{
    static void Main(string[] args)
    {
        var bytes = Base32Encoding.ToBytes("JBSWY3DPEHPK3PXP");

        var totp = new Totp(bytes);

        var result = totp.ComputeTotp();
        var remainingTime = totp.RemainingSeconds();
    }
}

Totp:

public class Totp
{
    const long unixEpochTicks = 621355968000000000L;

    const long ticksToSeconds = 10000000L;

    private const int step = 30;

    private const int totpSize = 6;

    private byte[] key;

    public Totp(byte[] secretKey)
    {
        key = secretKey;
    }

    public string ComputeTotp()
    {
        var window = CalculateTimeStepFromTimestamp(DateTime.UtcNow);

        var data = GetBigEndianBytes(window);

        var hmac = new HMACSHA1();
        hmac.Key = key;
        var hmacComputedHash = hmac.ComputeHash(data);

        int offset = hmacComputedHash[hmacComputedHash.Length - 1] & 0x0F;
        var otp = (hmacComputedHash[offset] & 0x7f) << 24
               | (hmacComputedHash[offset + 1] & 0xff) << 16
               | (hmacComputedHash[offset + 2] & 0xff) << 8
               | (hmacComputedHash[offset + 3] & 0xff) % 1000000;

        var result = Digits(otp, totpSize);

        return result;
    }

    public int RemainingSeconds()
    {
        return step - (int)(((DateTime.UtcNow.Ticks - unixEpochTicks) / ticksToSeconds) % step);
    }

    private byte[] GetBigEndianBytes(long input)
    {
        // Since .net uses little endian numbers, we need to reverse the byte order to get big endian.
        var data = BitConverter.GetBytes(input);
        Array.Reverse(data);
        return data;
    }

    private long CalculateTimeStepFromTimestamp(DateTime timestamp)
    {
        var unixTimestamp = (timestamp.Ticks - unixEpochTicks) / ticksToSeconds;
        var window = unixTimestamp / (long)step;
        return window;
    }

    private string Digits(long input, int digitCount)
    {
        var truncatedValue = ((int)input % (int)Math.Pow(10, digitCount));
        return truncatedValue.ToString().PadLeft(digitCount, '0');
    }

}

Base32Encoding:

public static class Base32Encoding
{
    public static byte[] ToBytes(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            throw new ArgumentNullException("input");
        }

        input = input.TrimEnd('='); //remove padding characters
        int byteCount = input.Length * 5 / 8; //this must be TRUNCATED
        byte[] returnArray = new byte[byteCount];

        byte curByte = 0, bitsRemaining = 8;
        int mask = 0, arrayIndex = 0;

        foreach (char c in input)
        {
            int cValue = CharToValue(c);

            if (bitsRemaining > 5)
            {
                mask = cValue << (bitsRemaining - 5);
                curByte = (byte)(curByte | mask);
                bitsRemaining -= 5;
            }
            else
            {
                mask = cValue >> (5 - bitsRemaining);
                curByte = (byte)(curByte | mask);
                returnArray[arrayIndex++] = curByte;
                curByte = (byte)(cValue << (3 + bitsRemaining));
                bitsRemaining += 3;
            }
        }

        //if we didn't end with a full byte
        if (arrayIndex != byteCount)
        {
            returnArray[arrayIndex] = curByte;
        }

        return returnArray;
    }

    public static string ToString(byte[] input)
    {
        if (input == null || input.Length == 0)
        {
            throw new ArgumentNullException("input");
        }

        int charCount = (int)Math.Ceiling(input.Length / 5d) * 8;
        char[] returnArray = new char[charCount];

        byte nextChar = 0, bitsRemaining = 5;
        int arrayIndex = 0;

        foreach (byte b in input)
        {
            nextChar = (byte)(nextChar | (b >> (8 - bitsRemaining)));
            returnArray[arrayIndex++] = ValueToChar(nextChar);

            if (bitsRemaining < 4)
            {
                nextChar = (byte)((b >> (3 - bitsRemaining)) & 31);
                returnArray[arrayIndex++] = ValueToChar(nextChar);
                bitsRemaining += 5;
            }

            bitsRemaining -= 3;
            nextChar = (byte)((b << bitsRemaining) & 31);
        }

        //if we didn't end with a full char
        if (arrayIndex != charCount)
        {
            returnArray[arrayIndex++] = ValueToChar(nextChar);
            while (arrayIndex != charCount) returnArray[arrayIndex++] = '='; //padding
        }

        return new string(returnArray);
    }

    private static int CharToValue(char c)
    {
        int value = (int)c;

        //65-90 == uppercase letters
        if (value < 91 && value > 64)
        {
            return value - 65;
        }
        //50-55 == numbers 2-7
        if (value < 56 && value > 49)
        {
            return value - 24;
        }
        //97-122 == lowercase letters
        if (value < 123 && value > 96)
        {
            return value - 97;
        }

        throw new ArgumentException("Character is not a Base32 character.", "c");
    }

    private static char ValueToChar(byte b)
    {
        if (b < 26)
        {
            return (char)(b + 65);
        }

        if (b < 32)
        {
            return (char)(b + 24);
        }

        throw new ArgumentException("Byte is not a value Base32 value.", "b");
    }

}

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

How to add include path in Qt Creator?

To add global include path use custom command for qmake in Projects/Build/Build Steps section in "Additional arguments" like this: "QT+=your_qt_modules" "DEFINES+=your_defines"

I think that you can use any command from *.pro files in that way.

How to import Google Web Font in CSS file?

Download the font ttf/other format files, then simply add this CSS code example:

_x000D_
_x000D_
@font-face { font-family: roboto-regular; _x000D_
    src: url('../font/Roboto-Regular.ttf'); } _x000D_
h2{_x000D_
 font-family: roboto-regular;_x000D_
}
_x000D_
_x000D_
_x000D_

Set textbox to readonly and background color to grey in jquery

If supported by your browser, you may use CSS3 :read-only selector:

input[type="text"]:read-only {
    cursor: normal;
    background-color: #f8f8f8;
    color: #999;
}

Maximum size of an Array in Javascript

No need to trim the array, simply address it as a circular buffer (index % maxlen). This will ensure it never goes over the limit (implementing a circular buffer means that once you get to the end you wrap around to the beginning again - not possible to overrun the end of the array).

For example:

var container = new Array ();
var maxlen = 100;
var index = 0;

// 'store' 1538 items (only the last 'maxlen' items are kept)
for (var i=0; i<1538; i++) {
   container [index++ % maxlen] = "storing" + i;
}

// get element at index 11 (you want the 11th item in the array)
eleventh = container [(index + 11) % maxlen];

// get element at index 11 (you want the 11th item in the array)
thirtyfifth = container [(index + 35) % maxlen];

// print out all 100 elements that we have left in the array, note
// that it doesn't matter if we address past 100 - circular buffer
// so we'll simply get back to the beginning if we do that.
for (i=0; i<200; i++) {
   document.write (container[(index + i) % maxlen] + "<br>\n");
}

NotificationCompat.Builder deprecated in Android O

enter image description here

Here is working code for all android versions as of API LEVEL 26+ with backward compatibility.

 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");

        notificationBuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker("Hearty365")
                .setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
                .setContentTitle("Default notification")
                .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
                .setContentInfo("Info");

NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());

UPDATE for API 26 to set Max priority

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);

        // Configure the notification channel.
        notificationChannel.setDescription("Channel description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }


    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

    notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker("Hearty365")
       //     .setPriority(Notification.PRIORITY_MAX)
            .setContentTitle("Default notification")
            .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            .setContentInfo("Info");

    notificationManager.notify(/*notification id*/1, notificationBuilder.build());

PivotTable's Report Filter using "greater than"

I can't say how much this might help you, but just found a solution to something similar problem which I faced. In the Pivot-

  1. Right click and choose Pivot table options
  2. Choose the display option
  3. uncheck the first 'Show expand/Collapse buttons'
  4. check the 'Classic PivotTable Layout(enables dragging of fields in the grid)
  5. click ok.

This would refine the data. Then, I had just copy and pasted this data in a new tab wherein I had applied the filters to my Total column with values greater than certain percentage.

This did work in my case and hope it helps you too.

How to hide the Google Invisible reCAPTCHA badge

For users of Contact Form 7 on Wordpress this method is working for me: I hide the v3 Recaptcha on all pages except those with Contact 7 Forms.

But this method should work on any site where you are using a unique class selector which can identify all pages with text input form elements.

First, I added a target style rule in CSS which can collapse the tile:

CSS

 div.grecaptcha-badge.hide{
    width:0 !important;
}

Then I added JQuery script in my header to trigger after the window loads so the 'grecaptcha-badge' class selector is available to JQuery, and can add the 'hide' class to apply the available CSS style.

$(window).load(function () { 
    if(!($('.wpcf7').length)){ 
      $('.grecaptcha-badge').addClass( 'hide' );
       }
});

My tile still will flash on every page for a half a second, but it's the best workaround I've found so far that I hope will comply. Suggestions for improvement appreciated.

Change User Agent in UIWebView

It should work with an NSMutableURLRequest as Kuso has written.

NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://www.google.com/"]];
[urlRequest setValue: @"iPhone" forHTTPHeaderField: @"User-Agent"]; // Or any other User-Agent value.

You'll have to use NSURLConnection to get the responseData. Set the responseData to your UIWebView and the webView should render:

[webView loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL];

How to clean up R memory (without the need to restart my PC)?

Just adding this for reference in case anybody needs to restart and immediatly run a command.

I'm using this approach just to clear RAM from the system. Make sure you have deleted all objects no longer required. Maybe gc() can also help before hand. But nothing will clear RAM better as restarting the R session.

library(rstudioapi)
restartSession(command = "print('x')")

Model Binding to a List MVC 4

A clean solution could be create a generic class to handle the list, so you don't need to create a different class each time you need it.

public class ListModel<T>
{
    public List<T> Items { get; set; }

    public ListModel(List<T> list) {
        Items = list;
    }
}

and when you return the View you just need to simply do:

List<customClass> ListOfCustomClass = new List<customClass>();
//Do as needed...
return View(new ListModel<customClass>(ListOfCustomClass));

then define the list in the model:

@model ListModel<customClass>

and ready to go:

@foreach(var element in Model.Items) {
  //do as needed...
}

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Are HTTP headers case-sensitive?

Header names are not case sensitive.

From RFC 2616 - "Hypertext Transfer Protocol -- HTTP/1.1", Section 4.2, "Message Headers":

Each header field consists of a name followed by a colon (":") and the field value. Field names are case-insensitive.

The updating RFC 7230 does not list any changes from RFC 2616 at this part.

How do I remove the blue styling of telephone numbers on iPhone/iOS?

This x-ms-format-detection="none" attribute handle the format phone.

https://msdn.microsoft.com/en-us/library/dn337007(v=vs.85).aspx

<p id="phone-text" x-ms-format-detection="none"  >Call us on <strong>+44 (0)20 7194 8000</strong></p>

Question mark and colon in JavaScript

hsb.s = max != 0 ? 255 * delta / max : 0;

? is a ternary operator. It works like an if in conjunction with the :

!= means not equals

So, the long form of this line would be

if (max != 0) { //if max is not zero
  hsb.s = 255 * delta / max;
} else {
  hsb.s = 0;
}

Is it worth using Python's re.compile?

For me, the biggest benefit to re.compile is being able to separate definition of the regex from its use.

Even a simple expression such as 0|[1-9][0-9]* (integer in base 10 without leading zeros) can be complex enough that you'd rather not have to retype it, check if you made any typos, and later have to recheck if there are typos when you start debugging. Plus, it's nicer to use a variable name such as num or num_b10 than 0|[1-9][0-9]*.

It's certainly possible to store strings and pass them to re.match; however, that's less readable:

num = "..."
# then, much later:
m = re.match(num, input)

Versus compiling:

num = re.compile("...")
# then, much later:
m = num.match(input)

Though it is fairly close, the last line of the second feels more natural and simpler when used repeatedly.

What is the best way to add a value to an array in state

If you want to keep adding a new object to the array i've been using:

_methodName = (para1, para2) => {
  this.setState({
    arr: this.state.arr.concat({para1, para2})
  })
}

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

Note that in an attribute selector (e.g., [attr~=value]), the tilde

Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

How to display HTML tags as plain text

you may use htmlspecialchars()

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

How can I find out if I have Xcode commandline tools installed?

If for some reason xcode is not installed under

/usr/bin/xcodebuild

execute the following command

which xcodebuild

and if it is installed, you'll be prompted with it's location.

Sprintf equivalent in Java

Both solutions workto simulate printf, but in a different way. For instance, to convert a value to a hex string, you have the 2 following solutions:

  • with format(), closest to sprintf():

    final static String HexChars = "0123456789abcdef";
    
    public static String getHexQuad(long v) {
        String ret;
        if(v > 0xffff) ret = getHexQuad(v >> 16); else ret = "";
        ret += String.format("%c%c%c%c",
            HexChars.charAt((int) ((v >> 12) & 0x0f)),
            HexChars.charAt((int) ((v >>  8) & 0x0f)),
            HexChars.charAt((int) ((v >>  4) & 0x0f)),
            HexChars.charAt((int) ( v        & 0x0f)));
        return ret;
    }
    
  • with replace(char oldchar , char newchar), somewhat faster but pretty limited:

        ...
        ret += "ABCD".
            replace('A', HexChars.charAt((int) ((v >> 12) & 0x0f))).
            replace('B', HexChars.charAt((int) ((v >>  8) & 0x0f))).
            replace('C', HexChars.charAt((int) ((v >>  4) & 0x0f))).
            replace('D', HexChars.charAt((int) ( v        & 0x0f)));
        ...
    
  • There is a third solution consisting of just adding the char to ret one by one (char are numbers that add to each other!) such as in:

    ...
    ret += HexChars.charAt((int) ((v >> 12) & 0x0f)));
    ret += HexChars.charAt((int) ((v >>  8) & 0x0f)));
    ...
    

...but that'd be really ugly.

Should operator<< be implemented as a friend or as a member function?

If possible, as non-member and non-friend functions.

As described by Herb Sutter and Scott Meyers, prefer non-friend non-member functions to member functions, to help increase encapsulation.

In some cases, like C++ streams, you won't have the choice and must use non-member functions.

But still, it does not mean you have to make these functions friends of your classes: These functions can still acess your class through your class accessors. If you succeed in writting those functions this way, then you won.

About operator << and >> prototypes

I believe the examples you gave in your question are wrong. For example;

ostream & operator<<(ostream &os) {
    return os << paragraph;
}

I can't even start to think how this method could work in a stream.

Here are the two ways to implement the << and >> operators.

Let's say you want to use a stream-like object of type T.

And that you want to extract/insert from/into T the relevant data of your object of type Paragraph.

Generic operator << and >> function prototypes

The first being as functions:

// T << Paragraph
T & operator << (T & p_oOutputStream, const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return p_oOutputStream ;
}

// T >> Paragraph
T & operator >> (T & p_oInputStream, const Paragraph & p_oParagraph)
{
   // do the extraction of p_oParagraph
   return p_oInputStream ;
}

Generic operator << and >> method prototypes

The second being as methods:

// T << Paragraph
T & T::operator << (const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return *this ;
}

// T >> Paragraph
T & T::operator >> (const Paragraph & p_oParagraph)
{
   // do the extraction of p_oParagraph
   return *this ;
}

Note that to use this notation, you must extend T's class declaration. For STL objects, this is not possible (you are not supposed to modify them...).

And what if T is a C++ stream?

Here are the prototypes of the same << and >> operators for C++ streams.

For generic basic_istream and basic_ostream

Note that is case of streams, as you can't modify the C++ stream, you must implement the functions. Which means something like:

// OUTPUT << Paragraph
template <typename charT, typename traits>
std::basic_ostream<charT,traits> & operator << (std::basic_ostream<charT,traits> & p_oOutputStream, const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return p_oOutputStream ;
}

// INPUT >> Paragraph
template <typename charT, typename traits>
std::basic_istream<charT,traits> & operator >> (std::basic_istream<charT,traits> & p_oInputStream, const CMyObject & p_oParagraph)
{
   // do the extract of p_oParagraph
   return p_oInputStream ;
}

For char istream and ostream

The following code will work only for char-based streams.

// OUTPUT << A
std::ostream & operator << (std::ostream & p_oOutputStream, const Paragraph & p_oParagraph)
{
   // do the insertion of p_oParagraph
   return p_oOutputStream ;
}

// INPUT >> A
std::istream & operator >> (std::istream & p_oInputStream, const Paragraph & p_oParagraph)
{
   // do the extract of p_oParagraph
   return p_oInputStream ;
}

Rhys Ulerich commented about the fact the char-based code is but a "specialization" of the generic code above it. Of course, Rhys is right: I don't recommend the use of the char-based example. It is only given here because it's simpler to read. As it is only viable if you only work with char-based streams, you should avoid it on platforms where wchar_t code is common (i.e. on Windows).

Hope this will help.

How to change line color in EditText

You can do it dynamically if you have custom class for edittext.

First of all you have declare state and color of edittext given below.

int[][] states = new int[][]{
                new int[]{-android.R.attr.state_focused}, // enabled
                new int[]{android.R.attr.state_focused}, // disabled
        };
        int[] colors = new int[]{
                secondaryColor,
                primaryColor,
        };

Then Create ColorStateList variable with that

ColorStateList myList = new ColorStateList(states, colors);

Then last step is to assign it to edittext.

editText.setBackgroundTintList(myList);

After this you have to written on focused change event.

this.setOnFocusChangeListener(new OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View view, boolean b) {
                        setUnderlineColor(selectionColor,deselectionColor);
                    }
                });

And you can make above code inside setUnderlineClor() Method,

private void setUnderlineColor(int primaryColor, int secondaryColor) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        int[][] states = new int[][]{
                new int[]{-android.R.attr.state_focused}, // enabled
                new int[]{android.R.attr.state_focused}, // disabled
        };
        int[] colors = new int[]{
                secondaryColor,
                primaryColor,
        };
        ColorStateList myList = new ColorStateList(states, colors);
        setBackgroundTintList(myList);
    }
}

How to detect orientation change in layout in Android?

For loading the layout in layout-land folder means you have two separate layouts then you have to make setContentView in onConfigurationChanged method.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.yourxmlinlayout-land);
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        setContentView(R.layout.yourxmlinlayoutfolder);
    }
}

If you have only one layout then no necessary to make setContentView in This method. simply

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

Cannot find control with name: formControlName in angular reactive form

you're missing group nested controls with formGroupName directive

<div class="panel-body" formGroupName="address">
  <div class="form-group">
    <label for="address" class="col-sm-3 control-label">Business Address</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
    </div>
  </div>
  <div class="form-group">
    <label for="website" class="col-sm-3 control-label">Website</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="website" placeholder="website">
    </div>
  </div>
  <div class="form-group">
    <label for="telephone" class="col-sm-3 control-label">Telephone</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
    </div>
  </div>
  <div class="form-group">
    <label for="email" class="col-sm-3 control-label">Email</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="email" placeholder="email">
    </div>
  </div>
  <div class="form-group">
    <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
    </div>
  </div>
  <div class="form-group">
    <label for="about" class="col-sm-3  control-label"></label>
    <div class="col-sm-3">
      <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
    </div>
    <label for="about" class="col-sm-2  control-label"></label>
    <div class="col-sm-3">
      <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
    </div>
  </div>
</div>

handling dbnull data in vb.net

You can also use the Convert.ToString() and Convert.ToInteger() methods to convert items with DB null effectivly.

Using OR & AND in COUNTIFS

In a more general case:

N( A union B) = N(A) + N(B) - N(A intersect B) 
= COUNTIFS(A1:A196,"Yes",J1:J196,"Agree")+COUNTIFS(A1:A196,"No",J1:J196,"Agree")-A1:A196,"Yes",A1:A196,"No")

How to use \n new line in VB msgbox() ...?

The message box must end with a text and not with a variable

conflicting types error when compiling c program using gcc

If you don't declare a function and it only appears after being called, it is automatically assumed to be int, so in your case, you didn't declare

void my_print (char *);
void my_print2 (char *);

before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *); and int my_print2 (char *); and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types.

As Brian suggested, declare those two methods before main.

Android ADB stop application command like "force-stop" for non rooted device

The first way
Needs root

Use kill:

adb shell ps => Will list all running processes on the device and their process ids
adb shell kill <PID> => Instead of <PID> use process id of your application

The second way
In Eclipse open DDMS perspective.
In Devices view you will find all running processes.
Choose the process and click on Stop.

enter image description here

The third way
It will kill only background process of an application.

adb shell am kill [options] <PACKAGE> => Kill all processes associated with (the app's package name). This command kills only processes that are safe to kill and that will not impact the user experience.
Options are:

--user | all | current: Specify user whose processes to kill; all users if not specified.

The fourth way
Needs root

adb shell pm disable <PACKAGE> => Disable the given package or component (written as "package/class").

The fifth way
Note that run-as is only supported for apps that are signed with debug keys.

run-as <package-name> kill <pid>

The sixth way
Introduced in Honeycomb

adb shell am force-stop <PACKAGE> => Force stop everything associated with (the app's package name).

P.S.: I know that the sixth method didn't work for you, but I think that it's important to add this method to the list, so everyone will know it.

offsetTop vs. jQuery.offset().top

Try this: parseInt(jQuery.offset().top, 10)

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

To be safe, you should use the proper APIs in Powershell (or VBScript)
Using PowerShell:

[Environment]::GetFolderPath("Desktop")

Copy something using Powershell:

Copy-Item $home\*.txt ([Environment]::GetFolderPath("Desktop"))

Here is a VBScript-example to get the desktop path:

dim WSHShell, desktop, pathstring, objFSO
set objFSO=CreateObject("Scripting.FileSystemObject")
Set WSHshell = CreateObject("WScript.Shell")
desktop = WSHShell.SpecialFolders("Desktop")
pathstring = objFSO.GetAbsolutePathName(desktop)
WScript.Echo pathstring

Convert UTC Epoch to local date

To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.

$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"

2/7/2018, 19:35:24

or as JS:

var date = new Date(Date.now()); 
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24

console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24

Note: The use of en-GB here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!

Unable to open project... cannot be opened because the project file cannot be parsed

subversion will corrupt my project file after a svn up on an almost weekly basis. I'm trying to figure out why it does this right now and came across this problem.

How to Find App Pool Recycles in Event Log

As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:

Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}

From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.

This along with @BlackHawkDesign comment should help you find what you need.

I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00

What is the easiest way to remove all packages installed by pip?

I wanted to elevate this answer out of a comment section because it's one of the most elegant solutions in the thread. Full credit for this answer goes to @joeb.

pip uninstall -y -r <(pip freeze)

This worked great for me for the use case of clearing my user packages folder outside the context of a virtualenv which many of the above answers don't handle.

Edit: Anyone know how to make this command work in a Makefile?

Bonus: A bash alias

I add this to my bash profile for convenience:

alias pipuninstallall="pip uninstall -y -r <(pip freeze)"

Then run:

pipuninstallall

Alternative for pipenv

If you happen to be using pipenv you can just run:

pipenv uninstall --all

Content Type text/xml; charset=utf-8 was not supported by service

First Google hit says:

this is usually a mismatch in the client/server bindings, where the message version in the service uses SOAP 1.2 (which expects application/soap+xml) and the version in the client uses SOAP 1.1 (which sends text/xml). WSHttpBinding uses SOAP 1.2, BasicHttpBinding uses SOAP 1.1.

It usually seems to be a wsHttpBinding on one side and a basicHttpBinding on the other.

MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

How to set a default Value of a UIPickerView

For example: you populated your UIPickerView with array values, then you wanted 

to select a certain array value in the first load of pickerView like "Arizona". Note that the word "Arizona" is at index 2. This how to do it :) Enjoy coding.

NSArray *countryArray =[NSArray arrayWithObjects:@"Alabama",@"Alaska",@"Arizona",@"Arkansas", nil];
UIPickerView *countryPicker=[[UIPickerView alloc]initWithFrame:self.view.bounds];
countryPicker.delegate=self;
countryPicker.dataSource=self;
[countryPicker selectRow:2 inComponent:0 animated:YES];
[self.view addSubview:countryPicker];

How to embed fonts in CSS?

One of the best source of information on this topic is Paul Irish's Bulletproof @font-face syntax article.

Read it and you will end with something like:

/* definition */
@font-face {
  font-family: EntezareZohoor2;
  src: url('fonts/EntezareZohoor2.eot');
  src: url('fonts/EntezareZohoor2.eot?') format('?'),
       url('fonts/EntezareZohoor2.woff') format('woff'),
       url('fonts/EntezareZohoor2.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

/* use */
body {
    font-family: EntezareZohoor2, Tahoma, serif;
}

What's the difference between console.dir and console.log?

I think Firebug does it differently than Chrome's dev tools. It looks like Firebug gives you a stringified version of the object while console.dir gives you an expandable object. Both give you the expandable object in Chrome, and I think that's where the confusion might come from. Or it's just a bug in Chrome.

In Chrome, both do the same thing. Expanding on your test, I have noticed that Chrome gets the current value of the object when you expand it.

> o = { foo: 1 }
> console.log(o)
Expand now, o.foo = 1
> o.foo = 2
o.foo is still displayed as 1 from previous lines

> o = { foo: 1 }
> console.log(o)
> o.foo = 2
Expand now, o.foo = 2

You can use the following to get a stringified version of an object if that's what you want to see. This will show you what the object is at the time this line is called, not when you expand it.

console.log(JSON.stringify(o));

How to make a WPF window be on top of all other windows of my app (not system wide)?

There are several threads, there's even a "topmost" tag. Search on that, or go directly to this post which looks good:

How to keep a window on top of all other windows in my application only?

Default port for SQL Server

If you have access to the server then you can use

select local_tcp_port from sys.dm_exec_connections where local_tcp_port is not null

For full details see port number of SQL Server

Check if input is integer type in C

I was having the same problem, finally figured out what to do:

#include <stdio.h>
#include <conio.h>

int main ()
{
    int x;
    float check;
    reprocess:
    printf ("enter a integer number:");
    scanf ("%f", &check);
    x=check;
    if (x==check)
    printf("\nYour number is %d", x);
    else 
    {
         printf("\nThis is not an integer number, please insert an integer!\n\n");
         goto reprocess;
    }
    _getch();
    return 0;
}

How to auto adjust the div size for all mobile / tablet display formats?

Fiddle

You want to set height which may set for all devices?

Decide upon the design of the site i.e Height on various devices.

Ex:

  • Height-100px for bubbles on device with -min-width: 700px.
  • Height-50px for bubbles on device with < 700px;

Have your css which has height 50px;

and add this media query

  @media only screen and (min-width: 700px) {
    /* Styles */
    .bubble {
        height: 100px;
        margin: 20px;
    }
    .bubble:after {
        bottom: -50px;
        border-width: 50px 50px 0;
    }
    .bubble:before {
        top: 100px;
        border-width: 52px 52px 0;
    }
    .bubble1 {
        height: 100px;
        margin: 20px;
    }
    .bubble1:after {
        bottom: -50px;
        border-width: 50px 50px 0;
    }
    .bubble1:before {
        top: 100px;
        border-width: 52px 52px 0;
    }
    .bubble2 {
        height: 100px;
        margin: 20px;
    }
    .bubble2:after {
        bottom: -50px;
        border-width: 50px 50px 0;
    }
    .bubble2:before {
        top: 100px;
        border-width: 52px 52px 0;
    }
}

This will make your bubbles have Height of 100px on devices greater than 700px and a margin of 20px;

How to set the action for a UIBarButtonItem in Swift

Swift 4/5 example

button.target = self
button.action = #selector(buttonClicked(sender:))

@objc func buttonClicked(sender: UIBarButtonItem) {
        
}

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

If you use mutexes to protect all your data, you really shouldn't need to worry. Mutexes have always provided sufficient ordering and visibility guarantees.

Now, if you used atomics, or lock-free algorithms, you need to think about the memory model. The memory model describes precisely when atomics provide ordering and visibility guarantees, and provides portable fences for hand-coded guarantees.

Previously, atomics would be done using compiler intrinsics, or some higher level library. Fences would have been done using CPU-specific instructions (memory barriers).

Remove first 4 characters of a string with PHP

You could use the substr function to return a substring starting from the 5th character:

$str = "The quick brown fox jumps over the lazy dog."
$str2 = substr($str, 4); // "quick brown fox jumps over the lazy dog."

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

Where does Android app package gets installed on phone

/data/data/"your app package name " 

but you wont able to read that unless you have a rooted device

ERROR: Google Maps API error: MissingKeyMapError

All Google Maps JavaScript API applications require authentication( API KEY )

  1. Go to https://developers.google.com/maps/documentation/javascript/get-api-key.
  2. Login with Google Account
  3. Click on Get a key button 3 Select or create a project
  4. Click on Enable API ( Google Maps API)
  5. Copy YOUR API KEY in your Project: <script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=(Paste YOUR API KEY)"></script>

How do I PHP-unserialize a jQuery-serialized form?

You shouldn't have to unserialize anything in PHP from the jquery serialize method. If you serialize the data, it should be sent to PHP as query parameters if you are using a GET method ajax request or post vars if you are using a POST ajax request. So in PHP, you would access values like $_POST["varname"] or $_GET["varname"] depending on the request type.

The serialize method just takes the form elements and puts them in string form. "varname=val&var2=val2"

How can I create a keystore?

I'd like to suggest automatic way with gradle only

** Define also at least one additional param for keystore in last command e.g. country '-dname', 'c=RU' **

apply plugin: 'com.android.application'

// define here sign properties
def sPassword = 'storePassword_here'
def kAlias = 'keyAlias_here'
def kPassword = 'keyPassword_here'

android {
    ...
    signingConfigs {
        release {
            storeFile file("keystore/release.jks")
            storePassword sPassword
            keyAlias kAlias
            keyPassword kPassword
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.release
        }
        release {
            shrinkResources true
            minifyEnabled true
            useProguard true
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    ...
}

...

task generateKeystore() {
    exec {
        workingDir projectDir
        commandLine 'mkdir', '-p', 'keystore'
    }
    exec {
        workingDir projectDir
        commandLine 'rm', '-f', 'keystore/release.jks'
    }
    exec {
        workingDir projectDir
        commandLine 'keytool', '-genkey', '-noprompt', '-keystore', 'keystore/release.jks',
            '-alias', kAlias, '-storepass', sPassword, '-keypass', kPassword, '-dname', 'c=RU',
            '-keyalg', 'RSA', '-keysize', '2048', '-validity', '10000'
    }
}

project.afterEvaluate {
    preBuild.dependsOn generateKeystore
}

This will generate keystore on project sync and build

> Task :app:generateKeystore UP-TO-DATE
> Task :app:preBuild UP-TO-DATE

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

This error occurs when you suspend some functions. Like running the query below with incorrect foreign key.

set foreign_key_checks=0

How do I iterate over the words of a string?

Yet another flexible and fast way

template<typename Operator>
void tokenize(Operator& op, const char* input, const char* delimiters) {
  const char* s = input;
  const char* e = s;
  while (*e != 0) {
    e = s;
    while (*e != 0 && strchr(delimiters, *e) == 0) ++e;
    if (e - s > 0) {
      op(s, e - s);
    }
    s = e + 1;
  }
}

To use it with a vector of strings (Edit: Since someone pointed out not to inherit STL classes... hrmf ;) ) :

template<class ContainerType>
class Appender {
public:
  Appender(ContainerType& container) : container_(container) {;}
  void operator() (const char* s, unsigned length) { 
    container_.push_back(std::string(s,length));
  }
private:
  ContainerType& container_;
};

std::vector<std::string> strVector;
Appender v(strVector);
tokenize(v, "A number of words to be tokenized", " \t");

That's it! And that's just one way to use the tokenizer, like how to just count words:

class WordCounter {
public:
  WordCounter() : noOfWords(0) {}
  void operator() (const char*, unsigned) {
    ++noOfWords;
  }
  unsigned noOfWords;
};

WordCounter wc;
tokenize(wc, "A number of words to be counted", " \t"); 
ASSERT( wc.noOfWords == 7 );

Limited by imagination ;)

Executing multiple SQL queries in one statement with PHP

This may be created sql injection point "SQL Injection Piggy-backed Queries". attackers able to append multiple malicious sql statements. so do not append user inputs directly to the queries.

Security considerations

The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.

PHP Doc

Why have header files and .cpp files?

Because C++ inherited them from C. Unfortunately.

How to check if internet connection is present in Java?

The code using NetworkInterface to wait for the network worked for me until I switched from fixed network address to DHCP. A slight enhancement makes it work also with DHCP:

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
    NetworkInterface interf = interfaces.nextElement();
    if (interf.isUp() && !interf.isLoopback()) {
    List<InterfaceAddress> adrs = interf.getInterfaceAddresses();
    for (Iterator<InterfaceAddress> iter = adrs.iterator(); iter.hasNext();) {
        InterfaceAddress adr = iter.next();
        InetAddress inadr = adr.getAddress();
        if (inadr instanceof Inet4Address) return true;
            }
    }
}

This works for Java 7 in openSuse 13.1 for IPv4 network. The problem with the original code is that although the interface was up after resuming from suspend, an IPv4 network address was not yet assigned. After waiting for this assignment, the program can connect to servers. But I have no idea what to do in case of IPv6.

JQuery Validate input file type

Simply use the .rules('add') method immediately after creating the element...

var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile

    // create the new input element
    $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");

    // declare the rule on this newly created input field        
    $('#FileUpload' + filenumber).rules('add', {
        required: true,  // <- with this you would not need 'required' attribute on input
        accept: "image/jpeg, image/pjpeg"
    });

    filenumber++; // increment counter for next time

    return false;
});
  • You'll still need to use .validate() to initialize the plugin within a DOM ready handler.

  • You'll still need to declare rules for your static elements using .validate(). Whatever input elements that are part of the form when the page loads... declare their rules within .validate().

  • You don't need to use .each(), when you're only targeting ONE element with the jQuery selector attached to .rules().

  • You don't need the required attribute on your input element when you're declaring the required rule using .validate() or .rules('add'). For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required".

Working DEMO: http://jsfiddle.net/8dAU8/5/

What is the max size of localStorage values?

I really like cdmckay's answer, but it does not really look good to check the size in a real time: it is just too slow (2 seconds for me). This is the improved version, which is way faster and more exact, also with an option to choose how big the error can be (default 250,000, the smaller error is - the longer the calculation is):

function getLocalStorageMaxSize(error) {
  if (localStorage) {
    var max = 10 * 1024 * 1024,
        i = 64,
        string1024 = '',
        string = '',
        // generate a random key
        testKey = 'size-test-' + Math.random().toString(),
        minimalFound = 0,
        error = error || 25e4;

    // fill a string with 1024 symbols / bytes    
    while (i--) string1024 += 1e16;

    i = max / 1024;

    // fill a string with 'max' amount of symbols / bytes    
    while (i--) string += string1024;

    i = max;

    // binary search implementation
    while (i > 1) {
      try {
        localStorage.setItem(testKey, string.substr(0, i));
        localStorage.removeItem(testKey);

        if (minimalFound < i - error) {
          minimalFound = i;
          i = i * 1.5;
        }
        else break;
      } catch (e) {
        localStorage.removeItem(testKey);
        i = minimalFound + (i - minimalFound) / 2;
      }
    }

    return minimalFound;
  }
}

To test:

console.log(getLocalStorageMaxSize()); // takes .3s
console.log(getLocalStorageMaxSize(.1)); // takes 2s, but way more exact

This works dramatically faster for the standard error; also it can be much more exact when necessary.

Force the origin to start at 0

xlim and ylim don't cut it here. You need to use expand_limits, scale_x_continuous, and scale_y_continuous. Try:

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for

enter image description here

p + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))

enter image description here

You may need to adjust things a little to make sure points are not getting cut off (see, for example, the point at x = 5 and y = 5.

Shell script to check if file exists

You have to understand how Unix interprets your input.

The standard Unix shell interpolates environment variables, and what are called globs before it passes the parameters to your program. This is a bit different from Windows which makes the program interpret the expansion.

Try this:

 $ echo *

This will echo all the files and directories in your current directory. Before the echo command acts, the shell interpolates the * and expands it, then passes that expanded parameter back to your command. You can see it in action by doing this:

$ set -xv
$ echo *
$ set +xv

The set -xv turns on xtrace and verbose. Verbose echoes the command as entered, and xtrace echos the command that will be executed (that is, after the shell expansion).

Now try this:

$ echo "*"

Note that putting something inside quotes hides the glob expression from the shell, and the shell cannot expand it. Try this:

$ foo="this is the value of foo"
$ echo $foo
$ echo "$foo"
$ echo '$foo'

Note that the shell can still expand environment variables inside double quotes, but not in single quotes.

Now let's look at your statement:

file="home/edward/bank1/fiche/Test*"

The double quotes prevent the shell from expanding the glob expression, so file is equal to the literal home/edward/bank1/finche/Test*. Therefore, you need to do this:

file=/home/edward/bank1/fiche/Test*

The lack of quotes (and the introductory slash which is important!) will now make file equal to all files that match that expression. (There might be more than one!). If there are no files, depending upon the shell, and its settings, the shell may simply set file to that literal string anyway.

You certainly have the right idea:

 file=/home/edward/bank1/fiche/Test*
 if  test -s $file
    then 
        echo "found one"
    else 
       echo "found none"
 fi

However, you still might get found none returned if there is more than one file. Instead, you might get an error in your test command because there are too many parameters.

One way to get around this might be:

if ls /home/edward/bank1/finche/Test* > /dev/null 2>&1
then
    echo "There is at least one match (maybe more)!"
else
    echo "No files found"
fi

In this case, I'm taking advantage of the exit code of the ls command. If ls finds one file it can access, it returns a zero exit code. If it can't find one matching file, it returns a non-zero exit code. The if command merely executes a command, and then if the command returns a zero, it assumes the if statement as true and executes the if clause. If the command returns a non-zero value, the if statement is assumed to be false, and the else clause (if one is available) is executed.

The test command works in a similar fashion. If the test is true, the test command returns a zero. Otherwise, the test command returns a non-zero value. This works great with the if command. In fact, there's an alias to the test command. Try this:

 $ ls -li /bin/test /bin/[

The i prints out the inode. The inode is the real ID of the file. Files with the same ID are the same file. You can see that /bin/test and /bin/[ are the same command. This makes the following two commands the same:

if test -s $file
then
    echo "The file exists"
fi

if [ -s $file ]
then
    echo "The file exists"
fi

Android Studio: /dev/kvm device permission denied

Just one slight improvement on Jerrin's answer on fixing this error with Ubuntu 18.04 by utilizing $USER variable available in the bash terminal. So you could use the following commands two commands:

sudo apt install qemu-kvm

Add the current user to the kvm group

sudo adduser $USER kvm

Also if you are still having issues, one other problem for me was the way in which I installed Ubuntu. I made the mistake of checking the box during installation for installing 3rd party software which did not play nice with my nvidia graphics card for development. So I reinstalled Ubuntu with this third party software unchecked.

enter image description here

Then after installation, open up Software & Updates and go to the Additional Drivers tab. Select the most up to date proprietary drivers that have also been tested and apply changes. Should restart the machine for the changes to take affect.

enter image description here

Min/Max of dates in an array?

Since dates are converted to UNIX epoch (numbers), you can use Math.max/min to find those:

var maxDate = Math.max.apply(null, dates)
// convert back to date object
maxDate = new Date(maxDate)

(tested in chrome only, but should work in most browsers)

Question mark and colon in statement. What does it mean?

It is the ternary conditional operator.

If the condition in the parenthesis before the ? is true, it returns the value to the left of the :, otherwise the value to the right.

Opening Chrome From Command Line

open command prompt and type

cd\ (enter)

then type

start chrome "www.google.com"(any website you require)

EOFError: EOF when reading a line

**The best is to use try except block to get rid of EOF **

try:
    width = input()
    height = input()
    def rectanglePerimeter(width, height):
       return ((width + height)*2)
    print(rectanglePerimeter(width, height))
except EOFError as e:
    print(end="")

Inserting line breaks into PDF

Or just try this after each text passage for a new line.

$pdf->Write(0, ' ', '*', 0, 'C', TRUE, 0, false, false, 0) ;

How to list all Git tags?

To list tags I prefer:

git tag -n

The -n flag displays the first line of the annotation message along with the tag, or the first commit message line if the tag is not annotated.

You can also do git tag -n5 to show the first 5 lines of the annotation.

Mapping list in Yaml to list of objects in Spring Boot

The reason must be somewhere else. Using only Spring Boot 1.2.2 out of the box with no configuration, it Just Works. Have a look at this repo - can you get it to break?

https://github.com/konrad-garus/so-yaml

Are you sure the YAML file looks exactly the way you pasted? No extra whitespace, characters, special characters, mis-indentation or something of that sort? Is it possible you have another file elsewhere in the search path that is used instead of the one you're expecting?

How to link home brew python version and set it as default

On OS X High Sierra, I had to do this:

sudo install -d -o $(whoami) -g admin /usr/local/Frameworks
brew uninstall --ignore-dependencies python
brew install python
python --version # should work, returns 2.7, which is a Python thing (it's weird, but ok)

credit to https://gist.github.com/irazasyed/7732946#gistcomment-2235469

I think it's better than recursively chowning the /usr/local dir, but that may solve other problems ;)

Bootstrap: how do I change the width of the container?

Container sizes

@container-large-desktop
(1140px + @grid-gutter-width) -> (970px + @grid-gutter-width)

in section Container sizes, change 1140 to 970

I hope its help you.


thank you for your correct. link for customize bootstrap: https://getbootstrap.com/docs/3.4/customize/

Pass Parameter to Gulp Task

If you want to avoid adding extra dependencies, I found node's process.argv to be useful:

gulp.task('mytask', function() {
    console.log(process.argv);
});

So the following:

gulp mytask --option 123

should display:

[ 'node', 'path/to/gulp.js', 'mytask', '--option', '123']

If you are sure that the desired parameter is in the right position, then the flags aren't needed.** Just use (in this case):

var option = process.argv[4]; //set to '123'

BUT: as the option may not be set, or may be in a different position, I feel that a better idea would be something like:

var option, i = process.argv.indexOf("--option");
if(i>-1) {
    option = process.argv[i+1];
}

That way, you can handle variations in multiple options, like:

//task should still find 'option' variable in all cases
gulp mytask --newoption somestuff --option 123
gulp mytask --option 123 --newoption somestuff
gulp mytask --flag --option 123

** Edit: true for node scripts, but gulp interprets anything without a leading "--" as another task name. So using gulp mytask 123 will fail because gulp can't find a task called '123'.

Change URL without refresh the page

When you use a function ...

<p onclick="update_url('/en/step2');">Link</p>

<script>
function update_url(url) {
    history.pushState(null, null, url);
}
</script>

Check if String contains only letters

private boolean isOnlyLetters(String s){
    char c=' ';
    boolean isGood=false, safe=isGood;
    int failCount=0;
    for(int i=0;i<s.length();i++){
        c = s.charAt(i);
        if(Character.isLetter(c))
            isGood=true;
        else{
            isGood=false;
            failCount+=1;
        }
    }
    if(failCount==0 && s.length()>0)
        safe=true;
    else
        safe=false;
    return safe;
}

I know it's a bit crowded. I was using it with my program and felt the desire to share it with people. It can tell if any character in a string is not a letter or not. Use it if you want something easy to clarify and look back on.

"elseif" syntax in JavaScript

x = 10;
if(x > 100 ) console.log('over 100')
else if (x > 90 ) console.log('over 90')
else if (x > 50 ) console.log('over 50')
else if (x > 9 ) console.log('over 9')
else console.log('lower 9') 

Generating (pseudo)random alpha-numeric strings

First make a string with all your possible characters:

 $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';

You could also use range() to do this more quickly.

Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string:

 $string = '';
 $max = strlen($characters) - 1;
 for ($i = 0; $i < $random_string_length; $i++) {
      $string .= $characters[mt_rand(0, $max)];
 }

$random_string_length is the length of the random string.

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

-n returns line number.

-i is for ignore-case. Only to be used if case matching is not necessary

$ grep -in null myfile.txt

2:example two null,
4:example four null,

Combine with awk to print out the line number after the match:

$ grep -in null myfile.txt | awk -F: '{print $2" - Line number : "$1}'

example two null, - Line number : 2
example four null, - Line number : 4

Use command substitution to print out the total null count:

$ echo "Total null count :" $(grep -ic null myfile.txt)

Total null count : 2

How to get the integer value of day of week

int day = (int)DateTime.Now.DayOfWeek;

First day of the week: Sunday (with a value of zero)

How to override and extend basic Django admin templates?

You can use django-overextends, which provides circular template inheritance for Django.

It comes from the Mezzanine CMS, from where Stephen extracted it into a standalone Django extension.

More infos you find in "Overriding vs Extending Templates" (http:/mezzanine.jupo.org/docs/content-architecture.html#overriding-vs-extending-templates) inside the Mezzanine docs.

For deeper insides look at Stephens Blog "Circular Template Inheritance for Django" (http:/blog.jupo.org/2012/05/17/circular-template-inheritance-for-django).

And in Google Groups the discussion (https:/groups.google.com/forum/#!topic/mezzanine-users/sUydcf_IZkQ) which started the development of this feature.

Note:

I don't have the reputation to add more than 2 links. But I think the links provide interesting background information. So I just left out a slash after "http(s):". Maybe someone with better reputation can repair the links and remove this note.

Difference Between Select and SelectMany

SelectMany() lets you collapse a multidimensional sequence in a way that would otherwise require a second Select() or loop.

More details at this blog post.

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

How to print jquery object/array

Your result is currently in string format, you need to parse it as json.

var obj = $.parseJSON(result);
alert(obj[0].category);

Additionally, if you set the dataType of the ajax call you are making to json, you can skip the $.parseJSON() step.

Ignore self-signed ssl cert using Jersey Client

For anyone on Jersey 2.x without lambdas, use this:

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;

public static Client getUnsecureClient() throws Exception 
{
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[]{new X509TrustManager() 
    {
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{}
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException{}
            public X509Certificate[] getAcceptedIssuers()
            {
                return new X509Certificate[0];
            }

    }}, new java.security.SecureRandom());


    HostnameVerifier allowAll = new HostnameVerifier() 
    {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier(allowAll).build();
}

Tested with jersey-client 2.11 on JRE 1.7.

PostgreSQL, checking date relative to "today"

This should give you the current date minus 1 year:

select now() - interval '1 year';

Convert String to Type in C#

If you really want to get the type by name you may use the following:

System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");

Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.

Find which commit is currently checked out in Git

If you want to extract just a simple piece of information, you can get that using git show with the --format=<string> option...and ask it not to give you the diff with --no-patch. This means you can get a printf-style output of whatever you want, which might often be a single field.

For instance, to get just the shortened hash (%h) you could say:

$ git show --format="%h" --no-patch
4b703eb

If you're looking to save that into an environment variable in bash (a likely thing for people to want to do) you can use the $() syntax:

$ GIT_COMMIT="$(git show --format="%h" --no-patch)"

$ echo $GIT_COMMIT
4b703eb

The full list of what you can do is in git show --help. But here's an abbreviated list of properties that might be useful:

  • %H commit hash
  • %h abbreviated commit hash
  • %T tree hash
  • %t abbreviated tree hash
  • %P parent hashes
  • %p abbreviated parent hashes
  • %an author name
  • %ae author email
  • %at author date, UNIX timestamp
  • %aI author date, strict ISO 8601 format
  • %cn committer name
  • %ce committer email
  • %ct committer date, UNIX timestamp
  • %cI committer date, strict ISO 8601 format
  • %s subject
  • %f sanitized subject line, suitable for a filename
  • %gD reflog selector, e.g., refs/stash@{1}
  • %gd shortened reflog selector, e.g., stash@{1}

Limit Decimal Places in Android EditText

et = (EditText) vw.findViewById(R.id.tx_edittext);

et.setFilters(new InputFilter[] {
        new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
            int beforeDecimal = 5, afterDecimal = 2;

            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                    Spanned dest, int dstart, int dend) {
                String temp = et.getText() + source.toString();

                if (temp.equals(".")) {
                    return "0.";
                }
                else if (temp.toString().indexOf(".") == -1) {
                    // no decimal point placed yet
                    if (temp.length() > beforeDecimal) {
                        return "";
                    }
                } else {
                    temp = temp.substring(temp.indexOf(".") + 1);
                    if (temp.length() > afterDecimal) {
                        return "";
                    }
                }

                return super.filter(source, start, end, dest, dstart, dend);
            }
        }
});

How to go to a specific element on page?

If the element is currently not visible on the page, you can use the native scrollIntoView() method.

$('#div_' + element_id)[0].scrollIntoView( true );

Where true means align to the top of the page, and false is align to bottom.

Otherwise, there's a scrollTo() plugin for jQuery you can use.

Or maybe just get the top position()(docs) of the element, and set the scrollTop()(docs) to that position:

var top = $('#div_' + element_id).position().top;
$(window).scrollTop( top );