Programs & Examples On #Bsd

BSD is a family of Unix-like operating systems, including FreeBSD, NetBSD and OpenBSD.

How do I timestamp every ping result?

ping -D -n -O -i1 -W1 8.8.8.8

or maybe

while true; do \
    ping -n -w1 -W1 -c1 8.8.8.8 \
    | grep -E "rtt|100%" \
    | sed -e "s/^/`date` /g"; \
    sleep 1; \
done

Custom seekbar (thumb size, color and background)

android:minHeight android:maxHeight is important for that.

<SeekBar
    android:id="@+id/pb"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="2dp"
    android:minHeight="2dp"
    android:progressDrawable="@drawable/seekbar_bg"
    android:thumb="@drawable/seekbar_thumb"
    android:max="100"
    android:progress="50"/>

seekbar_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="3dp" />
            <solid android:color="#ECF0F1" />
        </shape>
    </item>
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="3dp" />
                <solid android:color="#C6CACE" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="3dp" />
                <solid android:color="#16BC5C" />
            </shape>
        </clip>
    </item>
</layer-list>

seekbar_thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#16BC5C" />
    <stroke
        android:width="1dp"
        android:color="#16BC5C" />
    <size
        android:height="20dp"
        android:width="20dp" />
</shape>

Error: JAVA_HOME is not defined correctly executing maven

We open a terminal and look for the location of java:

manuel@zonademanel:~ ? whereis java

java: /usr/bin/java /etc/java /usr/bin/X11/java /usr/share/java /usr/share/man/man1/java.1.gz

What we are looking for is /usr/bin/java continue on the command line to find the absolute path , as this is only a symbolic link.

manuel@zonademanel:~ ? ls -lah /usr/bin/java

lrwxrwxrwx 1 root root 22 may 19 2015 /usr/bin/java -> /etc/alternatives/java

manuel@zonademanel:~ ? ls -lah /etc/alternatives/java

lrwxrwxrwx 1 root root 39 dic 7 11:52 /etc/alternatives/java -> /usr/lib/jvm/java-8-oracle/jre/bin/java

I modified my /etc/environment file with the following values

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/jvm/java-8-oracle/jre/bin" JAVA_HOME="/usr/lib/jvm/java-8-oracle/jre"

If I do not want to relogin I can reload the changes with:

source /etc/environment 

??And run mvn -version correctly

manuel@zonademanel:~ ? mvn -version

Apache Maven 3.0.5
Maven home: /usr/share/maven
Java version: 1.8.0_77, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-oracle/jre
Default locale: es_MX, platform encoding: UTF-8
OS name: "linux", version: "3.16.0-70-generic", arch: "amd64", family: "unix"

Windows 10 SSH keys

Warning: If you are saving your keys under C:/User/username/.ssh ( the default place), make sure to back up your keys somewhere (eg your password manager).

After the most recent Windows 10 Update (version 1607), my .ssh folder was empty. This is where my keys have always been, but Windows decided to delete them when updating.

Thankfully I had backed up my keys... But... I bet some people will be reverting their PC's today.

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

echo (""); is a php code, and <prev> tries to be HTML, but isn't.

As @pekka said, its probably supposed to be <pre>

Get local IP address

This is the best code I found to get the current IP, avoiding get VMWare host or other invalid IP address.

public string GetLocalIpAddress()
{
    UnicastIPAddressInformation mostSuitableIp = null;

    var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

    foreach (var network in networkInterfaces)
    {
        if (network.OperationalStatus != OperationalStatus.Up)
            continue;

        var properties = network.GetIPProperties();

        if (properties.GatewayAddresses.Count == 0)
            continue;

        foreach (var address in properties.UnicastAddresses)
        {
            if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                continue;

            if (IPAddress.IsLoopback(address.Address))
                continue;

            if (!address.IsDnsEligible)
            {
                if (mostSuitableIp == null)
                    mostSuitableIp = address;
                continue;
            }

            // The best IP is the IP got from DHCP server
            if (address.PrefixOrigin != PrefixOrigin.Dhcp)
            {
                if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)
                    mostSuitableIp = address;
                continue;
            }

            return address.Address.ToString();
        }
    }

    return mostSuitableIp != null 
        ? mostSuitableIp.Address.ToString()
        : "";
}

Do I need <class> elements in persistence.xml?

I'm not sure this solution is under the spec but I think I can share for others.

dependency tree

my-entities.jar

Contains entity classes only. No META-INF/persistence.xml.

my-services.jar

Depends on my-entities. Contains EJBs only.

my-resources.jar

Depends on my-services. Contains resource classes and META-INF/persistence.xml.

problems

  • How can we specify <jar-file/> element in my-resources as the version-postfixed artifact name of a transient dependency?
  • How can we sync the <jar-file/> element's value and the actual transient dependency's one?

solution

direct (redundant?) dependency and resource filtering

I put a property and a dependency in my-resources/pom.xml.

<properties>
  <my-entities.version>x.y.z-SNAPSHOT</my-entities.version>
</properties>
<dependencies>
  <dependency>
    <!-- this is actually a transitive dependency -->
    <groupId>...</groupId>
    <artifactId>my-entities</artifactId>
    <version>${my-entities.version}</version>
    <scope>compile</scope> <!-- other values won't work -->
  </dependency>
  <dependency>
    <groupId>...</groupId>
    <artifactId>my-services</artifactId>
    <version>some.very.sepecific</version>
    <scope>compile</scope>
  </dependency>
<dependencies>

Now get the persistence.xml ready for being filtered

<?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
  <persistence-unit name="myPU" transaction-type="JTA">
    ...
    <jar-file>lib/my-entities-${my-entities.version}.jar</jar-file>
    ...
  </persistence-unit>
</persistence>

Maven Enforcer Plugin

With the dependencyConvergence rule, we can assure that the my-entities' version is same in both direct and transitive.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-enforcer-plugin</artifactId>
  <version>1.4.1</version>
  <executions>
    <execution>
      <id>enforce</id>
      <configuration>
        <rules>
           <dependencyConvergence/>
        </rules>
      </configuration>
      <goals>
        <goal>enforce</goal>
      </goals>
    </execution>
  </executions>
</plugin>

How to insert element into arrays at specific position?

This is better method how insert item to array on some position.

function arrayInsert($array, $item, $position)
{
    $begin = array_slice($array, 0, $position);
    array_push($begin, $item);
    $end = array_slice($array, $position);
    $resultArray = array_merge($begin, $end);
    return $resultArray;
}

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

Associating existing Eclipse project with existing SVN repository

I am using Tortoise SVN client. You can alternativley check out the required project from SVN in some folder. You can see a .SVN folder inside the project. Copy the .SVN folder into the workspace folder. Now remove the project from eclipse and import the same again into eclipse. You can see now the project is now associated with svn

Shell script "for" loop syntax

Here it worked on Mac OS X.

It includes the example of a BSD date, how to increment and decrement the date also:

for ((i=28; i>=6 ; i--));
do
    dat=`date -v-${i}d -j "+%Y%m%d"` 
    echo $dat
done

How do I read the contents of a Node.js stream into a string variable?

setEncoding('utf8');

Well done Sebastian J above.

I had the "buffer problem" with a few lines of test code I had, and added the encoding information and it solved it, see below.

Demonstrate the problem

software

// process.stdin.setEncoding('utf8');
process.stdin.on('data', (data) => {
    console.log(typeof(data), data);
});

input

hello world

output

object <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 0d 0a>

Demonstrate the solution

software

process.stdin.setEncoding('utf8'); // <- Activate!
process.stdin.on('data', (data) => {
    console.log(typeof(data), data);
});

input

hello world

output

string hello world

get the titles of all open windows

Here’s some code you can use to get a list of all the open windows. Actually, you get a dictionary where each item is a KeyValuePair where the key is the handle (hWnd) of the window and the value is its title. It also finds pop-up windows, such as those created by MessageBox.Show.

using System.Runtime.InteropServices;
using HWND = System.IntPtr;

/// <summary>Contains functionality to get all the open windows.</summary>
public static class OpenWindowGetter
{
  /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
  /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
  public static IDictionary<HWND, string> GetOpenWindows()
  {
    HWND shellWindow = GetShellWindow();
    Dictionary<HWND, string> windows = new Dictionary<HWND, string>();

    EnumWindows(delegate(HWND hWnd, int lParam)
    {
      if (hWnd == shellWindow) return true;
      if (!IsWindowVisible(hWnd)) return true;

      int length = GetWindowTextLength(hWnd);
      if (length == 0) return true;

      StringBuilder builder = new StringBuilder(length);
      GetWindowText(hWnd, builder, length + 1);

      windows[hWnd] = builder.ToString();
      return true;

    }, 0);

    return windows;
  }

  private delegate bool EnumWindowsProc(HWND hWnd, int lParam);

  [DllImport("USER32.DLL")]
  private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

  [DllImport("USER32.DLL")]
  private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);

  [DllImport("USER32.DLL")]
  private static extern int GetWindowTextLength(HWND hWnd);

  [DllImport("USER32.DLL")]
  private static extern bool IsWindowVisible(HWND hWnd);

  [DllImport("USER32.DLL")]
  private static extern IntPtr GetShellWindow();
}

And here’s some code that uses it:

foreach(KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
{
  IntPtr handle = window.Key;
  string title = window.Value;

  Console.WriteLine("{0}: {1}", handle, title);
}

Credit: http://www.tcx.be/blog/2006/list-open-windows/

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

To use in Eloquent. Add on top of your model

protected $table = 'table_name as alias'

//table_name should be exact as in your database

..then use in your query like

ModelName::query()->select(alias.id, alias.name)

Java optional parameters

Short version :

Using three dots:

public void foo(Object... x) {
    String first    =  x.length > 0 ? (String)x[0]  : "Hello";
    int duration    =  x.length > 1 ? Integer.parseInt((String) x[1])     : 888;
}   
foo("Hii", ); 
foo("Hii", 146); 

(based on @VitaliiFedorenko's answer)

How to execute a program or call a system command from Python

There are a lot of different ways to run external commands in Python, and all of them have their own plus sides and drawbacks.

My colleagues and me have been writing Python system administration tools, so we need to run a lot of external commands, and sometimes you want them to block or run asynchronously, time-out, update every second, etc.

There are also different ways of handling the return code and errors, and you might want to parse the output, and provide new input (in an expect kind of style). Or you will need to redirect stdin, stdout and stderr to run in a different tty (e.g., when using screen).

So you will probably have to write a lot of wrappers around the external command. So here is a Python module which we have written which can handle almost anything you would want, and if not, it's very flexible so you can easily extend it:

https://github.com/hpcugent/vsc-base/blob/master/lib/vsc/utils/run.py

update: It doesn't work standalone and requires some of our other tools, and got a lot of specialised functionality over the years, so it might not be a drop in replacement for you, but can give you a lot of info on how the internals of python for running commands work and idea's on how to handle certain situations.

How can I get the number of days between 2 dates in Oracle 11g?

You can try using:

select trunc(sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) as days from dual

How to reset postgres' primary key sequence when it falls out of sync?

Reset all sequence from public

CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text) RETURNS "pg_catalog"."void" AS 
$body$  
  DECLARE 
  BEGIN 
  EXECUTE 'SELECT setval( ''' 
  || tablename  
  || '_id_seq'', ' 
  || '(SELECT id + 1 FROM "' 
  || tablename  
  || '" ORDER BY id DESC LIMIT 1), false)';  
  END;  
$body$  LANGUAGE 'plpgsql';

select sequence_name, reset_sequence(split_part(sequence_name, '_id_seq',1)) from information_schema.sequences
        where sequence_schema='public';

Do you recommend using semicolons after every statement in JavaScript?

No, only use semicolons when they're required.

C - error: storage size of ‘a’ isn’t known

You define your struct as xyx, however in your main, you use struct xyz a; , which only creates a forward declaration of a differently named struct.

Try using xyx a; instead of that line.

How to make a script wait for a pressed key?

Cross Platform, Python 2/3 code:

# import sys, os

def wait_key():
    ''' Wait for a key press on the console and return it. '''
    result = None
    if os.name == 'nt':
        import msvcrt
        result = msvcrt.getch()
    else:
        import termios
        fd = sys.stdin.fileno()

        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, newattr)

        try:
            result = sys.stdin.read(1)
        except IOError:
            pass
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)

    return result

I removed the fctl/non-blocking stuff because it was giving IOErrors and I didn't need it. I'm using this code specifically because I want it to block. ;)

Addendum:

I implemented this in a package on PyPI with a lot of other goodies called console:

>>> from console.utils import wait_key

>>> wait_key()
'h'

How do you execute SQL from within a bash script?

As Bash doesn't have built in sql database connectivity... you will need to use some sort of third party tool.

Selecting Folder Destination in Java?

Along with JFileChooser is possible use this:

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

for have a Look and Feel like Windows.

for others settings, view here: https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#available

Scatter plot with error bars

To summarize Laryx Decidua's answer:

define and use a function like the following

plot.with.errorbars <- function(x, y, err, ylim=NULL, ...) {
  if (is.null(ylim))
    ylim <- c(min(y-err), max(y+err))
  plot(x, y, ylim=ylim, pch=19, ...)
  arrows(x, y-err, x, y+err, length=0.05, angle=90, code=3)
}

where one can override the automatic ylim, and also pass extra parameters such as main, xlab, ylab.

Name attribute in @Entity and @Table

@Entity(name = "someThing") => this name will be used to identify the domain ..this name will only be identified by hql queries ..ie ..name of the domain object

@Table(name = "someThing") => this name will be used to which table referred by domain object..ie ..name of the table

Loading all images using imread from a given folder

import glob
cv_img = []
for img in glob.glob("Path/to/dir/*.jpg"):
    n= cv2.imread(img)
    cv_img.append(n)`

Calculate the execution time of a method

 using System.Diagnostics;
 class Program
 {
    static void Test1()
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine("Test1 " + i);
        }
    }
  static void Main(string[] args)
    {

        Stopwatch sw = new Stopwatch();
        sw.Start();
        Test1();
        sw.Stop();
        Console.WriteLine("Time Taken-->{0}",sw.ElapsedMilliseconds);
   }
 }

Where does gcc look for C and C++ header files?

You can create a file that attempts to include a bogus system header. If you run gcc in verbose mode on such a source, it will list all the system include locations as it looks for the bogus header.

$ echo "#include <bogus.h>" > t.c; gcc -v t.c; rm t.c

[..]

#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.

[..]

t.c:1:32: error: bogus.h: No such file or directory

How do I find the CPU and RAM usage using PowerShell?

I use the following PowerShell snippet to get CPU usage for local or remote systems:

Get-Counter -ComputerName localhost '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples | Select-Object -Property instancename, cookedvalue| Sort-Object -Property cookedvalue -Descending| Select-Object -First 20| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100).toString('P')}} -AutoSize

Same script but formatted with line continuation:

Get-Counter -ComputerName localhost '\Process(*)\% Processor Time' `
    | Select-Object -ExpandProperty countersamples `
    | Select-Object -Property instancename, cookedvalue `
    | Sort-Object -Property cookedvalue -Descending | Select-Object -First 20 `
    | ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100).toString('P')}} -AutoSize

On a 4 core system it will return results that look like this:

InstanceName          CPU
------------          ---
_total                399.61 %
idle                  314.75 %
system                26.23 %
services              24.69 %
setpoint              15.43 %
dwm                   3.09 %
policy.client.invoker 3.09 %
imobilityservice      1.54 %
mcshield              1.54 %
hipsvc                1.54 %
svchost               1.54 %
stacsv64              1.54 %
wmiprvse              1.54 %
chrome                1.54 %
dbgsvc                1.54 %
sqlservr              0.00 %
wlidsvc               0.00 %
iastordatamgrsvc      0.00 %
intelmefwservice      0.00 %
lms                   0.00 %

The ComputerName argument will accept a list of servers, so with a bit of extra formatting you can generate a list of top processes on each server. Something like:

$psstats = Get-Counter -ComputerName utdev1,utdev2,utdev3 '\Process(*)\% Processor Time' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty countersamples | %{New-Object PSObject -Property @{ComputerName=$_.Path.Split('\')[2];Process=$_.instancename;CPUPct=("{0,4:N0}%" -f $_.Cookedvalue);CookedValue=$_.CookedValue}} | ?{$_.CookedValue -gt 0}| Sort-Object @{E='ComputerName'; A=$true },@{E='CookedValue'; D=$true },@{E='Process'; A=$true }
$psstats | ft @{E={"{0,25}" -f $_.Process};L="ProcessName"},CPUPct -AutoSize -GroupBy ComputerName -HideTableHeaders

Which would result in a $psstats variable with the raw data and the following display:

   ComputerName: utdev1

           _total  397%
             idle  358%
             3mws   28%
           webcrs   10%


   ComputerName: utdev2

           _total  400%
             idle  248%
             cpfs   42%
             cpfs   36%
             cpfs   34%
          svchost   21%
         services   19%


   ComputerName: utdev3

           _total  200%
             idle  200%

Remove trailing spaces automatically or with a shortcut

<Ctr>-<Shift>-<F> 

Format, does it as well.

This removes trailing whitespace and formats/indents your code.

Ideal way to cancel an executing AsyncTask

The thing is that AsyncTask.cancel() call only calls the onCancel function in your task. This is where you want to handle the cancel request.

Here is a small task I use to trigger an update method

private class UpdateTask extends AsyncTask<Void, Void, Void> {

        private boolean running = true;

        @Override
        protected void onCancelled() {
            running = false;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            onUpdate();
        }

        @Override
        protected Void doInBackground(Void... params) {
             while(running) {
                 publishProgress();
             }
             return null;
        }
     }

How can I copy a Python string?

Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]

Nested Recycler view height doesn't wrap its content

I have tried all solutions, they are very useful but this only works fine for me

public class  LinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {

    public LinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
        super(context, orientation, reverseLayout);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                          int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);
        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {


            if (getOrientation() == HORIZONTAL) {

                measureScrapChild(recycler, i,
                        View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                        heightSpec,
                        mMeasuredDimension);

                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                measureScrapChild(recycler, i,
                        widthSpec,
                        View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                        mMeasuredDimension);
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }

        if (height < heightSize || width < widthSize) {

            switch (widthMode) {
                case View.MeasureSpec.EXACTLY:
                    width = widthSize;
                case View.MeasureSpec.AT_MOST:
                case View.MeasureSpec.UNSPECIFIED:
            }

            switch (heightMode) {
                case View.MeasureSpec.EXACTLY:
                    height = heightSize;
                case View.MeasureSpec.AT_MOST:
                case View.MeasureSpec.UNSPECIFIED:
            }

            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(recycler, state, widthSpec, heightSpec);
        }
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        View view = recycler.getViewForPosition(position);
        recycler.bindViewToPosition(view, position);
        if (view != null) {
            RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight(), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom(), p.height);
            view.measure(childWidthSpec, childHeightSpec);
            measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
            measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }
}

How to run 'sudo' command in windows

The following vbs script allows to launch a given command with arguments with elevation and mimics the behavior of the original unix sudo command for a limited set of used cases (it will not cache credentials nor it allows to truly execute commands with different credentials). I put it on C:\Windows\System32.

Set objArgs = WScript.Arguments
exe = objArgs(0)
args = ""
IF objArgs.Count >= 2 Then
   args = args & objArgs(1)
End If
For it = 2 to objArgs.Count - 1
   args = args & " " & objArgs(it)
Next
Set objShell = CreateObject( "WScript.Shell")
windir=objShell.ExpandEnvironmentStrings("%WINDIR%")
Set objShellApp = CreateObject("Shell.Application")
objShellApp.ShellExecute exe, args, "", "runas", 1
set objShellApp = nothing

Example use on a command prompt sudo net start service

Databinding an enum property to a ComboBox in WPF

This is a DevExpress specific answer based on the top-voted answer by Gregor S. (currently it has 128 votes).

This means we can keep the styling consistent across the entire application:

enter image description here

Unfortunately, the original answer doesn't work with a ComboBoxEdit from DevExpress without some modifications.

First, the XAML for the ComboBoxEdit:

<dxe:ComboBoxEdit ItemsSource="{Binding Source={xamlExtensions:XamlExtensionEnumDropdown {x:myEnum:EnumFilter}}}"
    SelectedItem="{Binding BrokerOrderBookingFilterSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    DisplayMember="Description"
    MinWidth="144" Margin="5" 
    HorizontalAlignment="Left"
    IsTextEditable="False"
    ValidateOnTextInput="False"
    AutoComplete="False"
    IncrementalFiltering="True"
    FilterCondition="Like"
    ImmediatePopup="True"/>

Needsless to say, you will need to point xamlExtensions at the namespace that contains the XAML extension class (which is defined below):

xmlns:xamlExtensions="clr-namespace:XamlExtensions"

And we have to point myEnum at the namespace that contains the enum:

xmlns:myEnum="clr-namespace:MyNamespace"

Then, the enum:

namespace MyNamespace
{
    public enum EnumFilter
    {
        [Description("Free as a bird")]
        Free = 0,

        [Description("I'm Somewhat Busy")]
        SomewhatBusy = 1,

        [Description("I'm Really Busy")]
        ReallyBusy = 2
    }
}

The problem in with the XAML is that we can't use SelectedItemValue, as this throws an error as the setter is unaccessable (bit of an oversight on your part, DevExpress). So we have to modify our ViewModel to obtain the value directly from the object:

private EnumFilter _filterSelected = EnumFilter.All;
public object FilterSelected
{
    get
    {
        return (EnumFilter)_filterSelected;
    }
    set
    {
        var x = (XamlExtensionEnumDropdown.EnumerationMember)value;
        if (x != null)
        {
            _filterSelected = (EnumFilter)x.Value;
        }
        OnPropertyChanged("FilterSelected");
    }
}

For completeness, here is the XAML extension from the original answer (slightly renamed):

namespace XamlExtensions
{
    /// <summary>
    ///     Intent: XAML markup extension to add support for enums into any dropdown box, see http://bit.ly/1g70oJy. We can name the items in the
    ///     dropdown box by using the [Description] attribute on the enum values.
    /// </summary>
    public class XamlExtensionEnumDropdown : MarkupExtension
    {
        private Type _enumType;


        public XamlExtensionEnumDropdown(Type enumType)
        {
            if (enumType == null)
            {
                throw new ArgumentNullException("enumType");
            }

            EnumType = enumType;
        }

        public Type EnumType
        {
            get { return _enumType; }
            private set
            {
                if (_enumType == value)
                {
                    return;
                }

                var enumType = Nullable.GetUnderlyingType(value) ?? value;

                if (enumType.IsEnum == false)
                {
                    throw new ArgumentException("Type must be an Enum.");
                }

                _enumType = value;
            }
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var enumValues = Enum.GetValues(EnumType);

            return (
                from object enumValue in enumValues
                select new EnumerationMember
                       {
                           Value = enumValue,
                           Description = GetDescription(enumValue)
                       }).ToArray();
        }

        private string GetDescription(object enumValue)
        {
            var descriptionAttribute = EnumType
                .GetField(enumValue.ToString())
                .GetCustomAttributes(typeof (DescriptionAttribute), false)
                .FirstOrDefault() as DescriptionAttribute;


            return descriptionAttribute != null
                ? descriptionAttribute.Description
                : enumValue.ToString();
        }

        #region Nested type: EnumerationMember
        public class EnumerationMember
        {
            public string Description { get; set; }
            public object Value { get; set; }
        }
        #endregion
    }
}

Disclaimer: I have no affiliation with DevExpress. Telerik is also a great library.

Using Jquery Datatable with AngularJs

Adding a new answer just as a reference for future researchers and as nobody mentioned that yet I think it's valid.

Another good option is ng-grid http://angular-ui.github.io/ng-grid/.

And there's a beta version (http://ui-grid.info/) available already with some improvements:

  • Native AngularJS implementation, no jQuery
  • Performs well with large data sets; even 10,000+ rows
  • Plugin architecture allows you to use only the features you need

UPDATE:

It seems UI GRID is not beta anymore.

With the 3.0 release, the repository has been renamed from "ng-grid" to "ui-grid".

Refresh a page using PHP

In PHP you can use:

$page = $_SERVER['PHP_SELF'];
$sec = "10";
header("Refresh: $sec; url=$page");

Or just use JavaScript's window.location.reload().

TypeError: 'int' object is not callable

As mentioned you might have a variable named round (of type int) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.

How to list processes attached to a shared memory segment in linux?

Just in case someone is interest only in what kind of process created the shared moeries, call

ls -l /dev/shm

It lists the names that are associated with the shared memories - at least on Ubuntu. Usually the names are quite telling.

(HTML) Download a PDF file instead of opening them in browser when clicked

With html5, it is possible now. Set a "download" attr in element.

<a href="http://link/to/file" download="FileName">Download it!</a>

Source : http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download

How can I set a UITableView to grouped style

I give you my solution, I am working in "XIB mode", here the code of a subclass of a UITableViewController :

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    return self;
}

AndroidStudio SDK directory does not exists

If your project is a subproject, the problem may lie on the parent local.properties file. I may suggest you to go up in the project hierarchy to the root file and execute the following command:

$ find . -type f -exec grep -l sdk.dir {} \;

That would work on OSX and Linux, if you are in Windows you may need to install Cygnus tools or something akin (I don't use Windows, so I cannot be more precise). If the path is wrongly set in some file, you'll find it with that command, then it is just a matter of opening the file with a text editor and replacing the wrong path with the right one.

Bootstrap 4: Multilevel Dropdown Inside Navigation

I found this multidrop-down menu which work great in all device.

Also, have hover style

It supports multi-level submenus with bootstrap 4.

_x000D_
_x000D_
$( document ).ready( function () {_x000D_
    $( '.navbar a.dropdown-toggle' ).on( 'click', function ( e ) {_x000D_
        var $el = $( this );_x000D_
        var $parent = $( this ).offsetParent( ".dropdown-menu" );_x000D_
        $( this ).parent( "li" ).toggleClass( 'show' );_x000D_
_x000D_
        if ( !$parent.parent().hasClass( 'navbar-nav' ) ) {_x000D_
            $el.next().css( { "top": $el[0].offsetTop, "left": $parent.outerWidth() - 4 } );_x000D_
        }_x000D_
        $( '.navbar-nav li.show' ).not( $( this ).parents( "li" ) ).removeClass( "show" );_x000D_
        return false;_x000D_
    } );_x000D_
} );
_x000D_
.navbar-light .navbar-nav .nav-link {_x000D_
    color: rgb(64, 64, 64);_x000D_
}_x000D_
.btco-menu li > a {_x000D_
    padding: 10px 15px;_x000D_
    color: #000;_x000D_
}_x000D_
_x000D_
.btco-menu .active a:focus,_x000D_
.btco-menu li a:focus ,_x000D_
.navbar > .show > a:focus{_x000D_
    background: transparent;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
.dropdown-menu .show > .dropdown-toggle::after{_x000D_
    transform: rotate(-90deg);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded btco-menu">_x000D_
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
        <span class="navbar-toggler-icon"></span>_x000D_
    </button>_x000D_
    <a class="navbar-brand" href="#">Navbar</a>_x000D_
    <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
        <ul class="navbar-nav">_x000D_
            <li class="nav-item active">_x000D_
                <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
            </li>_x000D_
            <li class="nav-item">_x000D_
                <a class="nav-link" href="#">Features</a>_x000D_
            </li>_x000D_
            <li class="nav-item">_x000D_
                <a class="nav-link" href="#">Pricing</a>_x000D_
            </li>_x000D_
            <li class="nav-item dropdown">_x000D_
                <a class="nav-link dropdown-toggle" href="https://bootstrapthemes.co" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown link</a>_x000D_
                <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
                    <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
                    <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
                    <li><a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
                        <ul class="dropdown-menu">_x000D_
                            <li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
                            <li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
                            <li><a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
                                <ul class="dropdown-menu">_x000D_
                                    <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                                    <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                                </ul>_x000D_
                            </li>_x000D_
                            <li><a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
                                <ul class="dropdown-menu">_x000D_
                                    <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                                    <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                                </ul>_x000D_
                            </li>_x000D_
                        </ul>_x000D_
                    </li>_x000D_
                </ul>_x000D_
            </li>_x000D_
        </ul>_x000D_
    </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How to get maximum value from the Collection (for example ArrayList)?

package in.co.largestinarraylist;

import java.util.ArrayList;
import java.util.Scanner;

public class LargestInArrayList {

    public static void main(String[] args) {

        int n;
        ArrayList<Integer> L = new ArrayList<Integer>();
        int max;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter Size of Array List");
        n = in.nextInt();
        System.out.println("Enter elements in Array List");

        for (int i = 0; i < n; i++) {
            L.add(in.nextInt());
        }

        max = L.get(0);

        for (int i = 0; i < L.size(); i++) {
            if (L.get(i) > max) {
                max = L.get(i);
            }
        }

        System.out.println("Max Element: " + max);
        in.close();
    }
}

How to get first object out from List<Object> using Linq

There are a bunch of such methods:
.First .FirstOrDefault .Single .SingleOrDefault
Choose which suits you best.

How do you sign a Certificate Signing Request with your Certification Authority?

1. Using the x509 module
openssl x509 ...
...

2 Using the ca module
openssl ca ...
...

You are missing the prelude to those commands.

This is a two-step process. First you set up your CA, and then you sign an end entity certificate (a.k.a server or user). Both of the two commands elide the two steps into one. And both assume you have a an OpenSSL configuration file already setup for both CAs and Server (end entity) certificates.


First, create a basic configuration file:

$ touch openssl-ca.cnf

Then, add the following to it:

HOME            = .
RANDFILE        = $ENV::HOME/.rnd

####################################################################
[ ca ]
default_ca    = CA_default      # The default ca section

[ CA_default ]

default_days     = 1000         # How long to certify for
default_crl_days = 30           # How long before next CRL
default_md       = sha256       # Use public key default MD
preserve         = no           # Keep passed DN ordering

x509_extensions = ca_extensions # The extensions to add to the cert

email_in_dn     = no            # Don't concat the email in the DN
copy_extensions = copy          # Required to copy SANs from CSR to cert

####################################################################
[ req ]
default_bits       = 4096
default_keyfile    = cakey.pem
distinguished_name = ca_distinguished_name
x509_extensions    = ca_extensions
string_mask        = utf8only

####################################################################
[ ca_distinguished_name ]
countryName         = Country Name (2 letter code)
countryName_default = US

stateOrProvinceName         = State or Province Name (full name)
stateOrProvinceName_default = Maryland

localityName                = Locality Name (eg, city)
localityName_default        = Baltimore

organizationName            = Organization Name (eg, company)
organizationName_default    = Test CA, Limited

organizationalUnitName         = Organizational Unit (eg, division)
organizationalUnitName_default = Server Research Department

commonName         = Common Name (e.g. server FQDN or YOUR name)
commonName_default = Test CA

emailAddress         = Email Address
emailAddress_default = [email protected]

####################################################################
[ ca_extensions ]

subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid:always, issuer
basicConstraints       = critical, CA:true
keyUsage               = keyCertSign, cRLSign

The fields above are taken from a more complex openssl.cnf (you can find it in /usr/lib/openssl.cnf), but I think they are the essentials for creating the CA certificate and private key.

Tweak the fields above to suit your taste. The defaults save you the time from entering the same information while experimenting with configuration file and command options.

I omitted the CRL-relevant stuff, but your CA operations should have them. See openssl.cnf and the related crl_ext section.

Then, execute the following. The -nodes omits the password or passphrase so you can examine the certificate. It's a really bad idea to omit the password or passphrase.

$ openssl req -x509 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

After the command executes, cacert.pem will be your certificate for CA operations, and cakey.pem will be the private key. Recall the private key does not have a password or passphrase.

You can dump the certificate with the following.

$ openssl x509 -in cacert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 11485830970703032316 (0x9f65de69ceef2ffc)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
        Validity
            Not Before: Jan 24 14:24:11 2014 GMT
            Not After : Feb 23 14:24:11 2014 GMT
        Subject: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (4096 bit)
                Modulus:
                    00:b1:7f:29:be:78:02:b8:56:54:2d:2c:ec:ff:6d:
                    ...
                    39:f9:1e:52:cb:8e:bf:8b:9e:a6:93:e1:22:09:8b:
                    59:05:9f
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                4A:9A:F3:10:9E:D7:CF:54:79:DE:46:75:7A:B0:D0:C1:0F:CF:C1:8A
            X509v3 Authority Key Identifier:
                keyid:4A:9A:F3:10:9E:D7:CF:54:79:DE:46:75:7A:B0:D0:C1:0F:CF:C1:8A

            X509v3 Basic Constraints: critical
                CA:TRUE
            X509v3 Key Usage:
                Certificate Sign, CRL Sign
    Signature Algorithm: sha256WithRSAEncryption
         4a:6f:1f:ac:fd:fb:1e:a4:6d:08:eb:f5:af:f6:1e:48:a5:c7:
         ...
         cd:c6:ac:30:f9:15:83:41:c1:d1:20:fa:85:e7:4f:35:8f:b5:
         38:ff:fd:55:68:2c:3e:37

And test its purpose with the following (don't worry about the Any Purpose: Yes; see "critical,CA:FALSE" but "Any Purpose CA : Yes").

$ openssl x509 -purpose -in cacert.pem -inform PEM
Certificate purposes:
SSL client : No
SSL client CA : Yes
SSL server : No
SSL server CA : Yes
Netscape SSL server : No
Netscape SSL server CA : Yes
S/MIME signing : No
S/MIME signing CA : Yes
S/MIME encryption : No
S/MIME encryption CA : Yes
CRL signing : Yes
CRL signing CA : Yes
Any Purpose : Yes
Any Purpose CA : Yes
OCSP helper : Yes
OCSP helper CA : Yes
Time Stamp signing : No
Time Stamp signing CA : Yes
-----BEGIN CERTIFICATE-----
MIIFpTCCA42gAwIBAgIJAJ9l3mnO7y/8MA0GCSqGSIb3DQEBCwUAMGExCzAJBgNV
...
aQUtFrV4hpmJUaQZ7ySr/RjCb4KYkQpTkOtKJOU1Ic3GrDD5FYNBwdEg+oXnTzWP
tTj//VVoLD43
-----END CERTIFICATE-----

For part two, I'm going to create another configuration file that's easily digestible. First, touch the openssl-server.cnf (you can make one of these for user certificates also).

$ touch openssl-server.cnf

Then open it, and add the following.

HOME            = .
RANDFILE        = $ENV::HOME/.rnd

####################################################################
[ req ]
default_bits       = 2048
default_keyfile    = serverkey.pem
distinguished_name = server_distinguished_name
req_extensions     = server_req_extensions
string_mask        = utf8only

####################################################################
[ server_distinguished_name ]
countryName         = Country Name (2 letter code)
countryName_default = US

stateOrProvinceName         = State or Province Name (full name)
stateOrProvinceName_default = MD

localityName         = Locality Name (eg, city)
localityName_default = Baltimore

organizationName            = Organization Name (eg, company)
organizationName_default    = Test Server, Limited

commonName           = Common Name (e.g. server FQDN or YOUR name)
commonName_default   = Test Server

emailAddress         = Email Address
emailAddress_default = [email protected]

####################################################################
[ server_req_extensions ]

subjectKeyIdentifier = hash
basicConstraints     = CA:FALSE
keyUsage             = digitalSignature, keyEncipherment
subjectAltName       = @alternate_names
nsComment            = "OpenSSL Generated Certificate"

####################################################################
[ alternate_names ]

DNS.1  = example.com
DNS.2  = www.example.com
DNS.3  = mail.example.com
DNS.4  = ftp.example.com

If you are developing and need to use your workstation as a server, then you may need to do the following for Chrome. Otherwise Chrome may complain a Common Name is invalid (ERR_CERT_COMMON_NAME_INVALID). I'm not sure what the relationship is between an IP address in the SAN and a CN in this instance.

# IPv4 localhost
IP.1     = 127.0.0.1

# IPv6 localhost
IP.2     = ::1

Then, create the server certificate request. Be sure to omit -x509*. Adding -x509 will create a certificate, and not a request.

$ openssl req -config openssl-server.cnf -newkey rsa:2048 -sha256 -nodes -out servercert.csr -outform PEM

After this command executes, you will have a request in servercert.csr and a private key in serverkey.pem.

And you can inspect it again.

$ openssl req -text -noout -verify -in servercert.csr
Certificate:
    verify OK
    Certificate Request:
        Version: 0 (0x0)
        Subject: C=US, ST=MD, L=Baltimore, CN=Test Server/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:ce:3d:58:7f:a0:59:92:aa:7c:a0:82:dc:c9:6d:
                    ...
                    f9:5e:0c:ba:84:eb:27:0d:d9:e7:22:5d:fe:e5:51:
                    86:e1
                Exponent: 65537 (0x10001)
        Attributes:
        Requested Extensions:
            X509v3 Subject Key Identifier:
                1F:09:EF:79:9A:73:36:C1:80:52:60:2D:03:53:C7:B6:BD:63:3B:61
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Key Encipherment
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
            Netscape Comment:
                OpenSSL Generated Certificate
    Signature Algorithm: sha256WithRSAEncryption
         6d:e8:d3:85:b3:88:d4:1a:80:9e:67:0d:37:46:db:4d:9a:81:
         ...
         76:6a:22:0a:41:45:1f:e2:d6:e4:8f:a1:ca:de:e5:69:98:88:
         a9:63:d0:a7

Next, you have to sign it with your CA.


You are almost ready to sign the server's certificate by your CA. The CA's openssl-ca.cnf needs two more sections before issuing the command.

First, open openssl-ca.cnf and add the following two sections.

####################################################################
[ signing_policy ]
countryName            = optional
stateOrProvinceName    = optional
localityName           = optional
organizationName       = optional
organizationalUnitName = optional
commonName             = supplied
emailAddress           = optional

####################################################################
[ signing_req ]
subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid,issuer
basicConstraints       = CA:FALSE
keyUsage               = digitalSignature, keyEncipherment

Second, add the following to the [ CA_default ] section of openssl-ca.cnf. I left them out earlier, because they can complicate things (they were unused at the time). Now you'll see how they are used, so hopefully they will make sense.

base_dir      = .
certificate   = $base_dir/cacert.pem   # The CA certifcate
private_key   = $base_dir/cakey.pem    # The CA private key
new_certs_dir = $base_dir              # Location for new certs after signing
database      = $base_dir/index.txt    # Database index file
serial        = $base_dir/serial.txt   # The current serial number

unique_subject = no  # Set to 'no' to allow creation of
                     # several certificates with same subject.

Third, touch index.txt and serial.txt:

$ touch index.txt
$ echo '01' > serial.txt

Then, perform the following:

$ openssl ca -config openssl-ca.cnf -policy signing_policy -extensions signing_req -out servercert.pem -infiles servercert.csr

You should see similar to the following:

Using configuration from openssl-ca.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'US'
stateOrProvinceName   :ASN.1 12:'MD'
localityName          :ASN.1 12:'Baltimore'
commonName            :ASN.1 12:'Test CA'
emailAddress          :IA5STRING:'[email protected]'
Certificate is to be certified until Oct 20 16:12:39 2016 GMT (1000 days)
Sign the certificate? [y/n]:Y

1 out of 1 certificate requests certified, commit? [y/n]Y
Write out database with 1 new entries
Data Base Updated

After the command executes, you will have a freshly minted server certificate in servercert.pem. The private key was created earlier and is available in serverkey.pem.

Finally, you can inspect your freshly minted certificate with the following:

$ openssl x509 -in servercert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9 (0x9)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
        Validity
            Not Before: Jan 24 19:07:36 2014 GMT
            Not After : Oct 20 19:07:36 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, CN=Test Server
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:ce:3d:58:7f:a0:59:92:aa:7c:a0:82:dc:c9:6d:
                    ...
                    f9:5e:0c:ba:84:eb:27:0d:d9:e7:22:5d:fe:e5:51:
                    86:e1
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                1F:09:EF:79:9A:73:36:C1:80:52:60:2D:03:53:C7:B6:BD:63:3B:61
            X509v3 Authority Key Identifier:
                keyid:42:15:F2:CA:9C:B1:BB:F5:4C:2C:66:27:DA:6D:2E:5F:BA:0F:C5:9E

            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Key Encipherment
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
            Netscape Comment:
                OpenSSL Generated Certificate
    Signature Algorithm: sha256WithRSAEncryption
         b1:40:f6:34:f4:38:c8:57:d4:b6:08:f7:e2:71:12:6b:0e:4a:
         ...
         45:71:06:a9:86:b6:0f:6d:8d:e1:c5:97:8d:fd:59:43:e9:3c:
         56:a5:eb:c8:7e:9f:6b:7a

Earlier, you added the following to CA_default: copy_extensions = copy. This copies extension provided by the person making the request.

If you omit copy_extensions = copy, then your server certificate will lack the Subject Alternate Names (SANs) like www.example.com and mail.example.com.

If you use copy_extensions = copy, but don't look over the request, then the requester might be able to trick you into signing something like a subordinate root (rather than a server or user certificate). Which means he/she will be able to mint certificates that chain back to your trusted root. Be sure to verify the request with openssl req -verify before signing.


If you omit unique_subject or set it to yes, then you will only be allowed to create one certificate under the subject's distinguished name.

unique_subject = yes            # Set to 'no' to allow creation of
                                # several ctificates with same subject.

Trying to create a second certificate while experimenting will result in the following when signing your server's certificate with the CA's private key:

Sign the certificate? [y/n]:Y
failed to update database
TXT_DB error number 2

So unique_subject = no is perfect for testing.


If you want to ensure the Organizational Name is consistent between self-signed CAs, Subordinate CA and End-Entity certificates, then add the following to your CA configuration files:

[ policy_match ]
organizationName = match

If you want to allow the Organizational Name to change, then use:

[ policy_match ]
organizationName = supplied

There are other rules concerning the handling of DNS names in X.509/PKIX certificates. Refer to these documents for the rules:

RFC 6797 and RFC 7469 are listed, because they are more restrictive than the other RFCs and CA/B documents. RFC's 6797 and 7469 do not allow an IP address, either.

How to create a backup of a single table in a postgres database?

Use --table to tell pg_dump what table it has to backup:

pg_dump --host localhost --port 5432 --username postgres --format plain --verbose --file "<abstract_file_path>" --table public.tablename dbname

How to improve Netbeans performance?

Is it a corporate Windows machine? If so aggressive virus scanners can really slow down modern IDEs. Check your task manager for processes that are using a lot of CPU or disk reads.

How to update the constant height constraint of a UIView programmatically?

Create an IBOutlet of NSLayoutConstraint of yourView and update the constant value accordingly the condition specifies.

//Connect them from Interface 
@IBOutlet viewHeight: NSLayoutConstraint! 
@IBOutlet view: UIView!

private func updateViewHeight(height:Int){
   guard let aView = view, aViewHeight = viewHeight else{
      return
   }
   aViewHeight.constant = height
   aView.layoutIfNeeded()
}

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

How do I get the base URL with PHP?

$some_variable =  substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['REQUEST_URI'], "/")+1);

and you get something like

lalala/tralala/something/

CSS styling in Django forms

You may not need to override your form class' __init__, because Django sets name & id attributes in the HTML inputs. You can have CSS like this:

form input[name='subject'] {
    font-size: xx-large;
}

What is the simplest way to convert array to vector?

One simple way can be the use of assign() function that is pre-defined in vector class.

e.g.

array[5]={1,2,3,4,5};

vector<int> v;
v.assign(array, array+5); // 5 is size of array.

When to use window.opener / window.parent / window.top

I think you need to add some context to your question. However, basic information about these things can be found here:

window.opener https://developer.mozilla.org/en-US/docs/Web/API/Window.opener

I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.

window.parent https://developer.mozilla.org/en-US/docs/Web/API/Window.parent

I've used this mostly when working with IFrames that need to communicate with the window object that contains them.

window.top https://developer.mozilla.org/en-US/docs/Web/API/Window.top

This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.

If you add some more detail to your question, I can supply other more relevant examples.

UPDATE: There are a few ways you can handle your situation.
You have the following structure:

  • Main Window
    • Dialog 1
      • Dialog 2 Opened By Dialog 1

When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.

So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:

childwindow.appMainWindow = window.opener

After making the assignment above, close dialog 1. Then from the code running inside dialog2, you should be able to use window.appMainWindow to reference the main window, window object.

Hope this helps.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

I use below code to get File Name & File Size from Uri in my project.

/**
 * Used to get file detail from uri.
 * <p>
 * 1. Used to get file detail (name & size) from uri.
 * 2. Getting file details from uri is different for different uri scheme,
 * 2.a. For "File Uri Scheme" - We will get file from uri & then get its details.
 * 2.b. For "Content Uri Scheme" - We will get the file details by querying content resolver.
 *
 * @param uri Uri.
 * @return file detail.
 */
public static FileDetail getFileDetailFromUri(final Context context, final Uri uri) {
    FileDetail fileDetail = null;
    if (uri != null) {
        fileDetail = new FileDetail();
        // File Scheme.
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            File file = new File(uri.getPath());
            fileDetail.fileName = file.getName();
            fileDetail.fileSize = file.length();
        }
        // Content Scheme.
        else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            Cursor returnCursor =
                    context.getContentResolver().query(uri, null, null, null, null);
            if (returnCursor != null && returnCursor.moveToFirst()) {
                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                fileDetail.fileName = returnCursor.getString(nameIndex);
                fileDetail.fileSize = returnCursor.getLong(sizeIndex);
                returnCursor.close();
            }
        }
    }
    return fileDetail;
}

/**
 * File Detail.
 * <p>
 * 1. Model used to hold file details.
 */
public static class FileDetail {

    // fileSize.
    public String fileName;

    // fileSize in bytes.
    public long fileSize;

    /**
     * Constructor.
     */
    public FileDetail() {

    }
}

How to search for a string in cell array in MATLAB?

Since 2011a, the recommended way is:

booleanIndex = strcmp('KU', strs)

If you want to get the integer index (which you often don't need), you can use:

integerIndex = find(booleanIndex);

strfind is deprecated, so try not to use it.

Sorting Python list based on the length of the string

When you pass a lambda to sort, you need to return an integer, not a boolean. So your code should instead read as follows:

xs.sort(lambda x,y: cmp(len(x), len(y)))

Note that cmp is a builtin function such that cmp(x, y) returns -1 if x is less than y, 0 if x is equal to y, and 1 if x is greater than y.

Of course, you can instead use the key parameter:

xs.sort(key=lambda s: len(s))

This tells the sort method to order based on whatever the key function returns.

EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass len directly as the key parameter to the function, thus eliminating the need for a lambda:

xs.sort(key=len)

And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort method, which creates a new list rather than sorting the existing one in-place:

print(sorted(xs, key=len))

How to check if a URL exists or returns 404 with Java?

There is nothing wrong with your code. It's the NBC.com doing tricks on you. When NBC.com decides that your browser is not capable of displaying PDF, it simply sends back a webpage regardless what you are requesting, even if it doesn't exist.

You need to trick it back by telling it your browser is capable, something like,

conn.setRequestProperty("User-Agent",
    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13");

Finding duplicate rows in SQL Server

I got a better option to get the duplicate records in a table

SELECT x.studid, y.stdname, y.dupecount
FROM student AS x INNER JOIN
(SELECT a.stdname, COUNT(*) AS dupecount
FROM student AS a INNER JOIN
studmisc AS b ON a.studid = b.studid
WHERE (a.studid LIKE '2018%') AND (b.studstatus = 4)
GROUP BY a.stdname
HAVING (COUNT(*) > 1)) AS y ON x.stdname = y.stdname INNER JOIN
studmisc AS z ON x.studid = z.studid
WHERE (x.studid LIKE '2018%') AND (z.studstatus = 4)
ORDER BY x.stdname

Result of the above query shows all the duplicate names with unique student ids and number of duplicate occurances

Click here to see the result of the sql

How to change resolution (DPI) of an image?

This article talks about modifying the EXIF data without the re-saving/re-compressing (and thus loss of information -- it actually uses a "trick"; there may be more direct libraries) required by the SetResolution approach. This was found on a quick google search, but I wanted to point out that all you need to do is modify the stored EXIF data.

Also: .NET lib for EXIF modification and another SO question. Google owns when you know good search terms.

Hive: Filtering Data between Specified Dates when Date is a String

Try this:

select * from your_table
where date >= '2020-10-01'  

How to increase application heap size in Eclipse?

In Eclipse Folder there is eclipse.ini file. Increase size -Xms512m -Xmx1024m

iPhone UIView Animation Best Practice

From the UIView reference's section about the beginAnimations:context: method:

Use of this method is discouraged in iPhone OS 4.0 and later. You should use the block-based animation methods instead.

Eg of Block-based Animation based on Tom's Comment

[UIView transitionWithView:mysuperview 
                  duration:0.75
                   options:UIViewAnimationTransitionFlipFromRight
                animations:^{ 
                    [myview removeFromSuperview]; 
                } 
                completion:nil];

How do I find the parent directory in C#?

IO.Path.GetFullPath(@"..\..")

If you clear the "bin\Debug\" in the Project properties -> Build -> Output path, then you can just use AppDomain.CurrentDomain.BaseDirectory

Oracle SQL - DATE greater than statement

You need to convert the string to date using the to_date() function

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');

This will work only if OrderDate is stored in Date format. If it is Varchar you should apply to_date() func on that column also like

 SELECT * FROM OrderArchive
    WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');

Query an XDocument for elements by name at any depth

There are two ways to accomplish this,

  1. LINQ to XML
  2. XPath

The following are samples of using these approaches,

List<XElement> result = doc.Root.Element("emails").Elements("emailAddress").ToList();

If you use XPath, you need to do some manipulation with the IEnumerable:

IEnumerable<XElement> mails = ((IEnumerable)doc.XPathEvaluate("/emails/emailAddress")).Cast<XElement>();

Note that

var res = doc.XPathEvaluate("/emails/emailAddress");

results either a null pointer, or no results.

Get list of certificates from the certificate store in C#

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certificate in store.Certificates){
    //TODO's
}

Unix's 'ls' sort by name

Check your .bashrc file for aliases.

How to save all console output to file in R?

If you are able to use the bash shell, you can consider simply running the R code from within a bash script and piping the stdout and stderr streams to a file. Here is an example using a heredoc:

File: test.sh

#!/bin/bash
# this is a bash script
echo "Hello World, this is bash"

test1=$(echo "This is a test")

echo "Here is some R code:"

Rscript --slave --no-save --no-restore - "$test1" <<EOF
  ## R code
  cat("\nHello World, this is R\n")
  args <- commandArgs(TRUE)
  bash_message<-args[1]
  cat("\nThis is a message from bash:\n")
  cat("\n",paste0(bash_message),"\n")
EOF

# end of script 

Then when you run the script with both stderr and stdout piped to a log file:

$ chmod +x test.sh
$ ./test.sh
$ ./test.sh &>test.log
$ cat test.log
Hello World, this is bash
Here is some R code:

Hello World, this is R

This is a message from bash:

 This is a test

Other things to look at for this would be to try simply pipping the stdout and stderr right from the R heredoc into a log file; I haven't tried this yet but it will probably work too.

How to make a HTML list appear horizontally instead of vertically using CSS only?

quite simple:

ul.yourlist li { float:left; }

or

ul.yourlist li { display:inline; }

How to echo in PHP, HTML tags

Separating HTML from PHP is the best method. It's less confusing and easy to debug.

<?php
  while($var)
  {
?>

     <div>
         <h3><a href="User<?php echo $i;?>"><?php echo $i;?></a></h3>
         <div>Lorem ipsum dolor sit amet.</div>
     </div>

<?php
  $i++;
  }
?>

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

I had this problem once before where one dialog box was throwing this error, while all the others were working perfectly. The answer was because I had another element with the same id="dialogBox" else ware on the page. I found this thread during a search, so hopefully this will help someone else.

How to get Url Hash (#) from server side

We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:

  1. When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.

  2. On the server you can use this value if you need to do something with it. You can even change it if you need to.

  3. On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.

  4. If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.

We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.

Before submit:

$("form").submit(function() {
  $("input", "#urlhash").val(window.location.hash);
});

On page load:

var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
  window.location.hash = hashVal;
}

IsHashValid() can check for "undefined" or other things you don't want to handle.

Also, make sure you use $(document).ready() appropriately, of course.

estimating of testing effort as a percentage of development time

Testing time is probably more closely correlated to feature scope than development time. I'd also argue (perhaps controversially) that testing time is correlated to the skill of your development team.

For a 6-to-9 month development effort, I demand a absolute minimum of 2 weeks testing time, performed by actual testers (not the development team) who are well-versed in the software they will be testing (i.e., 2 weeks does not include ramp-up time). This is for a project that has ~5 developers.

How can I disable inherited css styles?

Simplest is to class-ify all of the divs:

div.rounded {
    background: #CFFEB6 url('tr.gif') no-repeat top right;
}
div.rounded div.br {
    background: url('br.gif') no-repeat bottom right;
}
div.rounded div.br div.bl {
    background: url('bl.gif') no-repeat bottom left;
}
div.rounded div.br div.bl div.inner {
    padding: 10px;
}
.button {
    border: 1px solid #999;
     background:#eeeeee url('');
    text-align:center;
}
.button:hover {
    background-color:#c4e2f2;
}

And then use:

<div class='round'><div class='br'><div class='bl'><div class='inner'>
<div class='button'><a href='#'>Test</a></div>
</div></div></div></div>

NoSQL Use Case Scenarios or WHEN to use NoSQL

It really is an "it depends" kinda question. Some general points:

  • NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
  • NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
  • Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
  • It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
  • IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
  • It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
  • NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.

What exactly is the meaning of an API?

Well, in addition to all the answers, I am just adding an example.

As others said API stands for Application Programming Interface through which softwares can interact with each other. Note, not a human interaction.

Where it is used

An example: You are buying an item online through your credit card. You will provide credit card details and press 'continue' button. It will tell you whether your information is correct or not. To provide these results, there are lot of things in the background.

The application will send your credit card details to a remote application which will validate your information and send the result back to your application. API is used in this scenario.

I hope it helps for the beginners who don't understand really what API is.

ANOTHER EXAMPLE

Weather application

Without API - Weather application must open weather.com site and read the details as a human does.

With API - Weather application will send a message to weather.com and receive the result and then display it.

SOURCE - Various online resources

How to select a single column with Entity Framework?

If you're fetching a single item only then, you need use select before your FirstOrDefault()/SingleOrDefault(). And you can use anonymous object of the required properties.

var name = dbContext.MyTable.Select(x => new { x.UserId, x.Name }).FirstOrDefault(x => x.UserId == 1)?.Name;

Above query will be converted to this:

Select Top (1) UserId, Name from MyTable where UserId = 1;

For multiple items you can simply chain Select after Where:

var names = dbContext.MyTable.Where(x => x.UserId > 10).Select(x => x.Name);

Use anonymous object inside Select if you need more than one properties.

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

I found a combination of these answers gave me the best outcome - allowing me to still position the tooltip and attach it to the relevant container:

$('body').on('mouseenter', '[rel=tooltip]', function(){
  var el = $(this);
  if (el.data('tooltip') === undefined) {
    el.tooltip({
      placement: el.data("placement") || "top",
      container: el.data("container") || false
    });
  }
  el.tooltip('show');
});

$('body').on('mouseleave', '[rel=tooltip]', function(){
  $(this).tooltip('hide');
});

Relevant HTML:

<button rel="tooltip" class="btn" data-placement="bottom" data-container=".some-parent" title="Show Tooltip">
    <i class="icon-some-icon"></i>
</button>

How to loop over files in directory and change path and add suffix to filename

A couple of notes first: when you use Data/data1.txt as an argument, should it really be /Data/data1.txt (with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt and .txt files only:

#!/bin/bash
for filename in /Data/*.txt; do
    for ((i=0; i<=3; i++)); do
        ./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
    done
done

Notes:

  • /Data/*.txt expands to the paths of the text files in /Data (including the /Data/ part)
  • $( ... ) runs a shell command and inserts its output at that point in the command line
  • basename somepath .txt outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt -> file)

If you needed to run MyProgram with Data/file.txt instead of /Data/file.txt, use "${filename#/}" to remove the leading slash. On the other hand, if it's really Data not /Data you want to scan, just use for filename in Data/*.txt.

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

Plotting two variables as lines using ggplot2 on the same graph

You need the data to be in "tall" format instead of "wide" for ggplot2. "wide" means having an observation per row with each variable as a different column (like you have now). You need to convert it to a "tall" format where you have a column that tells you the name of the variable and another column that tells you the value of the variable. The process of passing from wide to tall is usually called "melting". You can use tidyr::gather to melt your data frame:

library(ggplot2)
library(tidyr)

test_data <-
  data.frame(
    var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
    var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
    date = seq(as.Date("2002-01-01"), by="1 month", length.out=100)
  )
test_data %>%
    gather(key,value, var0, var1) %>%
    ggplot(aes(x=date, y=value, colour=key)) +
    geom_line()

multiple series ggplot2

Just to be clear the data that ggplot is consuming after piping it via gather looks like this:

date        key     value
2002-01-01  var0    100.00000
2002-02-01  var0    115.16388 
...
2007-11-01  var1    114.86302
2007-12-01  var1    119.30996

Is there a way to list open transactions on SQL Server 2000 database?

DBCC OPENTRAN helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the transaction log of the specified database. Results are displayed only if there is an active transaction that exists in the log or if the database contains replication information.

An informational message is displayed if there are no active transactions in the log.

DBCC OPENTRAN

how to execute php code within javascript

Interaction of Javascript and PHP

We all grew up knowing that Javascript ran on the Client Side (ie the browser) and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.

But -- good news; it can be made to work and here's how.

The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.

First, to clarify the DHTML usage I'll cite this DHTML example:

<script type="text/javascript">

function updateContent() {
 var frameObj = document.getElementById("frameContent");
 var y = (frameObj.contentWindow || frameObj.contentDocument);

 if (y.document) y = y.document;
 y.body.style.backgroundColor="red";  // demonstration of failure to alter the display

 // create a default, simplistic alteration usinga fixed string.
 var textMsg = 'Say good night Gracy';

 y.write(textMsg);

 y.body.style.backgroundColor="#00ee00";  // visual confirmation that the updateContent() was effective

}
</script>

Assuming we have an html file with the ID="frameContent" somewhere, then we can alter the display with a simple < body onload="updateContent()" >

Golly gee; we don't need PHP to do that now do we! But that creates a structure for applying PHP provided content.

We change the webpage in question into a PHTML type to allow the server side PHP access to the content:

**foo.html becomes foo.phtml**

and we add to the top of that page. We also cause the php data to be loaded into globals for later access - - like this:

<?php
   global $msg1, $msg2, $textMsgPHP;

function getContent($filename) {
    if ($theData = file_get_contents($filename, FALSE)) {
        return "$theData";
    } else {
        echo "FAILED!";
        }
}
function returnContent($filename) {

  if ( $theData = getContent($filename) ) {
    // this works ONLY if $theData is one linear line (ie remove all \n)
    $textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
    return "$textPHP";
  } else {
    echo '<span class="ERR">Error opening source file :(\n</span>';  # $filename!\n";
  } 
}

// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 =       returnContent('dummy_frame_data.txt');
$msg2 =       returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');

?>

Now our javascripts can get to the PHP globals like this:

// by accessig the globals var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';

In the javascript, replace

var textMsg = 'Say good night Gracy';

with: // using php returnContent()

var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';

Summary:

  • the webpage to be modified MUST be a phtml or some php file
  • the first thing in that file MUST be the < ? php to get the dynamic data ?>
  • the php data MUST contain its own css styling (if content is in a frame)
  • the javascript to use the dynamic data must be in this same file
  • and we drop in/outof PHP as necessary to access the dynamic data
  • Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data

To be resolved: calling updateContent() with a filename and using it via onClick() instead of onLoad()

An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it

FontAwesome icons not showing. Why?

Just adding some more info to the above answers in regards with update on fontawesome,

If you use font awesome 5,

a. just copy-to-paste the below HTML,

<script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js" integrity="sha384-SlE991lGASHoBfWbelyBPLsUlwY1GwNDJo3jSJO04KZ33K2bwfV9YBauFfnzvynJ" crossorigin="anonymous"></script>

Note: Better to include all your scripts within the <body> {YOUR_SCRIPT_HERE}</body> and just before (YOUR_CLOSING_BODY)

b. And for example,

<li><a href="https://stackoverflow.com/users/{USER}" class="social-icons"><i class="fab fa-stack-overflow"></i></a></li>

How to keep indent for second line in ordered lists via CSS?

The ol, ul lists will work if you want you can also use a table with border: none in the css.

Convert output of MySQL query to utf8

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.

Sum the digits of a number

A base 10 number can be expressed as a series of the form

a × 10^p + b × 10^p-1 .. z × 10^0

so the sum of a number's digits is the sum of the coefficients of the terms.

Based on this information, the sum of the digits can be computed like this:

import math

def add_digits(n):
    # Assume n >= 0, else we should take abs(n)
    if 0 <= n < 10:
        return n
    r = 0
    ndigits = int(math.log10(n))
    for p in range(ndigits, -1, -1):
        d, n = divmod(n, 10 ** p)
        r += d
    return r

This is effectively the reverse of the continuous division by 10 in the accepted answer. Given the extra computation in this function compared to the accepted answer, it's not surprising to find that this approach performs poorly in comparison: it's about 3.5 times slower, and about twice as slow as

sum(int(x) for x in str(n))

How to auto adjust the <div> height according to content in it?

simply set the height to auto, that should fix the problem, because div are block elements so they stretch out to full width and height of any element contained in it. if height set to auto not working then simple don't add the height, it should adjust and make sure that the div is not inheriting any height from it's parent element as well...

Run Command Line & Command From VBS

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

C# Get a control's position on a form

Oddly enough, PointToClient and PointToScreen weren't ideal for my situation. Particularly because I'm working with offscreen controls that aren't associated with any form. I found sahin's solution the most helpful, but took out recursion and eliminated the Form termination. The solution below works for any of my controls visible or not, Form-contained or not, IContainered or not. Thanks Sahim.

private static Point FindLocation(Control ctrl)
{
    Point p;
    for (p = ctrl.Location; ctrl.Parent != null; ctrl = ctrl.Parent)
        p.Offset(ctrl.Parent.Location);
    return p;
}

How to run Pip commands from CMD

Make sure to also add "C:\Python27\Scripts" to your path. pip.exe should be in that folder. Then you can just run:

C:\> pip install modulename

.htaccess mod_rewrite - how to exclude directory from rewrite rule

Try this rule before your other rules:

RewriteRule ^(admin|user)($|/) - [L]

This will end the rewriting process.

Getting all documents from one collection in Firestore

I prefer to hide all code complexity in my services... so, I generally use something like this:

In my events.service.ts

    async getEvents() {
        const snapchot = await this.db.collection('events').ref.get();
        return new Promise <Event[]> (resolve => {
            const v = snapchot.docs.map(x => {
                const obj = x.data();
                obj.id = x.id;
                return obj as Event;
            });
            resolve(v);
        });
    }

In my sth.page.ts

   myList: Event[];

   construct(private service: EventsService){}

   async ngOnInit() {
      this.myList = await this.service.getEvents();
   }

Enjoy :)

REST API Best practice: How to accept list of parameter values as input

The standard way to pass a list of values as URL parameters is to repeat them:

http://our.api.com/Product?id=101404&id=7267261

Most server code will interpret this as a list of values, although many have single value simplifications so you may have to go looking.

Delimited values are also okay.

If you are needing to send JSON to the server, I don't like seeing it in in the URL (which is a different format). In particular, URLs have a size limitation (in practice if not in theory).

The way I have seen some do a complicated query RESTfully is in two steps:

  1. POST your query requirements, receiving back an ID (essentially creating a search criteria resource)
  2. GET the search, referencing the above ID
  3. optionally DELETE the query requirements if needed, but note that they requirements are available for reuse.

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

Sibling package imports

Here is another alternative that I insert at top of the Python files in tests folder:

# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))

How to call multiple JavaScript functions in onclick event?

You can add multiple only by code even if you have the second onclick atribute in the html it gets ignored, and click2 triggered never gets printed, you could add one on action the mousedown but that is just an workaround.

So the best to do is add them by code as in:

_x000D_
_x000D_
var element = document.getElementById("multiple_onclicks");_x000D_
element.addEventListener("click", function(){console.log("click3 triggered")}, false);_x000D_
element.addEventListener("click", function(){console.log("click4 triggered")}, false);
_x000D_
<button id="multiple_onclicks" onclick='console.log("click1 triggered");' onclick='console.log("click2 triggered");' onmousedown='console.log("click mousedown triggered");'  > Click me</button>
_x000D_
_x000D_
_x000D_

You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.

'namespace' but is used like a 'type'

if the error is

Line 26:
Line 27: @foreach (Customers customer in Model) Line 28: { Line 29:

give the full name space
like @foreach (Start.Models.customer customer in Model)

Not equal <> != operator on NULL

The only test for NULL is IS NULL or IS NOT NULL. Testing for equality is nonsensical because by definition one doesn't know what the value is.

Here is a wikipedia article to read:

https://en.wikipedia.org/wiki/Null_(SQL)

In Angular, how to add Validator to FormControl after control is created?

You simply pass the FormControl an array of validators.

Here's an example showing how you can add validators to an existing FormControl:

this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);

Note, this will reset any existing validators you added when you created the FormControl.

set initial viewcontroller in appdelegate - swift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var exampleViewController: ExampleViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ExampleController") as! ExampleViewController

    self.window?.rootViewController = exampleViewController

    self.window?.makeKeyAndVisible()

    return true
}

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

I am just adding this answer for an awkward situation from DB provider.

what happened in our case is the primary and secondary db shifted reversely (primary to secondary and vice versa) and we are getting the same error.

so please check in the configuration settings for database status which may help you.

How to install python-dateutil on Windows?

If you are offline and have untared the package, you can use command prompt.

Navigate to the untared folder and run:

python setup.py install

How do you find out which version of GTK+ is installed on Ubuntu?

Try,

apt-cache policy libgtk2.0-0 libgtk-3-0 

or,

dpkg -l libgtk2.0-0 libgtk-3-0

How to Add Stacktrace or debug Option when Building Android Studio Project

You can use GUI to add these gradle command line flags from

File > Settings > Build, Execution, Deployment > Compiler

For MacOS user, it's here

Android Studio > Preferences > Build, Execution, Deployment > Compiler

like this (add --stacktrace or --debug)

enter image description here

Note that the screenshot is from before 0.8.10, the option is no longer in the Compiler > Gradle section, it's now in a separate section named Compiler (Gradle-based Android Project)

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

The cleanest way I found to do this is create a child of 'ThemeOverlay.AppCompat.Dark.ActionBar'. In the example, I set the Toolbar's background color to RED and text's color to BLUE.

<style name="MyToolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">#FF0000</item>
    <item name="android:textColorPrimary">#0000FF</item>
</style>

You can then apply your theme to the toolbar:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    app:theme="@style/MyToolbar"
    android:minHeight="?attr/actionBarSize"/>

How to reduce a huge excel file

I wrote a VBA file to add a tool cleaning these abnormally biggest file. This script clear all columns and rows after the last cells realy used to reset the last cells ( [Ctrl]+[End] ), and it also provides enable images compression.

I dev an AddIns with auto install (just run it with macro enabled) to include in context menu many new buttons:

  1. Optimize
  2. Optimize and Save
  3. Disable Optimizer

Context menu after install it

This is based on KB of Microsoft office 2003 and answer of PP. with personals improvement :

  1. add compression of images
  2. fix bug for Columns
  3. feat compatibility with excel 2007 - 2010 - ... (more than 255 columns)

SOLUTION > you can download my *.xlam file ToolsKit

the main code is

Sub ClearExcessRowsAndColumns()
    Dim ar As Range, r As Double, c As Double, tr As Double, tc As Double
    Dim wksWks As Worksheet, ur As Range, arCount As Integer, i As Integer
    Dim blProtCont As Boolean, blProtScen As Boolean, blProtDO As Boolean
    Dim shp As Shape
    Application.ScreenUpdating = False
    On Error Resume Next
    For Each wksWks In ActiveWorkbook.Worksheets
      Err.Clear
      'Store worksheet protection settings and unprotect if protected.
      blProtCont = wksWks.ProtectContents
      blProtDO = wksWks.ProtectDrawingObjects
      blProtScen = wksWks.ProtectScenarios
      wksWks.Unprotect ""
      If Err.Number = 1004 Then
         Err.Clear
         MsgBox "'" & wksWks.Name & "' is protected with a password and cannot be checked.", vbInformation
      Else
         Application.StatusBar = "Checking " & wksWks.Name & ", Please Wait..."
         r = 0
         c = 0

         'Determine if the sheet contains both formulas and constants
         Set ur = Union(wksWks.UsedRange.SpecialCells(xlCellTypeConstants), wksWks.UsedRange.SpecialCells(xlCellTypeFormulas))
         'If both fails, try constants only
         If Err.Number = 1004 Then
            Err.Clear
            Set ur = wksWks.UsedRange.SpecialCells(xlCellTypeConstants)
         End If
         'If constants fails then set it to formulas
         If Err.Number = 1004 Then
            Err.Clear
            Set ur = wksWks.UsedRange.SpecialCells(xlCellTypeFormulas)
         End If
         'If there is still an error then the worksheet is empty
         If Err.Number <> 0 Then
            Err.Clear
            If wksWks.UsedRange.Address <> "$A$1" Then
               ur.EntireRow.Delete
            Else
               Set ur = Nothing
            End If
         End If
         'On Error GoTo 0
         If Not ur Is Nothing Then
            arCount = ur.Areas.Count
            'determine the last column and row that contains data or formula
            For Each ar In ur.Areas
               i = i + 1
               tr = ar.Range("A1").Row + ar.Rows.Count - 1
               tc = ar.Range("A1").Column + ar.Columns.Count - 1
               If tc > c Then c = tc
               If tr > r Then r = tr
            Next
            'Determine the area covered by shapes
            'so we don't remove shading behind shapes
            For Each shp In wksWks.Shapes
               tr = shp.BottomRightCell.Row
               tc = shp.BottomRightCell.Column
               If tc > c Then c = tc
               If tr > r Then r = tr
            Next
            Application.StatusBar = "Clearing Excess Cells in " & wksWks.Name & ", Please Wait..."
            Set ur = wksWks.Rows(r + 1 & ":" & wksWks.Rows.Count)
                'Reset row height which can also cause the lastcell to be innacurate
                ur.EntireRow.RowHeight = wksWks.StandardHeight
                ur.Clear

            Set ur = wksWks.Columns(ColLetter(c + 1) & ":" & ColLetter(wksWks.Columns.Count))
                'Reset column width which can also cause the lastcell to be innacurate
                ur.EntireColumn.ColumnWidth = wksWks.StandardWidth
                ur.Clear
         End If
      End If
      'Reset protection.
      wksWks.Protect "", blProtDO, blProtCont, blProtScen
      Err.Clear
    Next
    Application.StatusBar = False
    ' prepare les combinaison de touches pour la validation automatique de la fenetre
    ' Application.SendKeys "%(oe)~{TAB}~"

    ' ouvre la fenetre de compression des images
    Application.CommandBars.ExecuteMso "PicturesCompress"
    Application.ScreenUpdating = True
End Sub


Function ColLetter(ColNumber As Integer) As String
    ColLetter = Left(Cells(1, ColNumber).Address(False, False), Len(Cells(1, ColNumber).Address(False, False)) - 1)
End Function

Test class with a new() call in it with Mockito

    public class TestedClass {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
    }
  }

-- Test Class:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(TestedClass.class)
    public class TestedClassTest {

        @Test
        public void testLogin() {
            LoginContext lcMock = mock(LoginContext.class);
            whenNew(LoginContext.class).withArguments(anyString(), anyString()).thenReturn(lcMock);
//comment: this is giving mock object ( lcMock )
            TestedClass tc = new TestedClass();
            tc.login ("something", "something else"); ///  testing this method.
            // test the login's logic
        }
    }

When calling the actual method tc.login ("something", "something else"); from the testLogin() { - This LoginContext lc is set to null and throwing NPE while calling lc.doThis();

How to create unit tests easily in eclipse

Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.

Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.

If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.

Fetch frame count with ffmpeg

Since my comment got a few upvotes, I figured I'd leave it as an answer:

ffmpeg -i 00000.avi -map 0:v:0 -c copy -f null -y /dev/null 2>&1 | grep -Eo 'frame= *[0-9]+ *' | grep -Eo '[0-9]+' | tail -1

This should be fast, since no encoding is being performed. ffmpeg will just demux the file and read (decode) the first video stream as quickly as possible. The first grep command will grab the text that shows the frame. The second grep command will grab just the number from that. The tail command will just show the final line (final frame count).

Creating a random string with A-Z and 0-9 in Java

RandomStringUtils from Apache commons-lang might help:

RandomStringUtils.randomAlphanumeric(17).toUpperCase()

2017 update: RandomStringUtils has been deprecated, you should now use RandomStringGenerator.

How to use BeanUtils.copyProperties?

There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.

One is

org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)

Another is

org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)

Pay attention to the opposite position of parameters.

./configure : /bin/sh^M : bad interpreter

Just adding sh before script name make it work in my case.

What is the best (and safest) way to merge a Git branch into master?

This is from GitLab: Just follow the instructions:

enter image description here

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

Having the same issue in Flask, I had already a template that loaded JQuery, Popper and Bootstrap. I was extending that template into other template that I was using as a base to load the page that had the table.

For some reason in Flask apparently the files in the outer template load before the files in the tables above in the hierarchy (the ones you are extending) so JQuery was loading before the DataTables files causing the issue.

I had to create another template where I run all my imports of JS CDNs in the same place, that solved the issue.

Making a Sass mixin with optional arguments

You can put the property with null as a default value and if you don't pass the parameter it will not be interpreted.

@mixin box-shadow($top, $left, $blur, $color, $inset:null) {
  -webkit-box-shadow: $top $left $blur $color $inset;
  -moz-box-shadow:    $top $left $blur $color $inset;
  box-shadow:         $top $left $blur $color $inset;
}

This means you can write the include statement like this.

@include box-shadow($top, $left, $blur, $color);

Instead of writing it like this.

@include box-shadow($top, $left, $blur, $color, null);

As shown in the answer here

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

I am not sure I understand what you want, but based on what I understood

the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"

you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)

p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")

worked for me, see the picture

enter image description here

I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code

PHP Function with Optional Parameters

function yourFunction($var1, $var2, $optional = Null){
   ... code
}

You can make a regular function and then add your optional variables by giving them a default Null value.

A Null is still a value, if you don't call the function with a value for that variable, it won't be empty so no error.

Converting JavaScript object with numeric keys into array

Assuming your have a value like the following

var obj = {"0":"1","1":"2","2":"3","3":"4"};

Then you can turn this into a javascript array using the following

var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array

This works for converting json into multi-diminsional javascript arrays as well.

None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.

Expected corresponding JSX closing tag for input Reactjs

You have to close all tags like , etc for this to not show.

Generating CSV file for Excel, how to have a newline inside a value

Newline inside a value seems to work if you use semicolon as separator, instead of comma or tab, and use quotes.

This works for me in both Excel 2010 and Excel 2000. However, surprisingly, it works only when you open the file as a new spreadsheet, not when you import it into an existing spreadsheet using the data import feature.

How to access form methods and controls from a class in C#?

You need access to the object.... you can't simply ask the form class....

eg...

you would of done some thing like

Form1.txtLog.Text = "blah"

instead of

Form1 blah = new Form1();
blah.txtLog.Text = "hello"

Java, reading a file from current directory?

Thanks @Laurence Gonsalves your answer helped me a lot. your current directory will working directory of proccess so you have to give full path start from your src directory like mentioned below:

public class Run {
public static void main(String[] args) {
    File inputFile = new File("./src/main/java/input.txt");
    try {
        Scanner reader = new Scanner(inputFile);
        while (reader.hasNextLine()) {
            String data = reader.nextLine();
            System.out.println(data);
            
        }
        reader.close();
    } catch (FileNotFoundException e) {
        System.out.println("scanner error");
        e.printStackTrace();
    }
}

}

While my input.txt file is in same directory.

enter image description here

How to cast or convert an unsigned int to int in C?

Some explain from C++Primer 5th Page 35

If we assign an out-of-range value to an object of unsigned type, the result is the remainder of the value modulo the number of values the target type can hold.

For example, an 8-bit unsigned char can hold values from 0 through 255, inclusive. If we assign a value outside the range, the compiler assigns the remainder of that value modulo 256.

unsigned char c = -1; // assuming 8-bit chars, c has value 255

If we assign an out-of-range value to an object of signed type, the result is undefined. The program might appear to work, it might crash, or it might produce garbage values.

Page 160: If any operand is an unsigned type, the type to which the operands are converted depends on the relative sizes of the integral types on the machine.

... When the signedness differs and the type of the unsigned operand is the same as or larger than that of the signed operand, the signed operand is converted to unsigned.

The remaining case is when the signed operand has a larger type than the unsigned operand. In this case, the result is machine dependent. If all values in the unsigned type fit in the large type, then the unsigned operand is converted to the signed type. If the values don't fit, then the signed operand is converted to the unsigned type.

For example, if the operands are long and unsigned int, and int and long have the same size, the length will be converted to unsigned int. If the long type has more bits, then the unsigned int will be converted to long.

I found reading this book is very helpful.

Can You Get A Users Local LAN IP Address Via JavaScript?

The WebRTC API can be used to retrieve the client's local IP.

However the browser may not support it, or the client may have disabled it for security reasons. In any case, one should not rely on this "hack" on the long term as it is likely to be patched in the future (see Cullen Fluffy Jennings's answer).

The ECMAScript 6 code below demonstrates how to do that.

/* ES6 */
const findLocalIp = (logInfo = true) => new Promise( (resolve, reject) => {
    window.RTCPeerConnection = window.RTCPeerConnection 
                            || window.mozRTCPeerConnection 
                            || window.webkitRTCPeerConnection;

    if ( typeof window.RTCPeerConnection == 'undefined' )
        return reject('WebRTC not supported by browser');

    let pc = new RTCPeerConnection();
    let ips = [];

    pc.createDataChannel("");
    pc.createOffer()
     .then(offer => pc.setLocalDescription(offer))
     .catch(err => reject(err));
    pc.onicecandidate = event => {
        if ( !event || !event.candidate ) {
            // All ICE candidates have been sent.
            if ( ips.length == 0 )
                return reject('WebRTC disabled or restricted by browser');

            return resolve(ips);
        }

        let parts = event.candidate.candidate.split(' ');
        let [base,componentId,protocol,priority,ip,port,,type,...attr] = parts;
        let component = ['rtp', 'rtpc'];

        if ( ! ips.some(e => e == ip) )
            ips.push(ip);

        if ( ! logInfo )
            return;

        console.log(" candidate: " + base.split(':')[1]);
        console.log(" component: " + component[componentId - 1]);
        console.log("  protocol: " + protocol);
        console.log("  priority: " + priority);
        console.log("        ip: " + ip);
        console.log("      port: " + port);
        console.log("      type: " + type);

        if ( attr.length ) {
            console.log("attributes: ");
            for(let i = 0; i < attr.length; i += 2)
                console.log("> " + attr[i] + ": " + attr[i+1]);
        }

        console.log();
    };
} );

Notice I write return resolve(..) or return reject(..) as a shortcut. Both of those functions do not return anything.

Then you may have something this :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Local IP</title>
</head>
<body>
    <h1>My local IP is</h1>
    <p id="ip">Loading..</p>
    <script src="ip.js"></script>
    <script>
    let p = document.getElementById('ip');
    findLocalIp().then(
        ips => {
            let s = '';
            ips.forEach( ip => s += ip + '<br>' );
            p.innerHTML = s;
        },
        err => p.innerHTML = err
    );
    </script>
</body>
</html>

How to resolve conflicts in EGit

Just right click on a conflicting file and add it to the index after resolving conflicts.

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

How to extract the decision rules from scikit-learn decision-tree?

Now you can use export_text.

from sklearn.tree import export_text

r = export_text(loan_tree, feature_names=(list(X_train.columns)))
print(r)

A complete example from [sklearn][1]

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_text
iris = load_iris()
X = iris['data']
y = iris['target']
decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
decision_tree = decision_tree.fit(X, y)
r = export_text(decision_tree, feature_names=iris['feature_names'])
print(r)

substring of an entire column in pandas dataframe

I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.

attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))

Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.

how to return a char array from a function in C

Lazy notes in comments.

#include <stdio.h>
// for malloc
#include <stdlib.h>

// you need the prototype
char *substring(int i,int j,char *ch);


int main(void /* std compliance */)
{
  int i=0,j=2;
  char s[]="String";
  char *test;
  // s points to the first char, S
  // *s "is" the first char, S
  test=substring(i,j,s); // so s only is ok
  // if test == NULL, failed, give up
  printf("%s",test);
  free(test); // you should free it
  return 0;
}


char *substring(int i,int j,char *ch)
{
  int k=0;
  // avoid calc same things several time
  int n = j-i+1; 
  char *ch1;
  // you can omit casting - and sizeof(char) := 1
  ch1=malloc(n*sizeof(char));
  // if (!ch1) error...; return NULL;

  // any kind of check missing:
  // are i, j ok? 
  // is n > 0... ch[i] is "inside" the string?...
  while(k<n)
    {   
      ch1[k]=ch[i];
      i++;k++;
    }   

  return ch1;
}

Uncaught ReferenceError: function is not defined with onclick

I think you put the function in the $(document).ready....... The functions are always provided out the $(document).ready.......

Changing all files' extensions in a folder with one command on Windows

What worked for me is this one(cd to the folder first):

Get-ChildItem -Filter *.old | Rename-Item -NewName {[System.IO.Path]::ChangeExtension($_.Name, ".new")}

What is difference between Lightsail and EC2?

Testing¹ reveals that Lightsail instances in fact are EC2 instances, from the t2 class of burstable instances.

EC2, of course, has many more instance families and classes other than the t2, almost all of which are more "powerful" (or better equipped for certain tasks) than these, but also much more expensive. But for meaningful comparisons, the 512 MiB Lightsail instance appears to be completely equivalent in specifications to the similarly-priced t2.nano, the 1GiB is a t2.micro, the 2 GiB is a t2.small, etc.

Lightsail is a lightweight, simplified product offering -- hard disks are fixed size EBS SSD volumes, instances are still billable when stopped, security group rules are much less flexible, and only a very limited subset of EC2 features and options are accessible.

It also has a dramatically simplified console, and even though the machines run in EC2, you can't see them in the EC2 section of the AWS console. The instances run in a special VPC, but this aspect is also provisioned automatically, and invisible in the console. Lightsail supports optionally peering this hidden VPC with your default VPC in the same AWS region, allowing Lightsail instances to access services like EC2 and RDS in the default VPC within the same AWS account.²

Bandwidth is unlimited, but of course free bandwidth is not -- however, Lightsail instances do include a significant monthly bandwidth allowance before any bandwidth-related charges apply.³ Lightsail also has a simplified interface to Route 53 with limited functionality.

But if those sound like drawbacks, they aren't. The point of Lightsail seems to be simplicity. The flexibility of EC2 (and much of AWS) leads inevitably to complexity. The target market for Lightsail appears to be those who "just want a simple VPS" without having to navigate the myriad options available in AWS services like EC2, EBS, VPC, and Route 53. There is virtually no learning curve, here. You don't even technically need to know how to use SSH with a private key -- the Lightsail console even has a built-in SSH client -- but there is no requirement that you use it. You can access these instances normally, with a standard SSH client.


¹Lightsail instances, just like "regular" EC2 (VPC and Classic) instances, have access to the instance metadata service, which allows an instance to discover things about itself, such as its instance type and availability zone. Lightsail instances are identified in the instance metadata as t2 machines.

²The Lightsail docs are not explicit about the fact that peering only works with your Default VPC, but this appears to be the case. If your AWS account was created in 2013 or before, then you may not actually have a VPC with the "Default VPC" designation. This can be resolved by submitting a support request, as I explained in Can't establish VPC peering connection from Amazon Lightsail (at Server Fault).

³The bandwidth allowance applies to both inbound and outbound traffic; after this total amount of traffic is exceeded, inbound traffic continues to be free, but outbound traffic becomes billable. See "What does data transfer cost?" in the Lightsail FAQ.

No appenders could be found for logger(log4j)?

For me, the reason was apparently different, and the error message misleading.

With just this in my build.gradle, it would complain that slf4j was missing at the beginning of the log, but still log things, albeit in a poor format:

    compile 'log4j:log4j:1.2.17'

Adding that dependency would cause the discussed "no appenders could be found" error message for me, even though I had defined them in src/main/java/log4j.properties:

    compile 'log4j:log4j:1.2.17'
    compile 'org.slf4j:slf4j-log4j12:1.7.25'

Finally, adding the following dependency (which I only guessed at by copycatting it from another project) resolved the issue:

    compile 'log4j:log4j:1.2.17'
    compile 'org.slf4j:slf4j-log4j12:1.7.25'
    compile 'commons-logging:commons-logging:1.2'

I don't know why, but with this it works. Any insights on that?

How to redirect all HTTP requests to HTTPS

I found out that the best way for https and www on domain is

RewriteCond %{HTTPS} off 
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

How to print in C

try this:

printf("%d", addNumber(a,b))

Here's the documentation for printf.

Properties order in Margin

Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.

All clockwise:

  • WPF start West (left->top->right->bottom)
  • Netscape (ie CSS) start North (top->right->bottom->left)

T-SQL split string

If you need a quick ad-hoc solution for common cases with minimum code, then this recursive CTE two-liner will do it:

DECLARE @s VARCHAR(200) = ',1,2,,3,,,4,,,,5,'

;WITH
a AS (SELECT i=-1, j=0 UNION ALL SELECT j, CHARINDEX(',', @s, j + 1) FROM a WHERE j > i),
b AS (SELECT SUBSTRING(@s, i+1, IIF(j>0, j, LEN(@s)+1)-i-1) s FROM a WHERE i >= 0)
SELECT * FROM b

Either use this as a stand-alone statement or just add the above CTEs to any of your queries and you will be able to join the resulting table b with others for use in any further expressions.

edit (by Shnugo)

If you add a counter, you will get a position index together with the List:

DECLARE @s VARCHAR(200) = '1,2333,344,4'

;WITH
a AS (SELECT n=0, i=-1, j=0 UNION ALL SELECT n+1, j, CHARINDEX(',', @s, j+1) FROM a WHERE j > i),
b AS (SELECT n, SUBSTRING(@s, i+1, IIF(j>0, j, LEN(@s)+1)-i-1) s FROM a WHERE i >= 0)
SELECT * FROM b;

The result:

n   s
1   1
2   2333
3   344
4   4

Select statement to find duplicates on certain fields

CREATE TABLE #tmp
(
    sizeId Varchar(MAX)
)

INSERT  #tmp 
    VALUES ('44'),
        ('44,45,46'),
        ('44,45,46'),
        ('44,45,46'),
        ('44,45,46'),
        ('44,45,46'),
        ('44,45,46')


SELECT * FROM #tmp
DECLARE @SqlStr VARCHAR(MAX)

SELECT @SqlStr = STUFF((SELECT ',' + sizeId
              FROM #tmp
              ORDER BY sizeId
              FOR XML PATH('')), 1, 1, '') 


SELECT TOP 1 * FROM (
select items, count(*)AS Occurrence
  FROM dbo.Split(@SqlStr,',')
  group by items
  having count(*) > 1
  )K
  ORDER BY K.Occurrence DESC    

Dynamically Add Variable Name Value Pairs to JSON Object

You can achieve this using Lodash _.assign function.

_x000D_
_x000D_
var ipID = {};_x000D_
_.assign(ipID, {'name': "value"}, {'anotherName': "anotherValue"});_x000D_
console.log(ipID);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

How to correctly assign a new string value?

The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

strcpy(p.name, "Jane");

Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

char* firstName = "Johnnie";
char* surname = "B. Goode";
person p;

p.name = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);

p.age = 25;
strcpy(p.name, firstName);
strcpy(p.surname, surname);

printf("Name: %s; Age: %d\n",p.name,p.age);

free(p.surname);
free(p.name);

How to read Excel cell having Date with Apache POI?

Try this code.

XSSFWorkbook workbook = new XSSFWorkbook(new File(result));
    XSSFSheet sheet = workbook.getSheetAt(0);

    // Iterate through each rows one by one
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        // For each row, iterate through all the columns
        Iterator<Cell> cellIterator = row.cellIterator();

        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                if (cell.getNumericCellValue() != 0) {
                    //Get date
                    Date date = row.getCell(0).getDateCellValue();



                    //Get datetime
                    cell.getDateCellValue()


                    System.out.println(date.getTime());
                }
                break;
            }
        }
    }

Hope is help.

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

Answer: 09 December 2015

Personally, I found the accepted answer both concise (good) and terse (bad). Appreciate this statement might be subjective, so please read this answer and see if you agree or disagree

The example given in the question was something like Ruby's:

x.times do |i|
  do_stuff(i)
end

Expressing this in JS using below would permit:

times(x)(doStuff(i));

Here is the code:

let times = (n) => {
  return (f) => {
    Array(n).fill().map((_, i) => f(i));
  };
};

That's it!

Simple example usage:

let cheer = () => console.log('Hip hip hooray!');

times(3)(cheer);

//Hip hip hooray!
//Hip hip hooray!
//Hip hip hooray!

Alternatively, following the examples of the accepted answer:

let doStuff = (i) => console.log(i, ' hi'),
  once = times(1),
  twice = times(2),
  thrice = times(3);

once(doStuff);
//0 ' hi'

twice(doStuff);
//0 ' hi'
//1 ' hi'

thrice(doStuff);
//0 ' hi'
//1 ' hi'
//2 ' hi'

Side note - Defining a range function

A similar / related question, that uses fundamentally very similar code constructs, might be is there a convenient Range function in (core) JavaScript, something similar to underscore's range function.

Create an array with n numbers, starting from x

Underscore

_.range(x, x + n)

ES2015

Couple of alternatives:

Array(n).fill().map((_, i) => x + i)

Array.from(Array(n), (_, i) => x + i)

Demo using n = 10, x = 1:

> Array(10).fill().map((_, i) => i + 1)
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

> Array.from(Array(10), (_, i) => i + 1)
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

In a quick test I ran, with each of the above running a million times each using our solution and doStuff function, the former approach (Array(n).fill()) proved slightly faster.

Using scp to copy a file to Amazon EC2 instance?

This just worked for me. I used a combination of two other answers to this question.

scp -i /Users/me/documents/myKP.pem -r /Users/me/desktop/testDir \
       [email protected]:/home/ec2-user/remoteDir

The "[email protected]" is copy-and-pasted from your ec2 instance's public DNS.

Default value in an asp.net mvc view model

Create a base class for your ViewModels with the following constructor code which will apply the DefaultValueAttributeswhen any inheriting model is created.

public abstract class BaseViewModel
{
    protected BaseViewModel()
    {
        // apply any DefaultValueAttribute settings to their properties
        var propertyInfos = this.GetType().GetProperties();
        foreach (var propertyInfo in propertyInfos)
        {
            var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
            if (attributes.Any())
            {
                var attribute = (DefaultValueAttribute) attributes[0];
                propertyInfo.SetValue(this, attribute.Value, null);
            }
        }
    }
}

And inherit from this in your ViewModels:

public class SearchModel : BaseViewModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale { get; set; }
}

Does a TCP socket connection have a "keep alive"?

If you're behind a masquerading NAT (as most home users are these days), there is a limited pool of external ports, and these must be shared among the TCP connections. Therefore masquerading NATs tend to assume a connection has been terminated if no data has been sent for a certain time period.

This and other such issues (anywhere in between the two endpoints) can mean the connection will no longer "work" if you try to send data after a reasonble idle period. However, you may not discover this until you try to send data.

Using keepalives both reduces the chance of the connection being interrupted somewhere down the line, and also lets you find out about a broken connection sooner.

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

LINQ Group By into a Dictionary Object

For @atari2600, this is what the answer would look like using ToLookup in lambda syntax:

var x = listOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToLookup(customObject => customObject);

Basically, it takes the IGrouping and materializes it for you into a dictionary of lists, with the values of PropertyName as the key.

Does height and width not apply to span?

Span is an inline element. It has no width or height.

You could turn it into a block-level element, then it will accept your dimension directives.

span.product__specfield_8_arrow
{
    display: inline-block; /* or block */
}

What is a constant reference? (not a reference to a constant)

The statement icr=y; does not make the reference refer to y; it assigns the value of y to the variable that icr refers to, i.

References are inherently const, that is you can't change what they refer to. There are 'const references' which are really 'references to const', that is you can't change the value of the object they refer to. They are declared const int& or int const& rather than int& const though.

Difference between web reference and service reference?

The low-level answer here is that a Web Reference will create a client proxy class that allows your code to talk to a Web Service that is described via WSDL and communicates via SOAP or HTTP GET (other posters indicate that it is only ASMX, but Web References can also talk to Java-based Web Services or Python-based or Ruby so long as they all talk WSDL and conform to the WS-I interoperability standard).

A Service Reference will create a client proxy class that communicates with a WCF-based service : regardless of whether that WCF service is a Web Service or not.

Centering FontAwesome icons vertically and horizontally

I just lowered the height to 28px on the .login-icon [class*='icon-'] Here's the fiddle: http://jsfiddle.net/mZHg7/

.login-icon [class*='icon-']{
    height: 28px;
    width: 50px;
    display: inline-block;
    text-align: center;
    vertical-align: baseline;
}

Explanation of JSONB introduced by PostgreSQL

A simple explanation of the difference between json and jsonb (original image by PostgresProfessional):

SELECT '{"c":0,   "a":2,"a":1}'::json, '{"c":0,   "a":2,"a":1}'::jsonb;

          json          |        jsonb 
------------------------+--------------------- 
 {"c":0,   "a":2,"a":1} | {"a": 1, "c": 0} 
(1 row)
  • json: textual storage «as is»
  • jsonb: no whitespaces
  • jsonb: no duplicate keys, last key win
  • jsonb: keys are sorted

More in speech video and slide show presentation by jsonb developers. Also they introduced JsQuery, pg.extension provides powerful jsonb query language

What is the difference between public, private, and protected?

PHP manual has a good read on the question here.

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

'mvn' is not recognized as an internal or external command,

Make sure you have your maven bin directory in the path and the JAVA_HOME property set

Oracle 11g SQL to get unique values in one column of a multi-column query

This will be more efficient, plus you have control over the ordering it uses to pick a value:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language
               ORDER BY person)
      ,language
FROM   tableA;

If you really don't care which person is picked for each language, you can omit the ORDER BY clause:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language)
      ,language
FROM   tableA;

Regular expression to extract text between square brackets

(?<=\[).*?(?=\]) works good as per explanation given above. Here's a Python example:

import re 
str = "Pagination.go('formPagination_bottom',2,'Page',true,'1',null,'2013')"
re.search('(?<=\[).*?(?=\])', str).group()
"'formPagination_bottom',2,'Page',true,'1',null,'2013'"

Maximum length of the textual representation of an IPv6 address?

45 characters.

You might expect an address to be

0000:0000:0000:0000:0000:0000:0000:0000

8 * 4 + 7 = 39

8 groups of 4 digits with 7 : between them.

But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by ., eg. [::ffff:192.168.100.228]. Written out fully:

0000:0000:0000:0000:0000:ffff:192.168.100.228

(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45

Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4] for the address above.

python: how to check if a line is an empty line

I think is more robust to use regular expressions:

import re

for i, line in enumerate(content):
    print line if not (re.match('\r?\n', line)) else pass

This would match in Windows/unix. In addition if you are not sure about lines containing only space char you could use '\s*\r?\n' as expression

git ignore vim temporary files

Here is the actual VIM code that generates the swap file extensions:

/* 
 * Change the ".swp" extension to find another file that can be used. 
 * First decrement the last char: ".swo", ".swn", etc. 
 * If that still isn't enough decrement the last but one char: ".svz" 
 * Can happen when editing many "No Name" buffers. 
 */
if (fname[n - 1] == 'a')        /* ".s?a" */
{   
    if (fname[n - 2] == 'a')    /* ".saa": tried enough, give up */
    {   
        EMSG(_("E326: Too many swap files found"));
        vim_free(fname);
        fname = NULL;
        break;  
    }
    --fname[n - 2];             /* ".svz", ".suz", etc. */
    fname[n - 1] = 'z' + 1;
}
--fname[n - 1];                 /* ".swo", ".swn", etc. */

This will generate swap files of the format:

[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]

Which is pretty much what is included in github's own gitignore file for VIM.

As others have correctly noted, this .gitignore will also ignore .svg image files and .swf adobe flash files.

Convert generic List/Enumerable to DataTable?

Marc Gravell's answer but in VB.NET

Public Shared Function ToDataTable(Of T)(data As IList(Of T)) As DataTable
    Dim props As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
    Dim table As New DataTable()
    For i As Integer = 0 To props.Count - 1
            Dim prop As PropertyDescriptor = props(i)
            table.Columns.Add(prop.Name, prop.PropertyType)
    Next
    Dim values As Object() = New Object(props.Count - 1) {}
    For Each item As T In data
            For i As Integer = 0 To values.Length - 1
                    values(i) = props(i).GetValue(item)
            Next
            table.Rows.Add(values)
    Next
    Return table
End Function

Vue.js img src concatenate variable and text

In another case I'm able to use template literal ES6 with backticks, so for yours could be set as:

<img v-bind:src="`${imgPreUrl()}img/logo.png`">

Reloading a ViewController

Direct to your ViewController again. in my situation [self.view setNeedsDisplay]; and [self viewDidLoad]; [self viewWillAppear:YES];does not work, but the method below worked.

In objective C

UIStoryboard *MyStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil ];
UIViewController *vc = [MyStoryboard instantiateViewControllerWithIdentifier:@"ViewControllerStoryBoardID"];
[self presentViewController:vc animated:YES completion:nil];

Swift:

let secondViewController = self.storyboard!.instantiateViewControllerWithIdentifier("ViewControllerStoryBoardID")   
self.presentViewController(secondViewController, animated: true, completion: nil)

How do I import a .sql file in mysql database using PHP?

Warning: mysql_* extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
Whenever possible, importing a file to MySQL should be delegated to MySQL client.

I have got another way to do this, try this

<?php

// Name of the file
$filename = 'churc.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '';
// Database name
$mysql_database = 'dump';

// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());

// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
    continue;

// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
    // Perform the query
    mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
    // Reset temp variable to empty
    $templine = '';
}
}
 echo "Tables imported successfully";
?>

This is working for me

How to break out of a loop in Bash?

It's not that different in bash.

workdone=0
while : ; do
  ...
  if [ "$workdone" -ne 0 ]; then
      break
  fi
done

: is the no-op command; its exit status is always 0, so the loop runs until workdone is given a non-zero value.


There are many ways you could set and test the value of workdone in order to exit the loop; the one I show above should work in any POSIX-compatible shell.

In jQuery, how do I get the value of a radio button when they all have the same name?

DEMO : https://jsfiddle.net/ipsjolly/xygr065w/

$(function(){
    $("#submit").click(function(){      
        alert($('input:radio:checked').val());
    });
 });

How long will my session last?

This is the one. The session will last for 1440 seconds (24 minutes).

session.gc_maxlifetime  1440    1440

How to add a right button to a UINavigationController?

Try adding the button to the navigationItem of the view controller that is going to be pushed onto this PropertyViewController class you have created.

That is:

MainViewController *vc = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[infoButton addTarget:self action:@selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
vc.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:infoButton] autorelease];

PropertyViewController *navController = [[PropertyViewController alloc] initWithRootViewController:vc];

Now, this infoButton that has been created programatically will show up in the navigation bar. The idea is that the navigation controller picks up its display information (title, buttons, etc) from the UIViewController that it is about to display. You don't actually add buttons and such directly to the UINavigationController.

Getting request payload from POST request in Java servlet

You only need

request.getParameterMap()

for getting the POST and GET - Parameters.

The Method returns a Map<String,String[]>.

You can read the parameters in the Map by

Map<String, String[]> map = request.getParameterMap();
//Reading the Map
//Works for GET && POST Method
for(String paramName:map.keySet()) {
    String[] paramValues = map.get(paramName);

    //Get Values of Param Name
    for(String valueOfParam:paramValues) {
        //Output the Values
        System.out.println("Value of Param with Name "+paramName+": "+valueOfParam);
    }
}

How can I delete a service in Windows?

You can use my small service list editor utility Service Manager

Preview

You can choose any service > Modify > Delete. Method works immediately, no reboot required.

Executable file: [Download]

Source code: [Download]

Blog post: [BlogLink]

Service editor class: WinServiceUtils.cs

Vim clear last search highlighting

Janus for VIM and GVIM has a number of baked-in things for newbs like me, including

<leader>hs - toggles highlight search

which is exactly what you need. Just type \hs in normal mode. (The leader key is mapped to \ by default.)

HTH.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

I installed System.Configuration.ConfigurationManager from Nuget into my .net core 2.2 application.

I then reference using System.Configuration;

Next, I changed

WebConfigurationManager.AppSettings

to ..

ConfigurationManager.AppSettings

So far I believe this is correct. 4.5.0 is typical with .net core 2.2

I have not had any issues with this.

How to remove a character at the end of each line in unix

You can use sed:

sed 's/,$//' file > file.nocomma

and to remove whatever last character:

sed 's/.$//' file > file.nolast

How to return a value from pthread threads in C?

Question : What is the best practice of returning/storing variables of multiple threads? A global hash table?

This totally depends on what you want to return and how you would use it? If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.

But, if you want some more information which will be used for further processing then you can use global data structure. But, in that case you need to handle concurrency issues by using appropriate synchronization primitives. Or you can allocate some dynamic memory (preferrably for the structure in which you want to store the data) and send it via pthread_exit and once the thread joins, you update it in another global structure. In this way only the one main thread will update the global structure and concurrency issues are resolved. But, you need to make sure to free all the memory allocated by different threads.

Android Calling JavaScript functions in WebView

Modification of @Ilya_Gazman answer

    private void callJavaScript(WebView view, String methodName, Object...params){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("javascript:try{");
        stringBuilder.append(methodName);
        stringBuilder.append("(");
        String separator = "";
        for (Object param : params) {               
            stringBuilder.append(separator);
            separator = ",";
            if(param instanceof String){
                stringBuilder.append("'");
            }
                stringBuilder.append(param.toString().replace("'", "\\'"));
            if(param instanceof String){
                stringBuilder.append("'");
            }

        }
        stringBuilder.append(")}catch(error){console.error(error.message);}");
        final String call = stringBuilder.toString();
        Log.i(TAG, "callJavaScript: call="+call);


        view.loadUrl(call);
    }

will correctly create JS calls e.g.

callJavaScript(mBrowser, "alert", "abc", "def");
//javascript:try{alert('abc','def')}catch(error){console.error(error.message);}
callJavaScript(mBrowser, "alert", 1, true, "abc");
//javascript:try{alert(1,true,'abc')}catch(error){console.error(error.message);}

Note that objects will not be passed correctly - but you can serialize them before passing as an argument.

Also I've changed where the error goes, I've diverted it to the console log which can be listened by:

    webView.setWebChromeClient(new CustomWebChromeClient());

and client

class CustomWebChromeClient extends WebChromeClient {
    private static final String TAG = "CustomWebChromeClient";

    @Override
    public boolean onConsoleMessage(ConsoleMessage cm) {
        Log.d(TAG, String.format("%s @ %d: %s", cm.message(),
                cm.lineNumber(), cm.sourceId()));
        return true;
    }
}

Getting list of items inside div using Selenium Webdriver

You're asking for all the elements of class facetContainerDiv, of which there is only one (your outer-most div). Why not do

List<WebElement> checks =  driver.findElements(By.class("facetCheck"));
// click the 3rd checkbox
checks.get(2).click();

npx command not found

Updating node helped me, whether that be from the command line or just re-downloading it from the web

How to get URL of current page in PHP

The other answers are correct. However, a quick note: if you're looking to grab the stuff after the ? in a URI, you should use the $_GET[] array.

View a file in a different Git branch without changing branches

git show somebranch:path/to/your/file

you can also do multiple files and have them concatenated:

git show branchA~10:fileA branchB^^:fileB

You do not have to provide the full path to the file, relative paths are acceptable e.g.:

git show branchA~10:../src/hello.c

If you want to get the file in the local directory (revert just one file) you can checkout:

git checkout somebranch^^^ -- path/to/file

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>

Conditionally displaying JSF components

In addition to previous post you can have

<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />

Jsf 2.0

Get the cell value of a GridView row

Have you tried Cell[0]? Remember indexes start at 0, not 1.

Quickly create large file on a Windows system

Check out RDFC http://www.bertel.de/software/rdfc/index-en.html

RDFC is probably not the fastest, but it does allocate data blocks. The absolutely fastest would have to use lower level API to just obtain cluster chains and put them into MFT without writing data.

Beware that there's no silver bullet here - if "creation" returns instantly that means you got a sparse file which just fakes a large file, but you won't get data blocks/chains till you write into it. If you just read is you'd get very fast zeros which could make you believe that your drive all of the sudden got blazingly fast :-)

json parsing error syntax error unexpected end of input

Unexpected end of input means that the parser has ended prematurely. For example, it might be expecting "abcd...wxyz" but only sees "abcd...wxy.

This can be a typo error somewhere, or it could be a problem you get when encodings are mixed across different parts of the application.

One example: consider you are receiving data from a native app using chrome.runtime.sendNativeMessage:

chrome.runtime.sendNativeMessage('appname', {toJSON:()=>{return msg}}, (data)=>{
    console.log(data);
});

Now before your callback is called, the browser would attempt to parse the message using JSON.parse which can give you "unexpected end of input" errors if the supplied byte length does not match the data.

Get current application physical path within Application_Start

There's, however, slight difference among all these options which

I found out that

If you do

    string URL = Server.MapPath("~");

or

    string URL = Server.MapPath("/");

or

    string URL = HttpRuntime.AppDomainAppPath;

your URL will display resources in your link like this:

    "file:///d:/InetPUB/HOME/Index/bin/Resources/HandlerDoc.htm"

But if you want your URL to show only virtual path not the resources location, you should do

    string URL = HttpRuntime.AppDomainAppVirtualPath; 

then, your URL is displaying a virtual path to your resources as below

    "http://HOME/Index/bin/Resources/HandlerDoc.htm"        

How to set base url for rest in spring boot?

Try using a PathMatchConfigurer (Spring Boot 2.x):

@Configuration
public class WebMvcConfig implements WebMvcConfigurer  {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix("api", HandlerTypePredicate.forAnnotation(RestController.class));
    }
}

I get conflicting provisioning settings error when I try to archive to submit an iOS app

If you are from Ionic world. You might get a "conflict code signing" error when you in the "archive" stage, as below:

... is automatically signed for development, but a conflicting code signing identity iPhone Distribution has been manually specified. Set the code signing identity value to "iPhone Developer" in the build settings editor, or switch to manual signing in the project editor. Code signing is required for product type 'Application' in SDK 'iOS 10.x'

In this case, please go to Build Settings/under signing, code signing identity, and select both as iOS Developer, not Distribution.

Go to the menu: Product/Archive again, then the issue will be fixed.

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

Just open your sql file with a text editor and search for 'utf8mb4' and replace with utf8.I hope it would work for you

Google map V3 Set Center to specific Marker

geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

How to set a parameter in a HttpServletRequest?

The missing getParameterMap override ended up being a real problem for me. So this is what I ended up with:

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/***
 * Request wrapper enabling the update of a request-parameter.
 * 
 * @author E.K. de Lang
 *
 */
final class HttpServletRequestReplaceParameterWrapper
    extends HttpServletRequestWrapper
{

    private final Map<String, String[]> keyValues;

    @SuppressWarnings("unchecked")
    HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, String key, String value)
    {
        super(request);

        keyValues = new HashMap<String, String[]>();
        keyValues.putAll(request.getParameterMap());
        // Can override the values in the request
        keyValues.put(key, new String[] { value });

    }

    @SuppressWarnings("unchecked")
    HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, Map<String, String> additionalRequestParameters)
    {
        super(request);
        keyValues = new HashMap<String, String[]>();
        keyValues.putAll(request.getParameterMap());
        for (Map.Entry<String, String> entry : additionalRequestParameters.entrySet()) {
            keyValues.put(entry.getKey(), new String[] { entry.getValue() });
        }

    }

    @Override
    public String getParameter(String name)
    {
        if (keyValues.containsKey(name)) {
            String[] strings = keyValues.get(name);
            if (strings == null || strings.length == 0) {
                return null;
            }
            else {
                return strings[0];
            }
        }
        else {
            // Just in case the request has some tricks of it's own.
            return super.getParameter(name);
        }
    }

    @Override
    public String[] getParameterValues(String name)
    {
        String[] value = this.keyValues.get(name);
        if (value == null) {
            // Just in case the request has some tricks of it's own.
            return super.getParameterValues(name);
        }
        else {
            return value;
        }
    }

    @Override
    public Map<String, String[]> getParameterMap()
    {
        return this.keyValues;
    }

}

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Simply follow the code

public static String getFormatedDate(String strDate,StringsourceFormate,
                                     String destinyFormate) {
    SimpleDateFormat df;
    df = new SimpleDateFormat(sourceFormate);
    Date date = null;
    try {
        date = df.parse(strDate);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    df = new SimpleDateFormat(destinyFormate);
    return df.format(date);

}

and pass the value into the function like that,

getFormatedDate("21:30:00", "HH:mm", "hh:mm aa");

or checkout this documentation SimpleDateFormat for StringsourceFormate and destinyFormate.

How to use the 'main' parameter in package.json?

From the npm documentation:

The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.

This should be a module ID relative to the root of your package folder.

For most modules, it makes the most sense to have a main script and often not much else.

To put it short:

  1. You only need a main parameter in your package.json if the entry point to your package differs from index.js in its root folder. For example, people often put the entry point to lib/index.js or lib/<packagename>.js, in this case the corresponding script must be described as main in package.json.
  2. You can't have two scripts as main, simply because the entry point require('yourpackagename') must be defined unambiguously.

Trimming text strings in SQL Server 2008

I would try something like this for a Trim function that takes into account all white-space characters defined by the Unicode Standard (LTRIM and RTRIM do not even trim new-line characters!):

_x000D_
_x000D_
IF OBJECT_ID(N'dbo.IsWhiteSpace', N'FN') IS NOT NULL_x000D_
    DROP FUNCTION dbo.IsWhiteSpace;_x000D_
GO_x000D_
_x000D_
-- Determines whether a single character is white-space or not (according to the UNICODE standard)._x000D_
CREATE FUNCTION dbo.IsWhiteSpace(@c NCHAR(1)) RETURNS BIT_x000D_
BEGIN_x000D_
 IF (@c IS NULL) RETURN NULL;_x000D_
 DECLARE @WHITESPACE NCHAR(31);_x000D_
 SELECT @WHITESPACE = ' ' + NCHAR(13) + NCHAR(10) + NCHAR(9) + NCHAR(11) + NCHAR(12) + NCHAR(133) + NCHAR(160) + NCHAR(5760) + NCHAR(8192) + NCHAR(8193) + NCHAR(8194) + NCHAR(8195) + NCHAR(8196) + NCHAR(8197) + NCHAR(8198) + NCHAR(8199) + NCHAR(8200) + NCHAR(8201) + NCHAR(8202) + NCHAR(8232) + NCHAR(8233) + NCHAR(8239) + NCHAR(8287) + NCHAR(12288) + NCHAR(6158) + NCHAR(8203) + NCHAR(8204) + NCHAR(8205) + NCHAR(8288) + NCHAR(65279);_x000D_
 IF (CHARINDEX(@c, @WHITESPACE) = 0) RETURN 0;_x000D_
 RETURN 1;_x000D_
END_x000D_
GO_x000D_
_x000D_
IF OBJECT_ID(N'dbo.Trim', N'FN') IS NOT NULL_x000D_
    DROP FUNCTION dbo.Trim;_x000D_
GO_x000D_
_x000D_
-- Removes all leading and tailing white-space characters. NULL is converted to an empty string._x000D_
CREATE FUNCTION dbo.Trim(@TEXT NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)_x000D_
BEGIN_x000D_
 -- Check tiny strings (NULL, 0 or 1 chars)_x000D_
 IF @TEXT IS NULL RETURN N'';_x000D_
 DECLARE @TEXTLENGTH INT = LEN(@TEXT);_x000D_
 IF @TEXTLENGTH < 2 BEGIN_x000D_
  IF (@TEXTLENGTH = 0) RETURN @TEXT;_x000D_
  IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1)) = 1) RETURN '';_x000D_
  RETURN @TEXT;_x000D_
 END_x000D_
 -- Check whether we have to LTRIM/RTRIM_x000D_
 DECLARE @SKIPSTART INT;_x000D_
 SELECT @SKIPSTART = dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1));_x000D_
 DECLARE @SKIPEND INT;_x000D_
 SELECT @SKIPEND = dbo.IsWhiteSpace(SUBSTRING(@TEXT, @TEXTLENGTH, 1));_x000D_
 DECLARE @INDEX INT;_x000D_
 IF (@SKIPSTART = 1) BEGIN_x000D_
  IF (@SKIPEND = 1) BEGIN_x000D_
   -- FULLTRIM_x000D_
   -- Determine start white-space length_x000D_
   SELECT @INDEX = 2;_x000D_
   WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise assign index as @SKIPSTART_x000D_
    SELECT @SKIPSTART = @INDEX;_x000D_
    -- Increase character index_x000D_
    SELECT @INDEX = (@INDEX + 1);_x000D_
   END_x000D_
   -- Return '' if the whole string is white-space_x000D_
   IF (@SKIPSTART = (@TEXTLENGTH - 1)) RETURN ''; _x000D_
   -- Determine end white-space length_x000D_
   SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
   WHILE (@INDEX > 1) BEGIN _x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise increase @SKIPEND_x000D_
    SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
    -- Decrease character index_x000D_
    SELECT @INDEX = (@INDEX - 1);_x000D_
   END_x000D_
   -- Return trimmed string_x000D_
   RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART - @SKIPEND);_x000D_
  END _x000D_
  -- LTRIM_x000D_
  -- Determine start white-space length_x000D_
  SELECT @INDEX = 2;_x000D_
  WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
   -- Stop loop if no white-space_x000D_
   IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
   -- Otherwise assign index as @SKIPSTART_x000D_
   SELECT @SKIPSTART = @INDEX;_x000D_
   -- Increase character index_x000D_
   SELECT @INDEX = (@INDEX + 1);_x000D_
  END_x000D_
  -- Return trimmed string_x000D_
  RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART);_x000D_
 END ELSE BEGIN_x000D_
  -- RTRIM_x000D_
  IF (@SKIPEND = 1) BEGIN_x000D_
   -- Determine end white-space length_x000D_
   SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
   WHILE (@INDEX > 1) BEGIN _x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise increase @SKIPEND_x000D_
    SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
    -- Decrease character index_x000D_
    SELECT @INDEX = (@INDEX - 1);_x000D_
   END_x000D_
   -- Return trimmed string_x000D_
   RETURN SUBSTRING(@TEXT, 1, @TEXTLENGTH - @SKIPEND);_x000D_
  END _x000D_
 END_x000D_
 -- NO TRIM_x000D_
 RETURN @TEXT;_x000D_
END_x000D_
GO
_x000D_
_x000D_
_x000D_

illegal character in path

You seem to have the quote marks (") embedded in your string at the start and the end. These are not needed and are illegal characters in a path. How are you initializing the string with the path?

This can be seen from the debugger visualizer, as the string starts with "\" and ends with \"", it shows that the quotes are part of the string, when they shouldn't be.

You can do two thing - a regular escaped string (using \) or a verbatim string literal (that starts with a @):

  string str = "C:\\Program Files (x86)\\test software\\myapp\\demo.exe";

Or:

  string verbatim = @"C:\Program Files (x86)\test software\myapp\demo.exe";

How to give a time delay of less than one second in excel vba?

Public Function CheckWholeNumber(Number As Double) As Boolean
    If Number - Fix(Number) = 0 Then
        CheckWholeNumber = True
    End If
End Function

Public Sub TimeDelay(Days As Double, Hours As Double, Minutes As Double, Seconds As Double)
    If CheckWholeNumber(Days) = False Then
        Hours = Hours + (Days - Fix(Days)) * 24
        Days = Fix(Days)
    End If
    If CheckWholeNumber(Hours) = False Then
        Minutes = Minutes + (Hours - Fix(Hours)) * 60
        Hours = Fix(Hours)
    End If
    If CheckWholeNumber(Minutes) = False Then
        Seconds = Seconds + (Minutes - Fix(Minutes)) * 60
        Minutes = Fix(Minutes)
    End If
    If Seconds >= 60 Then
        Seconds = Seconds - 60
        Minutes = Minutes + 1
    End If
    If Minutes >= 60 Then
        Minutes = Minutes - 60
        Hours = Hours + 1
    End If
    If Hours >= 24 Then
        Hours = Hours - 24
        Days = Days + 1
    End If
    Application.Wait _
    ( _
        Now + _
        TimeSerial(Hours + Days * 24, Minutes, 0) + _
        Seconds * TimeSerial(0, 0, 1) _
    )
End Sub

example:

call TimeDelay(1.9,23.9,59.9,59.9999999)

hopy you enjoy.

edit:

here's one without any additional functions, for people who like it being faster

Public Sub WaitTime(Days As Double, Hours As Double, Minutes As Double, Seconds As Double)
    If Days - Fix(Days) > 0 Then
        Hours = Hours + (Days - Fix(Days)) * 24
        Days = Fix(Days)
    End If
    If Hours - Fix(Hours) > 0 Then
        Minutes = Minutes + (Hours - Fix(Hours)) * 60
        Hours = Fix(Hours)
    End If
    If Minutes - Fix(Minutes) > 0 Then
        Seconds = Seconds + (Minutes - Fix(Minutes)) * 60
        Minutes = Fix(Minutes)
    End If
    If Seconds >= 60 Then
        Seconds = Seconds - 60
        Minutes = Minutes + 1
    End If
    If Minutes >= 60 Then
        Minutes = Minutes - 60
        Hours = Hours + 1
    End If
    If Hours >= 24 Then
        Hours = Hours - 24
        Days = Days + 1
    End If
    Application.Wait _
    ( _
        Now + _
        TimeSerial(Hours + Days * 24, Minutes, 0) + _
        Seconds * TimeSerial(0, 0, 1) _
    )
End Sub

How to get value of Radio Buttons?

To Get the Value when the radio button is checked

if (rdbtnSN06.IsChecked == true)
{
string RadiobuttonContent =Convert.ToString(rdbtnSN06.Content.ToString());
}
else
{
string RadiobuttonContent =Convert.ToString(rdbtnSN07.Content.ToString());
}