Programs & Examples On #Operating system

An operating System (OS) is a basic software whose role is to be an abstract layer between software requisitions for resources and the hardware available, manage input/output, memory allocation/deallocation, file systems, among other basic tasks a device (not necessarily a computer) should do.

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

What is the difference between the kernel space and the user space?

Kernel space and user space is the separation of the privileged operating system functions and the restricted user applications. The separation is necessary to prevent user applications from ransacking your computer. It would be a bad thing if any old user program could start writing random data to your hard drive or read memory from another user program's memory space.

User space programs cannot access system resources directly so access is handled on the program's behalf by the operating system kernel. The user space programs typically make such requests of the operating system through system calls.

Kernel threads, processes, stack do not mean the same thing. They are analogous constructs for kernel space as their counterparts in user space.

Comprehensive methods of viewing memory usage on Solaris

# echo ::memstat | mdb -k
Page Summary                Pages                MB  %Tot
------------     ----------------  ----------------  ----
Kernel                       7308                57   23%
Anon                         9055                70   29%
Exec and libs                1968                15    6%
Page cache                   2224                17    7%
Free (cachelist)             6470                50   20%
Free (freelist)              4641                36   15%

Total                       31666               247
Physical                    31256               244

What languages are Windows, Mac OS X and Linux written in?

The Linux kernel is mostly written in C (and a bit of assembly language, I'd imagine), but some of the important userspace utilities (programs) are shell scripts written in the Bash scripting language. Beyond that, it's sort of hard to define "Linux" since you basically build a Linux system by picking bits and pieces you want and putting them together, and depending on what an individual Linux user wants, you can get pretty much any language involved. (As Paul said, Python and C++ play important roles)

What is the difference between the operating system and the kernel?

The difference between an operating system and a kernel:

The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:

  1. memory management
  2. network management
  3. device driver
  4. file management
  5. process management

How to run regasm.exe from command line other than Visual Studio command prompt?

Execute only 1 of the below
Once a command works, skip the rest/ below to it:

Normal:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe myTest.dll
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe myTest.dll /tlb:myTest.tlb
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe myTest.dll /tlb:myTest.tlb /codebase

Only if you face issues, use old version 'v2.0.50727':

%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe myTest.dll
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe myTest.dll /tlb:myTest.tlb
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe myTest.dll /tlb:myTest.tlb 

Only if you built myTest.dll for 64bit Only, use 'Framework64' path:

%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe myTest.dll
%SystemRoot%\Microsoft.NET\Framework64\v2.0.50727\RegAsm.exe myTest.dll

Note: 64-bit built dlls will not work on 32-bit platform.

All options:

See https://docs.microsoft.com/en-us/dotnet/framework/tools/regasm-exe-assembly-registration-tool

Context.startForegroundService() did not then call Service.startForeground()

One issue might be Service class is not enabled in AndroidManifest file. Please check it as well.

<service
        android:name=".AudioRecorderService"
        android:enabled="true"
        android:exported="false"
        android:foregroundServiceType="microphone" />

What is private bytes, virtual bytes, working set?

The definition of the perfmon counters has been broken since the beginning and for some reason appears to be too hard to correct.

A good overview of Windows memory management is available in the video "Mysteries of Memory Management Revealed" on MSDN: It covers more topics than needed to track memory leaks (eg working set management) but gives enough detail in the relevant topics.


To give you a hint of the problem with the perfmon counter descriptions, here is the inside story about private bytes from "Private Bytes Performance Counter -- Beware!" on MSDN:

Q: When is a Private Byte not a Private Byte?

A: When it isn't resident.

The Private Bytes counter reports the commit charge of the process. That is to say, the amount of space that has been allocated in the swap file to hold the contents of the private memory in the event that it is swapped out. Note: I'm avoiding the word "reserved" because of possible confusion with virtual memory in the reserved state which is not committed.


From "Performance Planning" on MSDN:

3.3 Private Bytes

3.3.1 Description

Private memory, is defined as memory allocated for a process which cannot be shared by other processes. This memory is more expensive than shared memory when multiple such processes execute on a machine. Private memory in (traditional) unmanaged dlls usually constitutes of C++ statics and is of the order of 5% of the total working set of the dll.

What is the difference between a process and a thread?

For those who are more comfortable with learning by visualizing, here is a handy diagram I created to explain Process and Threads.
I used the information from MSDN - About Processes and Threads

Processes and Threads

What are file descriptors, explained in simple terms?

More points regarding File Descriptor:

  1. File Descriptors (FD) are non-negative integers (0, 1, 2, ...) that are associated with files that are opened.

  2. 0, 1, 2 are standard FD's that corresponds to STDIN_FILENO, STDOUT_FILENO and STDERR_FILENO (defined in unistd.h) opened by default on behalf of shell when the program starts.

  3. FD's are allocated in the sequential order, meaning the lowest possible unallocated integer value.

  4. FD's for a particular process can be seen in /proc/$pid/fd (on Unix based systems).

What resources are shared between threads?

In an x86 framework, one can divide as many segments (up to 2^16-1). The ASM directives SEGMENT/ENDS allows this, and the operators SEG and OFFSET allows initialization of segment registers. CS:IP are usually initialized by the loader, but for DS, ES, SS the application is responsible with initialization. Many environments allow the so-called "simplified segment definitions" like .code, .data, .bss, .stack etc. and, depending also on the "memory model" (small, large, compact etc.) the loader initializes segment registers accordingly. Usually .data, .bss, .stack and other usual segments (I haven't done this since 20 years so I don't remember all) are grouped in one single group - that is why usually DS, ES and SS points to teh same area, but this is only to simplify things.

In general, all segment registers can have different values upon run-time. So, the interview question was right: which one of the CODE, DATA, and STACK are shared between threads. Heap management is something else - it is simply a sequence of calls to the OS. But what if you don't have an OS at all, like in an embedded system - can you still have new/delete in your code?

My advice to the young people - read some good assembly programming book. It seems that university curriculae are quite poor in this respect.

What is an OS kernel ? How does it differ from an operating system?

a kernel is part of the operating system, it is the first thing that the boot loader loads onto the cpu (for most operating systems), it is the part that interfaces with the hardware, and it also manages what programs can do what with the hardware, it is really the central part of the os, it is made up of drivers, a driver is a program that interfaces with a particular piece of hardware, for example: if I made a digital camera for computers, I would need to make a driver for it, the drivers are the only programs that can control the input and output of the computer

How can I safely create a nested directory?

I would personally recommend that you use os.path.isdir() to test instead of os.path.exists().

>>> os.path.exists('/tmp/dirname')
True
>>> os.path.exists('/tmp/dirname/filename.etc')
True
>>> os.path.isdir('/tmp/dirname/filename.etc')
False
>>> os.path.isdir('/tmp/fakedirname')
False

If you have:

>>> dir = raw_input(":: ")

And a foolish user input:

:: /tmp/dirname/filename.etc

... You're going to end up with a directory named filename.etc when you pass that argument to os.makedirs() if you test with os.path.exists().

How do I check OS with a preprocessor directive?

#ifdef _WIN32
// do something for windows like include <windows.h>
#elif defined __unix__
// do something for unix like include <unistd.h>
#elif defined __APPLE__
// do something for mac
#endif

Get operating system info

When you go to a website, your browser sends a request to the web server including a lot of information. This information might look something like this:

GET /questions/18070154/get-operating-system-info-with-php HTTP/1.1  
Host: stackoverflow.com  
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 
            (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  
Accept-Language: en-us,en;q=0.5  
Accept-Encoding: gzip,deflate,sdch  
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7  
Keep-Alive: 300  
Connection: keep-alive  
Cookie: <cookie data removed> 
Pragma: no-cache  
Cache-Control: no-cache

These information are all used by the web server to determine how to handle the request; the preferred language and whether compression is allowed.

In PHP, all this information is stored in the $_SERVER array. To see what you're sending to a web server, create a new PHP file and print out everything from the array.

<pre><?php print_r($_SERVER); ?></pre>

This will give you a nice representation of everything that's being sent to the server, from where you can extract the desired information, e.g. $_SERVER['HTTP_USER_AGENT'] to get the operating system and browser.

Fork() function in C

int a = fork(); 

Creates a duplicate process "clone?", which shares the execution stack. The difference between the parent and the child is the return value of the function.

The child getting 0 returned, and the parent getting the new pid.

Each time the addresses and the values of the stack variables are copied. The execution continues at the point it already got to in the code.

At each fork, only one value is modified - the return value from fork.

How to detect my browser version and operating system using JavaScript?

Detecting browser's details:

var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName  = navigator.appName;
var fullVersion  = ''+parseFloat(navigator.appVersion); 
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome" 
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version" 
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox" 
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent 
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < 
          (verOffset=nAgt.lastIndexOf('/')) ) 
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
   fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
   fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion); 
 majorVersion = parseInt(navigator.appVersion,10);
}

document.write(''
 +'Browser name  = '+browserName+'<br>'
 +'Full version  = '+fullVersion+'<br>'
 +'Major version = '+majorVersion+'<br>'
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br>'
)

Source JavaScript: browser name.
See JSFiddle to detect Browser Details.

Detecting OS:

// This script sets OSName variable as follows:
// "Windows"    for all versions of Windows
// "MacOS"      for all versions of Macintosh OS
// "Linux"      for all versions of Linux
// "UNIX"       for all other UNIX flavors 
// "Unknown OS" indicates failure to detect the OS

var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

document.write('Your OS: '+OSName);

source JavaScript: OS detection.
See JSFiddle to detect OS Details.

_x000D_
_x000D_
    var nVer = navigator.appVersion;_x000D_
    var nAgt = navigator.userAgent;_x000D_
    var browserName  = navigator.appName;_x000D_
    var fullVersion  = ''+parseFloat(navigator.appVersion); _x000D_
    var majorVersion = parseInt(navigator.appVersion,10);_x000D_
    var nameOffset,verOffset,ix;_x000D_
    _x000D_
    // In Opera, the true version is after "Opera" or after "Version"_x000D_
    if ((verOffset=nAgt.indexOf("Opera"))!=-1) {_x000D_
     browserName = "Opera";_x000D_
     fullVersion = nAgt.substring(verOffset+6);_x000D_
     if ((verOffset=nAgt.indexOf("Version"))!=-1) _x000D_
       fullVersion = nAgt.substring(verOffset+8);_x000D_
    }_x000D_
    // In MSIE, the true version is after "MSIE" in userAgent_x000D_
    else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {_x000D_
     browserName = "Microsoft Internet Explorer";_x000D_
     fullVersion = nAgt.substring(verOffset+5);_x000D_
    }_x000D_
    // In Chrome, the true version is after "Chrome" _x000D_
    else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {_x000D_
     browserName = "Chrome";_x000D_
     fullVersion = nAgt.substring(verOffset+7);_x000D_
    }_x000D_
    // In Safari, the true version is after "Safari" or after "Version" _x000D_
    else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {_x000D_
     browserName = "Safari";_x000D_
     fullVersion = nAgt.substring(verOffset+7);_x000D_
     if ((verOffset=nAgt.indexOf("Version"))!=-1) _x000D_
       fullVersion = nAgt.substring(verOffset+8);_x000D_
    }_x000D_
    // In Firefox, the true version is after "Firefox" _x000D_
    else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {_x000D_
     browserName = "Firefox";_x000D_
     fullVersion = nAgt.substring(verOffset+8);_x000D_
    }_x000D_
    // In most other browsers, "name/version" is at the end of userAgent _x000D_
    else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < _x000D_
              (verOffset=nAgt.lastIndexOf('/')) ) _x000D_
    {_x000D_
     browserName = nAgt.substring(nameOffset,verOffset);_x000D_
     fullVersion = nAgt.substring(verOffset+1);_x000D_
     if (browserName.toLowerCase()==browserName.toUpperCase()) {_x000D_
      browserName = navigator.appName;_x000D_
     }_x000D_
    }_x000D_
    // trim the fullVersion string at semicolon/space if present_x000D_
    if ((ix=fullVersion.indexOf(";"))!=-1)_x000D_
       fullVersion=fullVersion.substring(0,ix);_x000D_
    if ((ix=fullVersion.indexOf(" "))!=-1)_x000D_
       fullVersion=fullVersion.substring(0,ix);_x000D_
    _x000D_
    majorVersion = parseInt(''+fullVersion,10);_x000D_
    if (isNaN(majorVersion)) {_x000D_
     fullVersion  = ''+parseFloat(navigator.appVersion); _x000D_
     majorVersion = parseInt(navigator.appVersion,10);_x000D_
    }_x000D_
    _x000D_
    document.write(''_x000D_
     +'Browser name  = '+browserName+'<br>'_x000D_
     +'Full version  = '+fullVersion+'<br>'_x000D_
     +'Major version = '+majorVersion+'<br>'_x000D_
     +'navigator.appName = '+navigator.appName+'<br>'_x000D_
     +'navigator.userAgent = '+navigator.userAgent+'<br>'_x000D_
    )_x000D_
_x000D_
    // This script sets OSName variable as follows:_x000D_
    // "Windows"    for all versions of Windows_x000D_
    // "MacOS"      for all versions of Macintosh OS_x000D_
    // "Linux"      for all versions of Linux_x000D_
    // "UNIX"       for all other UNIX flavors _x000D_
    // "Unknown OS" indicates failure to detect the OS_x000D_
    _x000D_
    var OSName="Unknown OS";_x000D_
    if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";_x000D_
    if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";_x000D_
    if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";_x000D_
    if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";_x000D_
    _x000D_
    document.write('Your OS: '+OSName);
_x000D_
_x000D_
_x000D_

How to run a program without an operating system?

Operating System as the inspiration

The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).

For example, this page can be used as a starting point:

How to write a simple operating system

Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!

Such or similar simple OS can be used to create a simple framework that will allow us:

make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.

There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.

Boot Loader as the inspiration

Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:

How to develop your own Boot Loader

The above article presents also the basic architecture of such a programs:

  1. Correct loading to the memory by 0000:7C00 address.
  2. Calling the BootMain function that is developed in the high-level language.
  3. Show “”Hello, world…”, from low-level” message on the display.

As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.

In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:

to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.

The article shows also how to see the created program in action and how to perform its testing and debug.

UEFI applications as the inspiration

The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:

Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.

A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.

If we would like to start creating such programs, we can, for example, start with these websites:

Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps

Exploring security issues as the inspiration

It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.

A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:

There are at least four known BIOS attack viruses, two of which were for demonstration purposes.

or perhaps another one too.

Attacks before system startup

Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.

Different ways to boot

I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:

What Is Network Booting (PXE) and How Can You Use It?

How do I check the operating system in Python?

If you want to know on which platform you are on out of "Linux", "Windows", or "Darwin" (Mac), without more precision, you should use:

>>> import platform
>>> platform.system()
'Linux'  # or 'Windows'/'Darwin'

The platform.system function uses uname internally.

How to find the operating system version using JavaScript?

If you list all of window.navigator's properties using

_x000D_
_x000D_
console.log(navigator);
_x000D_
_x000D_
_x000D_

You'll see something like this

# platform = Win32
# appCodeName = Mozilla
# appName = Netscape
# appVersion = 5.0 (Windows; en-US)
# language = en-US
# mimeTypes = [object MimeTypeArray]
# oscpu = Windows NT 5.1
# vendor = Firefox
# vendorSub = 1.0.7
# product = Gecko
# productSub = 20050915
# plugins = [object PluginArray]
# securityPolicy =
# userAgent = Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7
# cookieEnabled = true
# javaEnabled = function javaEnabled() { [native code] }
# taintEnabled = function taintEnabled() { [native code] }
# preference = function preference() { [native code] }

Note that oscpu attribute gives you the Windows version. Also, you should know that:

'Windows 3.11' => 'Win16',
'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)',
'Windows 98' => '(Windows 98)|(Win98)',
'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)',
'Windows XP' => '(Windows NT 5.1)|(Windows XP)',
'Windows Server 2003' => '(Windows NT 5.2)',
'Windows Vista' => '(Windows NT 6.0)',
'Windows 7' => '(Windows NT 6.1)',
'Windows 8' => '(Windows NT 6.2)|(WOW64)',
'Windows 10' => '(Windows 10.0)|(Windows NT 10.0)',
'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)',
'Windows ME' => 'Windows ME',
'Open BSD' => 'OpenBSD',
'Sun OS' => 'SunOS',
'Linux' => '(Linux)|(X11)',
'Mac OS' => '(Mac_PowerPC)|(Macintosh)',
'QNX' => 'QNX',
'BeOS' => 'BeOS',
'OS/2' => 'OS/2',
'Search Bot'=>'(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves/Teoma)|(ia_archiver)'

How to make parent wait for all child processes to finish?

pid_t child_pid, wpid;
int status = 0;

//Father code (before child processes start)

for (int id=0; id<n; id++) {
    if ((child_pid = fork()) == 0) {
        //child code
        exit(0);
    }
}

while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes 

//Father code (After all child processes end)

wait waits for a child process to terminate, and returns that child process's pid. On error (eg when there are no child processes), -1 is returned. So, basically, the code keeps waiting for child processes to finish, until the waiting errors out, and then you know they are all finished.

Difference between binary semaphore and mutex

Mutex are used for " Locking Mechanisms ". one process at a time can use a shared resource

whereas

Semaphores are used for " Signaling Mechanisms " like "I am done , now can continue"

DNS caching in linux

Here are two other software packages which can be used for DNS caching on Linux:

  • dnsmasq
  • bind

After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.

If your system is using NetworkManager you can either try using the dns=dnsmasq option in /etc/NetworkManager/NetworkManager.conf or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.

What is the difference between user and kernel modes in operating systems?

  1. Kernel Mode

    In Kernel mode, the executing code has complete and unrestricted access to the underlying hardware. It can execute any CPU instruction and reference any memory address. Kernel mode is generally reserved for the lowest-level, most trusted functions of the operating system. Crashes in kernel mode are catastrophic; they will halt the entire PC.

  2. User Mode

    In User mode, the executing code has no ability to directly access hardware or reference memory. Code running in user mode must delegate to system APIs to access hardware or memory. Due to the protection afforded by this sort of isolation, crashes in user mode are always recoverable. Most of the code running on your computer will execute in user mode.

Read more

Understanding User and Kernel Mode

How do I programmatically determine operating system in Java?

I think following can give broader coverage in fewer lines

import org.apache.commons.exec.OS;

if (OS.isFamilyWindows()){
                //load some property
            }
else if (OS.isFamilyUnix()){
                //load some other property
            }

More details here: https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/OS.html

What is the return value of os.system() in Python?

Based on the answer of @AlokThakur (thanks!):

def run_system_command(command):
    return_value = os.system(command)
    # Calculate the return value code
    return_value = int(bin(return_value).replace("0b", "").rjust(16, '0')[:8], 2)
    if return_value != 0:
        raise RuntimeError(f'The system command\n{command}\nexited with return code {return_value}')

Get Windows version in a batch file

These one-line commands have been tested on Windows XP, Server 2012, 7 and 10 (thank you Mad Tom Vane).

Extract version x.y in a cmd console

for /f "tokens=4-7 delims=[.] " %i in ('ver') do @(if %i==Version (echo %j.%k) else (echo %i.%j))

Extract the full version x.y.z

for /f "tokens=4-7 delims=[.] " %i in ('ver') do @(if %i==Version (echo %j.%k.%l) else (echo %i.%j.%k))

In a batch script use %% instead of single %

@echo off
for /f "tokens=4-7 delims=[.] " %%i in ('ver') do (if %%i==Version (set v=%%j.%%k) else (set v=%%i.%%j))
echo %v%

Version is not always consistent to brand name number

Be aware that the extracted version number does not always corresponds to the Windows name release. See below an extract from the full list of Microsoft Windows versions.

10.0   Windows 10
6.3   Windows Server 2012
6.3   Windows 8.1   /!\
6.2   Windows 8   /!\
6.1   Windows 7   /!\
6.0   Windows Vista
5.2   Windows XP x64
5.1   Windows XP
5.0   Windows 2000
4.10   Windows 98

Please also up-vote answers from Agent Gibbs and peterbh as my answer is inspired from their ideas.

How do I check CPU and Memory Usage in Java?

If you are using the Sun JVM, and are interested in the internal memory usage of the application (how much out of the allocated memory your app is using) I prefer to turn on the JVMs built-in garbage collection logging. You simply add -verbose:gc to the startup command.

From the Sun documentation:

The command line argument -verbose:gc prints information at every collection. Note that the format of the -verbose:gc output is subject to change between releases of the J2SE platform. For example, here is output from a large server application:

[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]

Here we see two minor collections and one major one. The numbers before and after the arrow

325407K->83000K (in the first line)

indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the count includes objects that aren't necessarily alive but can't be reclaimed, either because they are directly alive, or because they are within or referenced from the tenured generation. The number in parenthesis

(776768K) (in the first line)

is the total available space, not counting the space in the permanent generation, which is the total heap minus one of the survivor spaces. The minor collection took about a quarter of a second.

0.2300771 secs (in the first line)

For more info see: http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html

Running windows shell commands with python

import subprocess
result = []
win_cmd = 'ipconfig'(curr_user,filename,ip_address)
process = subprocess.Popen(win_cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE )
for line in process.stdout:
    print line
result.append(line)
errcode = process.returncode
for line in result:
    print line

Find Process Name by its Process ID

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET /a pid=1600
FOR /f "skip=3delims=" %%a IN ('tasklist') DO (
 SET "found=%%a"
 SET /a foundpid=!found:~26,8!
 IF %pid%==!foundpid! echo found %pid%=!found:~0,24%!
)

GOTO :EOF

...set PID to suit your circumstance.

What are some resources for getting started in operating system development?

Minix is a lot smaller, and designed for learning purposes, and the book to go with it is a good one too.

Update: I guess Minix 3 is a bit of a different goal, but Minix 2 (and of course the first version) were for teaching purposes.

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

How to uninstall a windows service and delete its files without rebooting

(so Windows releases it's hold on the file)

Instead, do Ctrl+Alt+Del right after the Stop of the service and kill the .exe of the service. Than, you can uninstall the service without rebooting. This happened to me in the past and it solves the part that you need to reboot.

How is TeamViewer so fast?

The most fundamental thing here probably is that you don't want to transmit static images but only changes to the images, which essentially is analogous to video stream.

My best guess is some very efficient (and heavily specialized and optimized) motion compensation algorithm, because most of the actual change in generic desktop usage is linear movement of elements (scrolling text, moving windows, etc. opposed to transformation of elements).

The DirectX 3D performance of 1 FPS seems to confirm my guess to some extent.

What is the difference between Trap and Interrupt?

Traps and interrupts are closely related. Traps are a type of exception, and exceptions are similar to interrupts.

Intel x86 defines two overlapping categories, vectored events (interrupts vs exceptions), and exception classes (faults vs traps vs aborts).

All of the quotes in this post are from the April 2016 version of the Intel Software Developer Manual. For the (definitive and complex) x86 perspective, I recommend reading the SDM's chapter on Interrupt and Exception handling.

Vectored Events

Vectored Events (interrupts and exceptions) cause the processor to jump into an interrupt handler after saving much of the processor's state (enough such that execution can continue from that point later).

Exceptions and interrupts have an ID, called a vector, that determines which interrupt handler the processor jumps to. Interrupt handlers are described within the Interrupt Descriptor Table.

Interrupts

Interrupts occur at random times during the execution of a program, in response to signals from hardware. System hardware uses interrupts to handle events external to the processor, such as requests to service peripheral devices. Software can also generate interrupts by executing the INT n instruction.

Exceptions

Exceptions occur when the processor detects an error condition while executing an instruction, such as division by zero. The processor detects a variety of error conditions including protection violations, page faults, and internal machine faults.

Exception Classifications

Exceptions are classified as faults, traps, or aborts depending on the way they are reported and whether the instruction that caused the exception can be restarted without loss of program or task continuity.

Summary: traps increment the instruction pointer, faults do not, and aborts 'explode'.

Trap

A trap is an exception that is reported immediately following the execution of the trapping instruction. Traps allow execution of a program or task to be continued without loss of program continuity. The return address for the trap handler points to the instruction to be executed after the trapping instruction.

Fault

A fault is an exception that can generally be corrected and that, once corrected, allows the program to be restarted with no loss of continuity. When a fault is reported, the processor restores the machine state to the state prior to the beginning of execution of the faulting instruction. The return address (saved contents of the CS and EIP registers) for the fault handler points to the faulting instruction, rather than to the instruction following the faulting instruction.

Example: A page fault is often recoverable. A piece of an application's address space may have been swapped out to disk from ram. The application will trigger a page fault when it tries to access memory that was swapped out. The kernel can pull that memory from disk to ram, and hand control back to the application. The application will continue where it left off (at the faulting instruction that was accessing swapped out memory), but this time the memory access should succeed without faulting.

An illegal-instruction fault handler that emulates floating-point or other missing instructions would have to manually increment the return address to get the trap-like behaviour it needs, after seeing if the faulting instruction was one it could handle. x86 #UD is a "fault", not a "trap". (The handler would need a pointer to the faulting instruction to figure out which instruction it was.)

Abort

An abort is an exception that does not always report the precise location of the instruction causing the exception and does not allow a restart of the program or task that caused the exception. Aborts are used to report severe errors, such as hardware errors and inconsistent or illegal values in system tables.

Edge Cases

Software invoked interrupts (triggered by the INT instruction) behave in a trap-like manner. The instruction completes before the processor saves its state and jumps to the interrupt handler.

python: get directory two levels up

For getting the directory 2 levels up:

 import os.path as path
 two_up = path.abspath(path.join(os.getcwd(),"../.."))

Best way to find os name and version in Unix/Linux platform

Following command worked out for me nicely. It gives you the OS name and version.

lsb_release -a

What is the difference between user variables and system variables?

Right-click My Computer and go to Properties->Advanced->Environmental Variables...

What's above are user variables, and below are system variables. The elements are combined when creating the environment for an application. System variables are shared for all users, but user variables are only for your account/profile.

If you deleted the system ones by accident, bring up the Registry Editor, then go to HKLM\ControlSet002\Control\Session Manager\Environment (assuming your current control set is not ControlSet002). Then find the Path value and copy the data into the Path value of HKLM\CurrentControlSet\Control\Session Manager\Environment. You might need to reboot the computer. (Hopefully, these backups weren't from too long ago, and they contain the info you need.)

Difference between multitasking, multithreading and multiprocessing?

Multiprogramming:- in which execution of multiple jobs by the same computer not at the same time.

Multitasking :- o/s in which more than one task are executed at the same time.

Detect Windows version in .net

This is a relatively old question but I've recently had to solve this problem and didn't see my solution posted anywhere.

The easiest (and simplest way in my opinion) is to just use a pinvoke call to RtlGetVersion

[DllImport("ntdll.dll", SetLastError = true)]
internal static extern uint RtlGetVersion(out Structures.OsVersionInfo versionInformation); // return type should be the NtStatus enum

[StructLayout(LayoutKind.Sequential)]
internal struct OsVersionInfo
{
    private readonly uint OsVersionInfoSize;

    internal readonly uint MajorVersion;
    internal readonly uint MinorVersion;

    private readonly uint BuildNumber;

    private readonly uint PlatformId;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    private readonly string CSDVersion;
}

Where Major and Minor version numbers in this struct correspond to the values in the table of the accepted answer.

This returns the correct Windows version number unlike the deprecated GetVersion & GetVersionEx functions from kernel32

How can I check for IsPostBack in JavaScript?

Create a global variable in and apply the value

<script>
       var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
</script>

Then you can reference it from elsewhere

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

called_from must be null. Add a test against that condition like

if (called_from != null && called_from.equalsIgnoreCase("add")) {

or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)

if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null

Disabling same-origin policy in Safari

If you want to disable the same-origin policy on Safari (I have 9.1.1), then you only need to enable the developer menu, and select "Disable Cross-Origin Restrictions" from the develop menu.

list.clear() vs list = new ArrayList<Integer>();

Tried the below program , With both the approach. 1. With clearing the arraylist obj in for loop 2. creating new New Arraylist in for loop.

List al= new ArrayList();
        for(int i=0;i<100;i++)
        {
            //List al= new ArrayList();

            for(int j=0;j<10;j++)
            {
                al.add(Integer.parseInt("" +j+i));
                //System.out.println("Obj val " +al.get(j));
            }
            //System.out.println("Hashcode : " + al.hashCode());
            al.clear();

        }

and to my surprise. the memory allocation didnt change much.

With New Arraylist approach.

Before loop total free memory: 64,909 ::

After loop total free memory: 64,775 ::

with Clear approach,

Before loop total free memory: 64,909 :: After loop total free memory: 64,765 ::

So this says there is not much difference in using arraylist.clear from memory utilization perspective.

C++ String Declaring

In C++ you can declare a string like this:

#include <string>

using namespace std;

int main()
{
    string str1("argue2000"); //define a string and Initialize str1 with "argue2000"    
    string str2 = "argue2000"; // define a string and assign str2 with "argue2000"
    string str3;  //just declare a string, it has no value
    return 1;
}

Add timer to a Windows Forms application

Bit more detail:

    private void Form1_Load(object sender, EventArgs e)
    {
        Timer MyTimer = new Timer();
        MyTimer.Interval = (45 * 60 * 1000); // 45 mins
        MyTimer.Tick += new EventHandler(MyTimer_Tick);
        MyTimer.Start();
    }

    private void MyTimer_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("The form will now be closed.", "Time Elapsed");
        this.Close();
    }

Is it possible to disable the network in iOS Simulator?

If you have at least 2 wifi networks to connect is a very simple way is to use a bug in iOS simulator:

  1. quit from simulator (cmd-q) if it is open
  2. connect your Mac to one wifi (it may be not connected to internet, no matters)
  3. launch simulator (menu: xCode->Open Developer Tool->iOs Simulator) and wait while it is loaded
  4. switch wifi network to other one
  5. profit

The bug is that simulator tries to use a network (IP?) which is not connected already.

Until you relaunched simulator- it will have no internet (even if that first wifi network you connected had internet connection), so you can run (cmd-R) and stop (cmd-.) project(s) to use simulator without connection, but your Mac will be connected.

Then, if you'll need to run simulator connected- just quit and launch it.

Configure hibernate to connect to database via JNDI Datasource

Tomcat-7 JNDI configuration:

Steps:

  1. Open the server.xml in the tomcat-dir/conf
  2. Add below <Resource> tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
          global="jdbc/mydb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/test"
          username="root"
          password=""
          maxActive="10"
          maxIdle="10"
          minIdle="5"
          maxWait="10000"/>
  1. Save the server.xml file
  2. Open the context.xml in the tomcat-dir/conf
  3. Add the below <ResourceLink> inside the <Context> tag.
<ResourceLink name="jdbc/mydb" 
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource" />
  1. Save the context.xml
  2. Open the hibernate-cfg.xml file and add and remove below properties.
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>

Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
  1. Save the file and put latest .WAR file in tomcat.
  2. Restart the tomcat. the DB connection will work.

Unable to resolve host "<URL here>" No address associated with host name

If you are running the app on an emulator, make sure that it is properly connected to the internet. If it is not, the easiest way of solving it is reopening the emulator or creating a new device.

How do you create a Distinct query in HQL

do something like this next time

 Criteria crit = (Criteria) session.
                  createCriteria(SomeClass.class).
                  setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

 List claz = crit.list();

How do I kill this tomcat process in Terminal?

In tomcat/bin/catalina.sh

add the following line after just after the comment section ends:

CATALINA_PID=someFile.txt

then, to kill a running instance of Tomcat, you can use:

kill -9 `cat someFile.txt`

From Arraylist to Array

ArrayList<String> a = new ArrayList<String>();
a.add( "test" );
@SuppressWarnings( "unused")
Object[] array = a.toArray();

It depends on what you want to achieve if you need to manipulate the array later it would cost more effort than keeping the string in the ArrayList. You have also random access with an ArrayList by list.get( index );

Crystal Reports 13 And Asp.Net 3.5

I had faced the same issue because of some dll files were missing from References of VS13. I went to the location http://scn.sap.com/docs/DOC-7824 and installed the newest pack. It resolved the issue.

How do I move a table into a schema in T-SQL

ALTER SCHEMA TargetSchema 
    TRANSFER SourceSchema.TableName;

If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable stored procedure:

exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"

Ref.: ALTER SCHEMA

SQL 2008: How do I change db schema to dbo

How do I create test and train samples from one dataframe with pandas?

Just select range row from df like this

row_count = df.shape[0]
split_point = int(row_count*1/5)
test_data, train_data = df[:split_point], df[split_point:]

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

An implementation of the fast Fourier transform (FFT) in C#

The Numerical Recipes website (http://www.nr.com/) has an FFT if you don't mind typing it in. I am working on a project converting a Labview program to C# 2008, .NET 3.5 to acquire data and then look at the frequency spectrum. Unfortunately the Math.Net uses the latest .NET framework, so I couldn't use that FFT. I tried the Exocortex one - it worked but the results to match the Labview results and I don't know enough FFT theory to know what is causing the problem. So I tried the FFT on the numerical recipes website and it worked! I was also able to program the Labview low sidelobe window (and had to introduce a scaling factor).

You can read the chapter of the Numerical Recipes book as a guest on thier site, but the book is so useful that I highly recomend purchasing it. Even if you do end up using the Math.NET FFT.

How to save a git commit message from windows cmd?

If you enter git commit but omit to enter a comment using the –m parameter, then Git will open up the default editor for you to edit your check-in note. By default that is Vim. Now you can do two things:

Alternative 1 – Exit Vim without entering any comment and repeat

A blank or unsaved comment will be counted as an aborted attempt to commit your changes and you can exit Vim by following these steps:

  1. Press Esc to make sure you are not in edit mode (you can press Esc several times if you are uncertain)

  2. Type :q! enter
    (that is, colon, letter q, exclamation mark, enter), this tells Vim to discard any changes and exit)
    Git will then respond:

    Aborting commit due to empty commit message

    and you are once again free to commit using:

    git commit –m "your comment here"
    

Alternative 2 – Use Vim to write a comment

Follow the following steps to use Vim for writing your comments

  1. Press i to enter Edit Mode (or Insert Mode).
    That will leave you with a blinking cursor on the first line. Add your comment. Press Esc to make sure you are not in edit mode (you can press Esc several time if you are uncertain)
  2. Type :wq enter
    (that is colon, letter w, letter q, enter), this will tell Vim to save changes and exit)

Response from https://blogs.msdn.microsoft.com/kristol/2013/07/02/the-git-command-line-101-for-windows-users/

How do I resize an image using PIL and maintain its aspect ratio?

Open your image file

from PIL import Image
im = Image.open("image.png")

Use PIL Image.resize(size, resample=0) method, where you substitute (width, height) of your image for the size 2-tuple.

This will display your image at original size:

display(im.resize((int(im.size[0]),int(im.size[1])), 0) )

This will display your image at 1/2 the size:

display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )

This will display your image at 1/3 the size:

display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )

This will display your image at 1/4 the size:

display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )

etc etc

Entity Framework 6 Code first Default value

In .NET Core 3.1 you can do the following in the model class:

    public bool? Active { get; set; } 

In the DbContext OnModelCreating you add the default value.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Foundation>()
            .Property(b => b.Active)
            .HasDefaultValueSql("1");

        base.OnModelCreating(modelBuilder);
    }

Resulting in the following in the database

enter image description here

Note: If you don't have nullable (bool?) for you property you will get the following warning

The 'bool' property 'Active' on entity type 'Foundation' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type. Consider using the nullable 'bool?' type instead so that the default will only be used for inserts when the property value is 'null'.

Difference between Encapsulation and Abstraction

Abstraction: what are the minimum functions and variables that should be exposed to the outside of our class.

Encapsulation: how to achieve this requirement, meaning how to implement it.

How to remove entry from $PATH on mac

Close the terminal(End the current session). Open it again.

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

If you are not behind any proxy and still getting connection timeout error, please check firewall settings/ antivirus. Sometimes firewall may block the connectivity from any tool (like Eclipse/STS etc..)

How to copy Java Collections list

private List<Item> cloneItemList(final List<Item> items)
    {
        Item[] itemArray = new Item[items.size()];
        itemArray = items.toArray(itemArray);
        return Arrays.asList(itemArray);
    }

Can I mask an input text in a bat file?

You may use ReadFormattedLine subroutine for all kind of formatted input. For example, the command below read a password of 8 characters, display asterisks in the screen, and continue automatically with no need to press Enter:

call :ReadFormattedLine password="********" /M "Enter password (8 chars): "

This subroutine is written in pure Batch so it does not require any additional program, and it allows several formatted input operations, like read just numbers, convert letters to uppercase, etc. You may download ReadFormattedLine subroutine from Read a line with specific format.


EDIT 2018-08-18: New method to enter an "invisible" password

The FINDSTR command have a strange bug that happen when this command is used to show characters in color AND the output of such a command is redirected to CON device. For details on how use FINDSTR command to show text in color, see this topic.

When the output of this form of FINDSTR command is redirected to CON, something strange happens after the text is output in the desired color: all the text after it is output as "invisible" characters, although a more precise description is that the text is output as black text over black background. The original text will appear if you use COLOR command to reset the foreground and background colors of the entire screen. However, when the text is "invisible" we could execute a SET /P command, so all characters entered will not appear on the screen.

@echo off
setlocal

set /P "=_" < NUL > "Enter password"
findstr /A:1E /V "^$" "Enter password" NUL > CON
del "Enter password"
set /P "password="
cls
color 07
echo The password read is: "%password%"

CSS centred header image

you don't need to set the width of header in css, just put the background image as center using this code:

background: url("images/logo.png") no-repeat top center;

or you can just use img tag and put align="center" in the div

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:

Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:

var foomodule = require('foo');
// do something with fooModule

What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...

var module = require(path); // Call RequireJS require

...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;

var moduleName = 'foo';
require([moduleName], function(fooModule){
    // do something with fooModule
})

Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:

define(['dyn_modules'], function (dynModules) {
    require(dynModules, function(){
        // use arguments since you don't know how many modules you're getting in the callback
        for (var i = 0; i < arguments.length; i++){
            var mymodule = arguments[i];
            // do something with mymodule...
        }
    });

});

EDIT: From your own answer, I see you're using underscore/lodash, so using _.values and _.object can simplify the looping through arguments array as above.

How to normalize a signal to zero mean and unit variance?

To avoid division by zero!

function x = normalize(x, eps)
    % Normalize vector `x` (zero mean, unit variance)

    % default values
    if (~exist('eps', 'var'))
        eps = 1e-6;
    end

    mu = mean(x(:));

    sigma = std(x(:));
    if sigma < eps
        sigma = 1;
    end

    x = (x - mu) / sigma;
end

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

Controller 'ngModel', required by directive '...', can't be found

One possible solution to this issue is ng-model attribute is required to use that directive.

Hence adding in the 'ng-model' attribute can resolve the issue.

<input submit-required="true" ng-model="user.Name"></input>

How to stop an unstoppable zombie job on Jenkins without restarting the server?

The first proposed solution is pretty close. If you use stop() instead of interrupt() it even kills runaway threads, that run endlessly in a groovy system script. This will kill any build, that runs for a job. Here is the code:

Thread.getAllStackTraces().keySet().each() {
    if (it.name.contains('YOUR JOBNAME')) {  
      println "Stopping $it.name"
      it.stop()
    }
}

Entity Framework Core: A second operation started on this context before a previous operation completed

I had the same error. It happened because I called a method that was constructed as public async void ... instead of public async Task ....

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

This question on StackOverflow deals with RadioButtonListFor and the answer addresses your question too. You can set the selected property in the RadioButtonListViewModel.

Get class labels from Keras functional model

y_prob = model.predict(x) 
y_classes = y_prob.argmax(axis=-1)

As suggested here.

"Object doesn't support this property or method" error in IE11

Add the code snippet in JS file used in master page or used globally.

<script language="javascript">
if (typeof browseris !== 'undefined') {
    browseris.ie = false;
}
</script>

For more information refer blog: http://blogs2share.blogspot.in/2016/11/object-doesnt-support-property-or.html

GET parameters in the URL with CodeIgniter

allesklar: That is slightly misleading, as scripts and bots can POST data nearly as easily as sending a normal request. It's not a secret, it's part of HTTP.

Use of def, val, and var in scala

With

def person = new Person("Kumar", 12) 

you are defining a function/lazy variable which always returns a new Person instance with name "Kumar" and age 12. This is totally valid and the compiler has no reason to complain. Calling person.age will return the age of this newly created Person instance, which is always 12.

When writing

person.age = 45

you assign a new value to the age property in class Person, which is valid since age is declared as var. The compiler will complain if you try to reassign person with a new Person object like

person = new Person("Steve", 13)  // Error

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

This happens when you are trying to run application on emulator. Emulator does not have shared google maps library.

Update multiple columns in SQL

I tried with this way and its working fine :

UPDATE 
  Emp
SET 
  ID = 123, 
  Name = 'Peter' 
FROM 
  Table_Name

How to allow user to pick the image with Swift?

Xcode 10, Swift 4.2

Below is a slightly optimized version of the implementation. This is in Swift 4.2 and I have tested it too.

You can see the complete code for ViewController here. Please note that you have to define an IBOutlet (imageView) and IBAction (didTapOnChooseImageButton) defined and connected in storyboard too. Hope this helps.

import UIKit

class ImagePickViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

var imagePicker = UIImagePickerController()
@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBAction func didTapOnChooseImageButton(_ sender: Any) {
    let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
    let cameraAction = UIAlertAction(title: "Camera", style: UIAlertAction.Style.default) {
        UIAlertAction in
        self.openCamera(UIImagePickerController.SourceType.camera)
    }
    let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertAction.Style.default) {
        UIAlertAction in
        self.openCamera(UIImagePickerController.SourceType.photoLibrary)
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) {
        UIAlertAction in
    }

    // Add the actions
    imagePicker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
    alert.addAction(cameraAction)
    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)
    self.present(alert, animated: true, completion: nil)
}

func openCamera(_ sourceType: UIImagePickerController.SourceType) {
    imagePicker.sourceType = sourceType
    self.present(imagePicker, animated: true, completion: nil)
}

//MARK:UIImagePickerControllerDelegate

func imagePickerController(_ picker: UIImagePickerController,
                                    didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    imageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    imagePicker.dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    print("imagePickerController cancel")
}

}

SQL - How to find the highest number in a column?

SELECT * FROM Customers ORDER BY ID DESC LIMIT 1

Then get the ID.

C# naming convention for constants?

Actually, it is

private const int TheAnswer = 42;

At least if you look at the .NET library, which IMO is the best way to decide naming conventions - so your code doesn't look out of place.

What does getActivity() mean?

Two likely definitions:

Python how to write to a binary file?

As of Python 3.2+, you can also accomplish this using the to_bytes native int method:

newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
    newFile.write(byte.to_bytes(1, byteorder='big'))

I.e., each single call to to_bytes in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte. You can also shorten the last two lines into a single one:

newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))

Check if a variable is of function type

I found that when testing native browser functions in IE8, using toString, instanceof, and typeof did not work. Here is a method that works fine in IE8 (as far as I know):

function isFn(f){
    return !!(f && f.call && f.apply);
}
//Returns true in IE7/8
isFn(document.getElementById);

Alternatively, you can check for native functions using:

"getElementById" in document

Though, I have read somewhere that this will not always work in IE7 and below.

How to listen for changes to a MongoDB collection?

There is an working java example which can be found here.

 MongoClient mongoClient = new MongoClient();
    DBCollection coll = mongoClient.getDatabase("local").getCollection("oplog.rs");

    DBCursor cur = coll.find().sort(BasicDBObjectBuilder.start("$natural", 1).get())
            .addOption(Bytes.QUERYOPTION_TAILABLE | Bytes.QUERYOPTION_AWAITDATA);

    System.out.println("== open cursor ==");

    Runnable task = () -> {
        System.out.println("\tWaiting for events");
        while (cur.hasNext()) {
            DBObject obj = cur.next();
            System.out.println( obj );

        }
    };
    new Thread(task).start();

The key is QUERY OPTIONS given here.

Also you can change find query, if you don't need to load all the data every time.

BasicDBObject query= new BasicDBObject();
query.put("ts", new BasicDBObject("$gt", new BsonTimestamp(1471952088, 1))); //timestamp is within some range
query.put("op", "i"); //Only insert operation

DBCursor cur = coll.find(query).sort(BasicDBObjectBuilder.start("$natural", 1).get())
.addOption(Bytes.QUERYOPTION_TAILABLE | Bytes.QUERYOPTION_AWAITDATA);

How to disable SSL certificate checking with Spring RestTemplate?

Please see below for a modest improvement on @Sled's code shown above, that turn-back-on method was missing one line, now it passes my tests. This disables HTTPS certificate and hostname spoofing when using RestTemplate in a Spring-Boot version 2 application that uses the default HTTP configuration, NOT configured to use Apache HTTP Client.

package org.my.little.spring-boot-v2.app;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Disables and enables certificate and host-name checking in
 * HttpsURLConnection, the default JVM implementation of the HTTPS/TLS protocol.
 * Has no effect on implementations such as Apache Http Client, Ok Http.
*/
public final class SSLUtils {

    private static final HostnameVerifier jvmHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();

    private static final HostnameVerifier trivialHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession sslSession) {
            return true;
        }
    };

    private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
        HttpsURLConnection.setDefaultHostnameVerifier(trivialHostnameVerifier);
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, UNQUESTIONING_TRUST_MANAGER, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
        HttpsURLConnection.setDefaultHostnameVerifier(jvmHostnameVerifier);
        // Return it to the initial state (discovered by reflection, now hardcoded)
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, null, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    private SSLUtils() {
        throw new UnsupportedOperationException("Do not instantiate libraries.");
    }
}

Check if a parameter is null or empty in a stored procedure

If you want to use a parameter is Optional so use it.

CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL
    AS
    SELECT *
    FROM AdventureWorks.Person.Address
    WHERE City = ISNULL(@City,City)
    AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%'
    GO

Remove trailing spaces automatically or with a shortcut

Not only can you change the Visual Studio Code settings to trim trailing whitespace automatically, but you can also do this from the command palette (Ctrl+Shift+P):

Command Palette: Trim Trailing Whitespace

You can also use the keyboard shortcut:

  • Windows, Linux: Ctrl+K, Ctrl+X
  • Mac: ? + k, ? + x.

(I'm using Visual Studio Code 1.20.1.)

How to disable Hyper-V in command line?

This command works

Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All

Run it then agree to restart the computer when prompted.

I ran it in elevated permissions PowerShell on Windows 10, but it should also work on Win 8 or 7.

How to delete row based on cell value

This is the autofilter macro you could base a function off of:

Selection.AutoFilter
ActiveSheet.Range("$A$1:$A$10").AutoFilter Field:=1, Criteria1:="=*-*", Operator:=xlAnd
Selection.AutoFilter

I use this autofilter function to delete matching rows:

Public Sub FindDelete(sCol As String, vSearch As Variant)
'Simple find and Delete
Dim lLastRow As Integer
Dim rng As Range
Dim rngDelete As Range
    Range(sCol & 1).Select
    [2:2].Insert
    Range(sCol & 2) = "temp"
    With ActiveSheet
        .usedrange
            lLastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
        Set rng = Range(sCol & 2, Cells(lLastRow, sCol))
            rng.AutoFilter Field:=1, Criteria1:=vSearch, Operator:=xlAnd
        Set rngDelete = rng.SpecialCells(xlCellTypeVisible)
            rng.AutoFilter
            rngDelete.EntireRow.Delete
        .usedrange
    End With
End Sub

call it like:

call FindDelete "A", "=*-*"

It's saved me a lot of work. Good luck!

Git Bash doesn't see my PATH

I meet this problem when I try to use mingw to compile the xgboost lib in Win10. Finally I found the solution.

Create a file named as .bashrc in your home directory (usually the C:\Users\username). Then add the path to it. Remember to use quotes if your path contains blank, and remember to use /c/ instead of C:/

For example:

PATH=$PATH:"/c/Program Files/mingw-w64/x86_64-7.2.0-posix-seh-rt_v5-rev1/mingw64/bin"

jQuery window scroll event does not fire up

  1. Declare your jQuery between <script> and </script> in the <head>,
  2. Wrap your .scroll() event within
$(document).ready(function(){
  //do something
});

How to loop through all elements of a form jQuery

From the jQuery :input selector page:

Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

This is the best choice.

$('#new_user_form *').filter(':input').each(function(){
    //your code here
});

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

Open web.config,then Change

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>

To

<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" timeout="2880" />
</authentication>

change to ~/Default.aspx

Make selected block of text uppercase

enter image description here

Select the text to transform.

Use Ctrl + L to selected the whole line

Open Show all commands.

Linux and Windows: Ctrl + Shift + P, Mac: ??P

Type in the command, e.g. lower, upper, title

Hit Enter

Am I trying to connect to a TLS-enabled daemon without TLS?

The underlining problem is simple – lack of permission to /var/run/docker.sock unix domain socket.

From Daemon socket option chapter of Docker Command Line reference for Docker 1.6.0:

By default, a unix domain socket (or IPC socket) is created at /var/run/docker.sock, requiring either root permission, or docker group membership.

Steps necessary to grant rights to users are nicely described in Docker installation instructions for Fedora:

Granting rights to users to use Docker

The docker command line tool contacts the docker daemon process via a socket file /var/run/docker.sock owned by root:root. Though it's recommended to use sudo for docker commands, if users wish to avoid it, an administrator can create a docker group, have it own /var/run/docker.sock, and add users to this group.

$ sudo groupadd docker
$ sudo chown root:docker /var/run/docker.sock
$ sudo usermod -a -G docker $USERNAME

Log out and log back in for above changes to take effect. Please note that Docker packages of some Linux distributions (Ubuntu) do already place /var/run/docker.sock in the docker group making the first two of above steps unnecessary.

In case of OS X and boot2docker the situation is different; the Docker daemon runs inside a VM so the DOCKER_HOST environment variable must be set to this VM so that the Docker client could find the Docker daemon. This is done by running $(boot2docker shellinit) in the shell.

How to open a WPF Popup when another control is clicked, using XAML markup only?

another way to do it:

<Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                    <StackPanel>
                        <Image Source="{Binding ProductImage,RelativeSource={RelativeSource TemplatedParent}}" Stretch="Fill" Width="65" Height="85"/>
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        <Button x:Name="myButton" Width="40" Height="10">
                            <Popup Width="100" Height="70" IsOpen="{Binding ElementName=myButton,Path=IsMouseOver, Mode=OneWay}">
                                <StackPanel Background="Yellow">
                                    <ItemsControl ItemsSource="{Binding Produkt.SubProducts}"/>
                                </StackPanel>
                            </Popup>
                        </Button>
                    </StackPanel>
                </Border>

Google Chrome: This setting is enforced by your administrator

Try to use this solution:

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome

Run regedit, Delete the key, then restart Chrome.

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

Adding items to end of linked list

Here's a hint, you have a graph of nodes in the linked list, and you always keep a reference to head which is the first node in the linkedList.
next points to the next node in the linkedlist, so when next is null you are at the end of the list.

Generate 'n' unique random numbers within a range

If you just need sampling without replacement:

>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]

random.sample takes a population and a sample size k and returns k random members of the population.

If you have to control for the case where k is larger than len(population), you need to be prepared to catch a ValueError:

>>> try:
...   random.sample(range(1, 2), 3)
... except ValueError:
...   print('Sample size exceeded population size.')
... 
Sample size exceeded population size

Dictionary text file

For an English dictionary .txt file, you can use Custom Dictionary.

You can also generate a list aspell or wordlist with own settings.

Also you can take a look at http://wordlist.sourceforge.net/

Only english words: http://www.math.sjsu.edu/~foster/dictionary.txt

Get keys from HashMap in Java

Use functional operation for faster iteration.

team1.keySet().forEach((key) -> { System.out.println(key); });

What's the best practice using a settings file in Python?

The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.

To use the yaml module is extremely simple:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

library not found for -lPods

Be sure that you open .xcworkspace, not .xcodeproj

Which Python memory profiler is recommended?

Consider the objgraph library (see this blog post for an example use case).

How to pass credentials to httpwebrequest for accessing SharePoint Library

You could also use:

request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 

How to include a quote in a raw Python string

Since I stumbled on this answer, and it greatly helped me, but I found a minor syntactic issue, I felt I should save others possible frustration. The triple quoted string works for this scenario as described, but note that if the " you want in the string occurs at the end of the string itself:

somestr = """This is a string with a special need to have a " in it at the end""""

You will hit an error at execution because the """" (4) quotes in a row confuses the string reader, as it thinks it has hit the end of the string already and then finds a random " out there. You can validate this by inserting a space into the 4 quotes like so: " """ and it will not have the error.

In this special case you will need to either use:

somestr = 'This.....at the end"'

or use the method described above of building multiple strings with mixed " and ' and then concatenating them after the fact.

H2 in-memory database. Table not found

Hard to tell. I created a program to test this:

package com.gigaspaces.compass;

import org.testng.annotations.Test;

import java.sql.*;

public class H2Test {
@Test
public void testDatabaseNoMem() throws SQLException {
    testDatabase("jdbc:h2:test");
}
@Test
public void testDatabaseMem() throws SQLException {
    testDatabase("jdbc:h2:mem:test");
}

private void testDatabase(String url) throws SQLException {
    Connection connection= DriverManager.getConnection(url);
    Statement s=connection.createStatement();
    try {
    s.execute("DROP TABLE PERSON");
    } catch(SQLException sqle) {
        System.out.println("Table not found, not dropping");
    }
    s.execute("CREATE TABLE PERSON (ID INT PRIMARY KEY, FIRSTNAME VARCHAR(64), LASTNAME VARCHAR(64))");
    PreparedStatement ps=connection.prepareStatement("select * from PERSON");
    ResultSet r=ps.executeQuery();
    if(r.next()) {
        System.out.println("data?");
    }
    r.close();
    ps.close();
    s.close();
    connection.close();
}
}

The test ran to completion, with no failures and no unexpected output. Which version of h2 are you running?

How can I center an image in Bootstrap?

Three ways to align img in the center of its parent.

  1. img is an inline element, text-center aligns inline elements in the center of its container should the container be a block element.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col text-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. mx-auto centers block elements. In order to so, change display of the img from inline to block with d-block class.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. Use d-flex and justify-content-center on its parent.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col d-flex justify-content-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Create a new RGB OpenCV image using Python?

The new cv2 interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:

import cv2  # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)

This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:

blank_image[:,0:width//2] = (255,0,0)      # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)

If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2 interface rather than the older cv one. I made the change recently and have never looked back. You can read more about cv2 at the OpenCV Change Logs.

Manually type in a value in a "Select" / Drop-down HTML list?

Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.

Example: http://jsfiddle.net/c258Q/

HTML code:

Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
    <option value="apple">Apple</option>
    <option value="orange">Apricot </option>
    <option value="melon">Peach</option>
    <option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>

JavaScript:

function DropDownChanged(oDDL) {
    var oTextbox = oDDL.form.elements["fruit_txt"];
    if (oTextbox) {
        oTextbox.style.display = (oDDL.value == "") ? "" : "none";
        if (oDDL.value == "")
            oTextbox.focus();
    }
}

function FormSubmit(oForm) {
    var oHidden = oForm.elements["fruit"];
    var oDDL = oForm.elements["fruit_ddl"];
    var oTextbox = oForm.elements["fruit_txt"];
    if (oHidden && oDDL && oTextbox)
        oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}

And in the server side, read the value of "fruit" from the Request.

AngularJS - add HTML element to dom in directive without jQuery

If your destination element is empty and will only contain the <svg> tag you could consider using ng-bind-html as follow :

Declare your HTML tag in the directive scope variable

link: function (scope, iElement, iAttrs) {

    scope.svgTag = '<svg width="600" height="100" class="svg"></svg>';

    ...
}

Then, in your directive template, just add the proper attribute at the exact place you want to append the svg tag :

<!-- start of directive template code -->
...
<!-- end of directive template code -->
<div ng-bind-html="svgTag"></div>

Don't forget to include ngSanitize to allow ng-bind-html to automatically parse the HTML string to trusted HTML and avoid insecure code injection warnings.

See official documentation for more details.

What does "Use of unassigned local variable" mean?

You don't assign values outside of the if statements ... and it is possible that credit might be something other than 0, 1, 2, or 3, as @iomaxx noted.

Try changing the separate if statements to a single if/else if/else if/else. Or assign default values up at the top.

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

For added information, under the context of running the application in docker.

In docker-compose.yml file, under the application container itself, you can use one of the following:

command: ["rm /your-app-path/tmp/pids/server.pid && bundle exec bin/rails s -p 3000 -b '0.0.0.0'"]

or

command: ["rm /your-app-path/tmp/pids/server.pid; foreman start"]

Note the use of either ; or &&, that && will send an exit signal if rm fails to find the file, forcing your container to prematurely stop. Using ; will continue to execute.

Why is this caused in the first place? The rationale is that if the server (puma/thin/whatever) does not cleanly exit, it will leave a pid in the host machine causing an exit error.

For portability rather than manually deleting the file on the host system, it's better to check if the file exists within scripted or compose file itself.

iPhone App Icons - Exact Radius?

There are two totally conflicting answers with large number of votes one is 160px@1024 the other is 180px@1024. So witch one?

I ran some experiments and I think that it is 180px@1024 so drbarnard is correct.

I downloaded iTunes U icon from the App Store it's 175x175px I upscaled it in photoshop to 1024px and put two shapes on it, one with 160px radius and one with 180px.

As you can see below the shape (thin gray line) with 160px (the 1st one) is a bit off whereas the one with 180px looks just fine.

shape with 160px radiusenter image description here

This is what I do now in PhotoShop:

  1. I create a canvas sized 1026x1026px with a 180px mask for main design Smart Object.
  2. I duplicate the main Smart Object 5 times and resize them to 1024px, 144px, 114px, 72px and 57px.
  3. I put a "New layered Based Slice" on each Smart Objects and I rename slices according to their size (e.g. icon-72px).
  4. When I save the artwork I select "All User Slices" and BANG! I have all icons necessary for my app.

Show Hide div if, if statement is true

<?php
$divStyle=''; // show div

// add condition
if($variable == '1'){
  $divStyle='style="display:none;"'; //hide div
}

print'<div '.$divStyle.'>Div to hide</div>';
?>

Count a list of cells with the same background color

Excel has no way of gathering that attribute with it's built-in functions. If you're willing to use some VB, all your color-related questions are answered here:

http://www.cpearson.com/excel/colors.aspx

Example form the site:

The SumColor function is a color-based analog of both the SUM and SUMIF function. It allows you to specify separate ranges for the range whose color indexes are to be examined and the range of cells whose values are to be summed. If these two ranges are the same, the function sums the cells whose color matches the specified value. For example, the following formula sums the values in B11:B17 whose fill color is red.

=SUMCOLOR(B11:B17,B11:B17,3,FALSE)

Array of char* should end at '\0' or "\0"?

Well, technically '\0' is a character while "\0" is a string, so if you're checking for the null termination character the former is correct. However, as Chris Lutz points out in his answer, your comparison won't work in it's current form.

Can I use Twitter Bootstrap and jQuery UI at the same time?

Bootstrap still doesnt work with Jquery UI, for example the modal.Bootstrap has nice style but as a framework with Twitter behind isnt that good.

Can RDP clients launch remote applications and not desktops

This is called "seamless" mode. rdesktop, the RDP client for Unix, is capable of this. From the manpage:

   -A     Enable SeamlessRDP. In this mode, rdesktop creates a X11 window for each window on the server
          side.  This  mode  requires  the  SeamlessRDP  server side component, which is available from
          http://www.cendio.com/seamlessrdp/.  When using this option, you  should  specify  a  startup
          shell which launches the desired application through SeamlessRDP.

See mentioned Cendio website for more information.

Parsing JSON in Excel VBA

Lots of good answers here - just chipping in my own.

I had a requirement to parse a very specific JSON string, representing the results of making a web-API call. The JSON described a list of objects, and looked something like this:

[
   {
     "property1": "foo",
     "property2": "bar",
     "timeOfDay": "2019-09-30T00:00:00",
     "numberOfHits": 98,
     "isSpecial": false,
     "comment": "just to be awkward, this contains a comma"
   },
   {
     "property1": "fool",
     "property2": "barrel",
     "timeOfDay": "2019-10-31T00:00:00",
     "numberOfHits": 11,
     "isSpecial": false,
     "comment": null
   },
   ...
]

There are a few things to note about this:

  1. The JSON should always describe a list (even if empty), which should only contain objects.
  2. The objects in the list should only contain properties with simple types (string / date / number / boolean or null).
  3. The value of a property may contain a comma - which makes parsing the JSON somewhat harder - but may not contain any quotes (because I'm too lazy to deal with that).

The ParseListOfObjects function in the code below takes the JSON string as input, and returns a Collection representing the items in the list. Each item is represented as a Dictionary, where the keys of the dictionary correspond to the names of the object's properties. The values are automatically converted to the appropriate type (String, Date, Double, Boolean - or Empty if the value is null).

Your VBA project will need a reference to the Microsoft Scripting Runtime library to use the Dictionary object - though it would not be difficult to remove this dependency if you use a different way of encoding the results.

Here's my JSON.bas:

Option Explicit

' NOTE: a fully-featured JSON parser in VBA would be a beast.
' This simple parser only supports VERY simple JSON (which is all we need).
' Specifically, it supports JSON comprising a list of objects, each of which has only simple properties.

Private Const strSTART_OF_LIST As String = "["
Private Const strEND_OF_LIST As String = "]"

Private Const strLIST_DELIMITER As String = ","

Private Const strSTART_OF_OBJECT As String = "{"
Private Const strEND_OF_OBJECT As String = "}"

Private Const strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR As String = ":"

Private Const strQUOTE As String = """"

Private Const strNULL_VALUE As String = "null"
Private Const strTRUE_VALUE As String = "true"
Private Const strFALSE_VALUE As String = "false"


Public Function ParseListOfObjects(ByVal strJson As String) As Collection

    ' Takes a JSON string that represents a list of objects (where each object has only simple value properties), and
    ' returns a collection of dictionary objects, where the keys and values of each dictionary represent the names and
    ' values of the JSON object properties.

    Set ParseListOfObjects = New Collection

    Dim strList As String: strList = Trim(strJson)

    ' Check we have a list
    If Left(strList, Len(strSTART_OF_LIST)) <> strSTART_OF_LIST _
    Or Right(strList, Len(strEND_OF_LIST)) <> strEND_OF_LIST Then
        Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list (it does not start with '" & strSTART_OF_LIST & "' and end with '" & strEND_OF_LIST & "')"
    End If

    ' Get the list item text (between the [ and ])
    Dim strBody As String: strBody = Trim(Mid(strList, 1 + Len(strSTART_OF_LIST), Len(strList) - Len(strSTART_OF_LIST) - Len(strEND_OF_LIST)))

    If strBody = "" Then
        Exit Function
    End If

    ' Check we have a list of objects
    If Left(strBody, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
        Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list of objects (the content of the list does not start with '" & strSTART_OF_OBJECT & "')"
    End If

    ' We now have something like:
    '    {"property":"value", "property":"value"}, {"property":"value", "property":"value"}, ...
    ' so we can't just split on a comma to get the various items (because the items themselves have commas in them).
    ' HOWEVER, since we know we're dealing with very simple JSON that has no nested objects, we can split on "}," because
    ' that should only appear between items. That'll mean that all but the last item will be missing it's closing brace.
    Dim astrItems() As String: astrItems = Split(strBody, strEND_OF_OBJECT & strLIST_DELIMITER)

    Dim ixItem As Long
    For ixItem = LBound(astrItems) To UBound(astrItems)

        Dim strItem As String: strItem = Trim(astrItems(ixItem))

        If Left(strItem, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
            Err.Raise vbObjectError, Description:="Mal-formed list item (does not start with '" & strSTART_OF_OBJECT & "')"
        End If

        ' Only the last item will have a closing brace (see comment above)
        Dim bIsLastItem As Boolean: bIsLastItem = ixItem = UBound(astrItems)

        If bIsLastItem Then
            If Right(strItem, Len(strEND_OF_OBJECT)) <> strEND_OF_OBJECT Then
                Err.Raise vbObjectError, Description:="Mal-formed list item (does not end with '" & strEND_OF_OBJECT & "')"
            End If
        End If

        Dim strContent: strContent = Mid(strItem, 1 + Len(strSTART_OF_OBJECT), Len(strItem) - Len(strSTART_OF_OBJECT) - IIf(bIsLastItem, Len(strEND_OF_OBJECT), 0))

        ParseListOfObjects.Add ParseObjectContent(strContent)

    Next ixItem

End Function

Private Function ParseObjectContent(ByVal strContent As String) As Scripting.Dictionary

    Set ParseObjectContent = New Scripting.Dictionary
    ParseObjectContent.CompareMode = TextCompare

    ' The object content will look something like:
    '    "property":"value", "property":"value", ...
    ' ... although the value may not be in quotes, since numbers are not quoted.
    ' We can't assume that the property value won't contain a comma, so we can't just split the
    ' string on the commas, but it's reasonably safe to assume that the value won't contain further quotes
    ' (and we're already assuming no sub-structure).
    ' We'll need to scan for commas while taking quoted strings into account.

    Dim ixPos As Long: ixPos = 1
    Do While ixPos <= Len(strContent)

        Dim strRemainder As String

        ' Find the opening quote for the name (names should always be quoted)
        Dim ixOpeningQuote As Long: ixOpeningQuote = InStr(ixPos, strContent, strQUOTE)

        If ixOpeningQuote <= 0 Then
            ' The only valid reason for not finding a quote is if we're at the end (though white space is permitted)
            strRemainder = Trim(Mid(strContent, ixPos))
            If Len(strRemainder) = 0 Then
                Exit Do
            End If
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not start with a quote)"
        End If

        ' Now find the closing quote for the name, which we assume is the very next quote
        Dim ixClosingQuote As Long: ixClosingQuote = InStr(ixOpeningQuote + 1, strContent, strQUOTE)
        If ixClosingQuote <= 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not end with a quote)"
        End If

        If ixClosingQuote - ixOpeningQuote - Len(strQUOTE) = 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (the object name is blank)"
        End If

        Dim strName: strName = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))

        ' The next thing after the quote should be the colon

        Dim ixNameValueSeparator As Long: ixNameValueSeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)

        If ixNameValueSeparator <= 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (missing '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
        End If

        ' Check that there was nothing between the closing quote and the colon

        strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixNameValueSeparator - ixClosingQuote - Len(strQUOTE)))
        If Len(strRemainder) > 0 Then
            Err.Raise vbObjectError, Description:="Mal-formed object (unexpected content between name and '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
        End If

        ' What comes after the colon is the value, which may or may not be quoted (e.g. numbers are not quoted).
        ' If the very next thing we see is a quote, then it's a quoted value, and we need to find the matching
        ' closing quote while ignoring any commas inside the quoted value.
        ' If the next thing we see is NOT a quote, then it must be an unquoted value, and we can scan directly
        ' for the next comma.
        ' Either way, we're looking for a quote or a comma, whichever comes first (or neither, in which case we
        ' have the last - unquoted - value).

        ixOpeningQuote = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strQUOTE)
        Dim ixPropertySeparator As Long: ixPropertySeparator = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strLIST_DELIMITER)

        If ixOpeningQuote > 0 And ixPropertySeparator > 0 Then
            ' Only use whichever came first
            If ixOpeningQuote < ixPropertySeparator Then
                ixPropertySeparator = 0
            Else
                ixOpeningQuote = 0
            End If
        End If

        Dim strValue As String
        Dim vValue As Variant

        If ixOpeningQuote <= 0 Then ' it's not a quoted value

            If ixPropertySeparator <= 0 Then ' there's no next value; this is the last one
                strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
                ixPos = Len(strContent) + 1
            Else ' this is not the last value
                strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), ixPropertySeparator - ixNameValueSeparator - Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
                ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)
            End If

            vValue = ParseUnquotedValue(strValue)

        Else ' It is a quoted value

            ' Find the corresponding closing quote, which should be the very next one

            ixClosingQuote = InStr(ixOpeningQuote + Len(strQUOTE), strContent, strQUOTE)

            If ixClosingQuote <= 0 Then
                Err.Raise vbObjectError, Description:="Mal-formed object (the value does not end with a quote)"
            End If

            strValue = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))
            vValue = ParseQuotedValue(strValue)

            ' Re-scan for the property separator, in case we hit one that was part of the quoted value
            ixPropertySeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strLIST_DELIMITER)

            If ixPropertySeparator <= 0 Then ' this was the last value

                ' Check that there's nothing between the closing quote and the end of the text
                strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE)))
                If Len(strRemainder) > 0 Then
                    Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
                End If

                ixPos = Len(strContent) + 1

            Else ' this is not the last value

                ' Check that there's nothing between the closing quote and the property separator
                strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixPropertySeparator - ixClosingQuote - Len(strQUOTE)))
                If Len(strRemainder) > 0 Then
                    Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
                End If

                ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)

            End If

        End If

        ParseObjectContent.Add strName, vValue

    Loop

End Function

Private Function ParseUnquotedValue(ByVal strValue As String) As Variant

    If StrComp(strValue, strNULL_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = Empty
    ElseIf StrComp(strValue, strTRUE_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = True
    ElseIf StrComp(strValue, strFALSE_VALUE, vbTextCompare) = 0 Then
        ParseUnquotedValue = False
    ElseIf IsNumeric(strValue) Then
        ParseUnquotedValue = CDbl(strValue)
    Else
        Err.Raise vbObjectError, Description:="Mal-formed value (not null, true, false or a number)"
    End If

End Function

Private Function ParseQuotedValue(ByVal strValue As String) As Variant

    ' Both dates and strings are quoted; we'll treat it as a date if it has the expected date format.
    ' Dates are in the form:
    '    2019-09-30T00:00:00
    If strValue Like "####-##-##T##:00:00" Then
        ' NOTE: we just want the date part
        ParseQuotedValue = CDate(Left(strValue, Len("####-##-##")))
    Else
        ParseQuotedValue = strValue
    End If

End Function

A simple test:

Const strJSON As String = "[{""property1"":""foo""}]"
Dim oObjects As Collection: Set oObjects = Json.ParseListOfObjects(strJSON)

MsgBox oObjects(1)("property1") ' shows "foo"

Eclipse: All my projects disappeared from Project Explorer

Tedious but it worked for me (Kepler):

  1. Using the OS zip utility, zip everything below the project workspace folder to a zip file, to be placed in a separate directory (will use c:\tmp\workspace.zip as an example).

  2. Unzip workspace.zip to the c:\tmp directory. Assume there's a project folder called Project1

    a. Ensure all the files in Project1 have Full Control permissions for Everyone or at least 777 permissions.

  3. Remove all the project folders in the Eclipse workspace.

  4. Recreate each project one by one according to its original type (Java, Dynamic Web, etc.). (Will use Project1 as an example.) Do not add anything.

  5. In Eclipse, do File -> Import -> File System. Then select c:\tmp\Project1 as a source

  6. Select the workspace Project1 as a destination. Do not overwrite any file.

  7. In Eclipse, refresh the project and test it. It should work.

Does my application "contain encryption"?

Yes, according to iTunes Connect Export Compliance Information screens, if you use built-in iOS or MacOS encryption (keychain, https), you are using encryption for purposes of US Government Export regulations. Whether you qualify for an export compliance exemption depends on what your app does and how it uses this encryption. Attached images show the iTunes Connect Export Compliance Screens to help you determine your export reporting obligations. In particular, it states:

If you are making use of ATS or making a call to HTTPS please note that you are required to submit a year-end self classification report to the US government. Learn more

iTunes Connect Export Compliance Information Q1

iTunes Connect Export Compliance Information Q2

Selecting option by text content with jQuery

If your <option> elements don't have value attributes, then you can just use .val:

$selectElement.val("text_you're_looking_for")

However, if your <option> elements have value attributes, or might do in future, then this won't work, because whenever possible .val will select an option by its value attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value attributes, so we'll have to add one ourselves with a simple plugin:

/*
  Source: https://stackoverflow.com/a/16887276/1709587

  Usage instructions:

  Call

      jQuery('#mySelectElement').selectOptionWithText('target_text');

  to select the <option> element from within #mySelectElement whose text content
  is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
    return this.each(function () {
        var $selectElement, $options, $targetOption;

        $selectElement = jQuery(this);
        $options = $selectElement.find('option');
        $targetOption = $options.filter(
            function () {return jQuery(this).text() == targetText}
        );

        // We use `.prop` if it's available (which it should be for any jQuery
        // versions above and including 1.6), and fall back on `.attr` (which
        // was used for changing DOM properties in pre-1.6) otherwise.
        if ($targetOption.prop) {
            $targetOption.prop('selected', true);
        } 
        else {
            $targetOption.attr('selected', 'true');
        }
    });
}

Just include this plugin somewhere after you add jQuery onto the page, and then do

jQuery('#someSelectElement').selectOptionWithText('Some Target Text');

to select options.

The plugin method uses filter to pick out only the option matching the targetText, and selects it using either .attr or .prop, depending upon jQuery version (see .prop() vs .attr() for explanation).

Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/

JavaScript regex for alphanumeric string with length of 3-5 chars

You'd have to define alphanumerics exactly, but

/^(\w{3,5})$/ 

Should match any digit/character/_ combination of length 3-5.

If you also need the dash, make sure to escape it (\-) add it, like this: :

/^([\w\-]{3,5})$/ 

Also: the ^ anchor means that the sequence has to start at the beginning of the line (character string), and the $ that it ends at the end of the line (character string). So your value string mustn't contain anything else, or it won't match.

How do I set a textbox's value using an anchor with jQuery?

Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')

Where is the IIS Express configuration / metabase file found?

The configuration file is called applicationhost.config. It's stored here:

My Documents > IIS Express > config

usually, but not always, one of these paths will work

%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config

Update for VS2019
If you're using Visual Studio 2019+ check this path:

$(solutionDir)\.vs\{projectName}\config\applicationhost.config

Update for VS2015 (credit: @Talon)
If you're using Visual Studio 2015-2017 check this path:

$(solutionDir)\.vs\config\applicationhost.config

In Visual Studio 2015+ you can also configure which applicationhost.config file is used by altering the <UseGlobalApplicationHostFile>true|false</UseGlobalApplicationHostFile> setting in the project file (eg: MyProject.csproj). (source: MSDN forum)

How to install plugins to Sublime Text 2 editor?

The instruction has been tested on Mac OSx Catalina.

After installing Sublime Text 3, install Package Control through Tools > Package Control. Use the following instructions to install package or theme:

  1. press CMD + SHIFT + P

  2. choose Package Control: Install Package---or any other options you require. package control

  3. enter the name of required package or theme and press enter.

installing package

How do you run a command as an administrator from the Windows command line?

Although @amr ali's code was great, I had an instance where my bat file contained > < signs, and it choked on them for some reason.

I found this instead. Just put it all before your code, and it works perfectly.

REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
    "%temp%\getadmin.vbs"
    exit /B
:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

How to Right-align flex item?

For those using Angular and Flex-Layout, use the following on the flex-item container:

<div fxLayout="row" fxLayoutAlign="flex-end">

See fxLayoutAlign docs here and the full fxLayout docs here.

Push an associative item into an array in JavaScript

JavaScript doesn't have associate arrays. You need to use Objects instead:

var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?

To get value you can use now different ways:

console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?

What causes java.lang.IncompatibleClassChangeError?

Documenting another scenario after burning way too much time.

Make sure you don't have a dependency jar that has a class with an EJB annotation on it.

We had a common jar file that had an @local annotation. That class was later moved out of that common project and into our main ejb jar project. Our ejb jar and our common jar are both bundled within an ear. The version of our common jar dependency was not updated. Thus 2 classes trying to be something with incompatible changes.

Remove a file from the list that will be committed

if you did a git add and you haven't pushed anything yet, you just have to do this to unstage it from your commit.

git reset HEAD <file>

Android Relative Layout Align Center

Is this what you need?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableRow
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp" >

        <ImageView
            android:id="@+id/place_category_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:contentDescription="ss"
            android:paddingRight="15dp"
            android:paddingTop="10dp"
            android:src="@drawable/marker" />

        <TextView
            android:id="@+id/place_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Place Name"
            android:textColor="#F00F00"
            android:layout_gravity="center_vertical"
            android:textSize="14sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/place_distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:layout_gravity="center_vertical"
            android:text="320" />
    </TableRow>

</RelativeLayout>

Add image in pdf using jspdf

In TypeScript, you can do:

private getImage(imagePath): ng.IPromise<any> {
    var defer = this.q.defer<any>();
    var img = new Image();
    img.src = imagePath;
    img.addEventListener('load',()=>{
       defer.resolve(img);
    });


    return defer.promise;
} 

Use the above function to getimage object. Then the following to add to pdf file:

pdf.addImage(getImage(url), 'png', x, y, imagewidth, imageheight);

In plain JavaScript, the function looks like this:

function (imagePath) {
        var defer = this.q.defer();
        var img = new Image();
        img.src = imagePath;
        img.addEventListener('load', function () {
            defer.resolve(img);
        });
        return defer.promise;
    };

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

List<String> arrayList = new ArrayList<String>();
for (String s : arrayList) {
    if(s.equals(value)){
        //do something
    }
}

or

for (int i = 0; i < arrayList.size(); i++) {
    if(arrayList.get(i).equals(value)){
        //do something
    }
}

But be carefull ArrayList can hold null values. So comparation should be

value.equals(arrayList.get(i))

when you are sure that value is not null or you should check if given element is null.

Parse JSON from HttpURLConnection object

Define the following function (not mine, not sure where I found it long ago):

private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
return sb.toString();

}

Then:

String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
    {
        success = true;
        InputStream response = conn.getInputStream();
        jsonReply = convertStreamToString(response);

        // Do JSON handling here....
    }

php $_POST array empty upon form submission

REFERENCE: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

POST method

We are going to make some modifications so POST method will be used when sending the request...

var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
  }
}
http.send(params);

Some http headers must be set along with any POST request. So we set them in these lines...

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

With the above lines we are basically saying that the data send is in the format of a form submission. We also give the length of the parameters we are sending.

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
  }
}

We set a handler for the 'ready state' change event. This is the same handler we used for the GET method. You can use the http.responseText here - insert into a div using innerHTML(AHAH), eval it(JSON) or anything else.

http.send(params);

Finally, we send the parameters with the request. The given url is loaded only after this line is called. In the GET method, the parameter will be a null value. But in the POST method, the data to be send will be send as the argument of the send function. The params variable was declared in the second line as lorem=ipsum&name=binny - so we send two parameters - 'lorem' and 'name' with the values 'ipsum' and 'binny' respectively.

Converting std::__cxx11::string to std::string

Answers here mostly focus on short way to fix it, but if that does not help, I'll give some steps to check, that helped me (Linux only):

  • If the linker errors happen when linking other libraries, build those libs with debug symbols ("-g" GCC flag)
  • List the symbols in the library and grep the symbols that linker complains about (enter the commands in command line):

    nm lib_your_problem_library.a | grep functionNameLinkerComplainsAbout

  • If you got the method signature, proceed to the next step, if you got no symbols instead, mostlikely you stripped off all the symbols from the library and that is why linker can't find them when linking the library. Rebuild the library without stripping ALL the symbols, you can strip debug (strip -S option) symbols if you need.

  • Use a c++ demangler to understand the method signature, for example, this one

  • Compare the method signature in the library that you just got with the one you are using in code (check header file as well), if they are different, use the proper header or the proper library or whatever other way you now know to fix it

How to loop through all but the last item of a list?

This answers what the OP should have asked, i.e. traverse a list comparing consecutive elements (excellent SilentGhost answer), yet generalized for any group (n-gram): 2, 3, ... n:

zip(*(l[start:] for start in range(0, n)))

Examples:

l = range(0, 4)  # [0, 1, 2, 3]

list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []

Explanations:

  • l[start:] generates a a list/generator starting from index start
  • *list or *generator: passes all elements to the enclosing function zip as if it was written zip(elem1, elem2, ...)

Note:

AFAIK, this code is as lazy as it can be. Not tested.

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

Concatenate columns in Apache Spark DataFrame

Another way to do it in pySpark using sqlContext...

#Suppose we have a dataframe:
df = sqlContext.createDataFrame([('row1_1','row1_2')], ['colname1', 'colname2'])

# Now we can concatenate columns and assign the new column a name 
df = df.select(concat(df.colname1, df.colname2).alias('joined_colname'))

Error: free(): invalid next size (fast):

I encountered such a situation where code was circumventing STL's api and writing to the array unsafely when someone resizes it. Adding the assert here caught it:

void Logo::add(const QVector3D &v, const QVector3D &n)
{
 GLfloat *p = m_data.data() + m_count;
 *p++ = v.x();
 *p++ = v.y();
 *p++ = v.z();
 *p++ = n.x();
 *p++ = n.y();
 *p++ = n.z();
 m_count += 6;
 Q_ASSERT( m_count <= m_data.size() );
}

Get integer value from string in swift

above answer didnt help me as my string value was "700.00"

with Swift 2.2 this works for me

let myString = "700.00"
let myInt = (myString as NSString).integerValue

I passed myInt to NSFormatterClass

let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.maximumFractionDigits = 0

let priceValue = formatter.stringFromNumber(myInt!)!

//Now priceValue is ? 700

Thanks to this blog post.

Read HttpContent in WebApi controller

You can keep your CONTACT parameter with the following approach:

using (var stream = new MemoryStream())
{
    var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
    context.Request.InputStream.Seek(0, SeekOrigin.Begin);
    context.Request.InputStream.CopyTo(stream);
    string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}

Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.

Found as accepted answer here

How to tell if a string is not defined in a Bash shell script

I think the answer you are after is implied (if not stated) by Vinko's answer, though it is not spelled out simply. To distinguish whether VAR is set but empty or not set, you can use:

if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "$VAR" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi

You probably can combine the two tests on the second line into one with:

if [ -z "$VAR" -a "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi

However, if you read the documentation for Autoconf, you'll find that they do not recommend combining terms with '-a' and do recommend using separate simple tests combined with &&. I've not encountered a system where there is a problem; that doesn't mean they didn't used to exist (but they are probably extremely rare these days, even if they weren't as rare in the distant past).

You can find the details of these, and other related shell parameter expansions, the test or [ command and conditional expressions in the Bash manual.


I was recently asked by email about this answer with the question:

You use two tests, and I understand the second one well, but not the first one. More precisely I don't understand the need for variable expansion

if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi

Wouldn't this accomplish the same?

if [ -z "${VAR}" ]; then echo VAR is not set at all; fi

Fair question - the answer is 'No, your simpler alternative does not do the same thing'.

Suppose I write this before your test:

VAR=

Your test will say "VAR is not set at all", but mine will say (by implication because it echoes nothing) "VAR is set but its value might be empty". Try this script:

(
unset VAR
if [ -z "${VAR+xxx}" ]; then echo JL:1 VAR is not set at all; fi
if [ -z "${VAR}" ];     then echo MP:1 VAR is not set at all; fi
VAR=
if [ -z "${VAR+xxx}" ]; then echo JL:2 VAR is not set at all; fi
if [ -z "${VAR}" ];     then echo MP:2 VAR is not set at all; fi
)

The output is:

JL:1 VAR is not set at all
MP:1 VAR is not set at all
MP:2 VAR is not set at all

In the second pair of tests, the variable is set, but it is set to the empty value. This is the distinction that the ${VAR=value} and ${VAR:=value} notations make. Ditto for ${VAR-value} and ${VAR:-value}, and ${VAR+value} and ${VAR:+value}, and so on.


As Gili points out in his answer, if you run bash with the set -o nounset option, then the basic answer above fails with unbound variable. It is easily remedied:

if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "${VAR-}" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi

Or you could cancel the set -o nounset option with set +u (set -u being equivalent to set -o nounset).

How to get the selected date value while using Bootstrap Datepicker?

this works with me for inline datepicker (and the other)

$('#startdate').data('datepicker').date

Configuration with name 'default' not found. Android Studio

In my setting.gradle, I included a module that does not exist. Once I removed it, it started working. This could be another way to fix this issue

@POST in RESTful web service

Please find example below, it might help you

package jersey.rest.test;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class SimpleService {
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {
        String output = "Get:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/{param}")
    public Response postMsg(@PathParam("param") String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/post")
    //@Consumes(MediaType.TEXT_XML)
    public Response postStrMsg( String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @PUT
    @Path("/{param}")
    public Response putMsg(@PathParam("param") String msg) {
        String output = "PUT: Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @DELETE
    @Path("/{param}")
    public Response deleteMsg(@PathParam("param") String msg) {
        String output = "DELETE:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @HEAD
    @Path("/{param}")
    public Response headMsg(@PathParam("param") String msg) {
        String output = "HEAD:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }
}

for testing you can use any tool like RestClient (http://code.google.com/p/rest-client/)

Transpose a matrix in Python

If we wanted to return the same matrix we would write:

return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]

What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:

[[1,2,3],
[4,5,6],
[7,8,9]]

Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:

[[1,4,7],
[2,5,8],
[3,6,9]]

Therefore just switch the order in which we iterate:

return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]

How can I update a single row in a ListView?

I made up another solution, like RecyclyerView method void notifyItemChanged(int position), create CustomBaseAdapter class just like this:

public abstract class CustomBaseAdapter implements ListAdapter, SpinnerAdapter {
    private final CustomDataSetObservable mDataSetObservable = new CustomDataSetObservable();

    public boolean hasStableIds() {
        return false;
    }

    public void registerDataSetObserver(DataSetObserver observer) {
        mDataSetObservable.registerObserver(observer);
    }

    public void unregisterDataSetObserver(DataSetObserver observer) {
        mDataSetObservable.unregisterObserver(observer);
    }

    public void notifyDataSetChanged() {
        mDataSetObservable.notifyChanged();
    }

    public void notifyItemChanged(int position) {
        mDataSetObservable.notifyItemChanged(position);
    }

    public void notifyDataSetInvalidated() {
        mDataSetObservable.notifyInvalidated();
    }

    public boolean areAllItemsEnabled() {
        return true;
    }

    public boolean isEnabled(int position) {
        return true;
    }

    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getView(position, convertView, parent);
    }

    public int getItemViewType(int position) {
        return 0;
    }

    public int getViewTypeCount() {
        return 1;
    }

    public boolean isEmpty() {
        return getCount() == 0;
    } {

    }
}

Don't forget to create a CustomDataSetObservable class too for mDataSetObservable variable in CustomAdapterClass, like this:

public class CustomDataSetObservable extends Observable<DataSetObserver> {

    public void notifyChanged() {
        synchronized(mObservers) {
            // since onChanged() is implemented by the app, it could do anything, including
            // removing itself from {@link mObservers} - and that could cause problems if
            // an iterator is used on the ArrayList {@link mObservers}.
            // to avoid such problems, just march thru the list in the reverse order.
            for (int i = mObservers.size() - 1; i >= 0; i--) {
                mObservers.get(i).onChanged();
            }
        }
    }

    public void notifyInvalidated() {
        synchronized (mObservers) {
            for (int i = mObservers.size() - 1; i >= 0; i--) {
                mObservers.get(i).onInvalidated();
            }
        }
    }

    public void notifyItemChanged(int position) {
        synchronized(mObservers) {
            // since onChanged() is implemented by the app, it could do anything, including
            // removing itself from {@link mObservers} - and that could cause problems if
            // an iterator is used on the ArrayList {@link mObservers}.
            // to avoid such problems, just march thru the list in the reverse order.
            mObservers.get(position).onChanged();
        }
    }
}

on class CustomBaseAdapter there is a method notifyItemChanged(int position), and you can call that method when you want update a row wherever you want (from button click or anywhere you want call that method). And voila!, your single row will update instantly..

How to add option to select list in jQuery

$('#dropListBuilding').append('<option>'+val+'</option>');

DIV table colspan: how?

you can simply use two table divs, for instance:

_x000D_
_x000D_
<div style="display:table; width:450px; margin:0 auto; margin-top:30px; ">_x000D_
  <div style="display:table-row">_x000D_
    <div style="width:50%">element1</div>_x000D_
    <div style="width:50%">element2</div>_x000D_
  </div>_x000D_
</div>_x000D_
<div style="display:table; width:450px; margin:0 auto;">_x000D_
  <div style="display:table-row">_x000D_
    <div style="width:100%">element1</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

works great!

jQuery dialog popup

You can check this link: http://jqueryui.com/dialog/

This code should work fine

$("#dialog").dialog();

Inserting created_at data with Laravel

You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:

protected $fillable = ['name', 'created_at']; 

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

You can fix this issue by deleting browser cookie from the begining of time. I have tried this and it is working fine for me.

To delete only cookies:

  1. hold down ctrl+shift+delete
  2. remove all check boxes except for cookies of course
  3. use the drop down on top to select "from the beginning of time
  4. click clear browsing data

Eclipse CDT project built but "Launch Failed. Binary Not Found"

The video link below illustrate these steps in more detail:

  1. Create Empty project
  2. Choose linux Gcc compiler
  3. Right click on project choose " source folder "
  4. Name it " src "
  5. Right click on src folder choose " source file "
  6. Start coding
  7. Save project
  8. Build project
  9. Run project

https://www.youtube.com/watch?v=wtyBvagV-_A

How to take character input in java

You can simply use (char) System.in.read(); casting to char is necessary to convert int to char

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

For anyone struggling with similar cases

No index signature with a parameter of type 'string' was found on type X

trying to use it with simple objects (used as dicts) like:

DNATranscriber = {
   G:"C",
   C: "G",
   T: "A",
   A: "U"
}

and trying to dynamically access the value from a calculated key like:

const key = getFirstType(dnaChain);
const result = DNATranscriber[key];

and you faced the error as shown above, you can use the keyof operator and try something like

const key = getFirstType(dnaChain) as keyof typeof DNATranscriber;

certainly you will need a guard at the result but if it seems more intuitive than some custom types magic, it is ok.

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

Please make sure the output folder in Java Build Path tab set as like below,which would determine where the .class file are generated.Then clean the project.

enter image description here

How do I add FTP support to Eclipse?

Eclipse natively supports FTP and SSH. Aptana is not necessary.

Native FTP and SSH support in Eclipse is in the "Remote System Explorer End-User Runtime" Plugin.

Install it through Eclipse itself. These instructions may vary slightly with your version of Eclipse:

  1. Go to 'Help' -> 'Install New Software' (in older Eclipses, this is called something a bit different)
  2. In the 'Work with:' drop-down, select your version's plugin release site. Example: for Kepler, this is
    Kepler - http://download.eclipse.org/releases/kepler
  3. In the filter field, type 'remote'.
  4. Check the box next to 'Remote System Explorer End-User Runtime'
  5. Click 'Next', and accept the terms. It should now download and install.
  6. After install, Eclipse may want to restart.

Using it, in Eclipse:

  1. Window -> Open Perspective -> (perhaps select 'Other') -> Remote System Explorer
  2. File -> New -> Other -> Remote System Explorer (folder) -> Connection (or type Connection into the filter field)
  3. Choose FTP from the 'Select Remote System Type' panel.
  4. Fill in your FTP host info in the next panel (username and password come later).
  5. In the Remote Systems panel, right-click the hostname and click 'connect'.
  6. Enter username + password and you're good!
  7. Well, not exactly 'good'. The RSE system is fairly unusual, but you're connected.
  8. And you're one smart cookie! You'll figure out the rest.

Edit: To change the default port, follow the instructions on this page: http://ikool.wordpress.com/2008/07/25/tips-to-access-ftpssh-on-different-ports-using-eclipse-rse/

PHP get domain name

To answer your question, these should work as long as:

  • Your HTTP server passes these values along to PHP (I don't know any that don't)
  • You're not accessing the script via command line (CLI)

But, if I remember correctly, these values can be faked to an extent, so it's best not to rely on them.

My personal preference is to set the domain name as an environment variable in the apache2 virtual host:

# Virtual host
setEnv DOMAIN_NAME example.com

And read it in PHP:

// PHP
echo getenv(DOMAIN_NAME);

This, however, isn't applicable in all circumstances.

Post parameter is always null

I had the same issue of getting null as parameter, but it was related to large objects. It turned out the problem was related to IIS max length. It can be configured in web.config.

  <system.web>
    <httpRuntime targetFramework="4.7" maxRequestLength="1073741824" />
  </system.web>

I wonder why Web API suppressed the error and sends null objects to my APIs. I found the error using Microsoft.AspNet.WebApi.Tracing.

Clearing my form inputs after submission

You can try this:

function submitForm() {
  $('form[name="contact-form"]').submit();
  $('input[type="text"], textarea').val('');
}

This script needs jquery to be added on the page.

count number of characters in nvarchar column

You can find the number of characters using system function LEN. i.e.

SELECT LEN(Column) FROM TABLE

Setting environment variable in react-native?

The specific method used to set environment variables will vary by CI service, build approach, platform and tools you're using.

If you're using Buddybuild for CI to build an app and manage environment variables, and you need access to config from JS, create a env.js.example with keys (with empty string values) for check-in to source control, and use Buddybuild to produce an env.js file at build time in the post-clone step, hiding the file contents from the build logs, like so:

#!/usr/bin/env bash

ENVJS_FILE="$BUDDYBUILD_WORKSPACE/env.js"

# Echo what's happening to the build logs
echo Creating environment config file

# Create `env.js` file in project root
touch $ENVJS_FILE

# Write environment config to file, hiding from build logs
tee $ENVJS_FILE > /dev/null <<EOF
module.exports = {
  AUTH0_CLIENT_ID: '$AUTH0_CLIENT_ID',
  AUTH0_DOMAIN: '$AUTH0_DOMAIN'
}
EOF

Tip: Don't forget to add env.js to .gitignore so config and secrets aren't checked into source control accidentally during development.

You can then manage how the file gets written using the Buddybuild variables like BUDDYBUILD_VARIANTS, for instance, to gain greater control over how your config is produced at build time.

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

I just spent about 1 hour to figure out possible solution for the same error.

So what I did under MS WIndows 7 is following

  1. Uninstall all Java packages of all versions.

  2. Download last packages Java SE or JRE for your 32 or 64 Windows and install it.

  3. First install JRE and second is Java SE.

enter image description here

  1. Open text editor and paste this code.

    public class Hello {

      public static void main(String[] args) {
    
         System.out.println("test");
    
      }
    
    } 
    
  2. Save it like Hello.java

  3. Go to Console and compile it like

javac Hello.java

  1. Execute the code like

java Hello

enter image description here

Should be no error.

Hex transparency in colors

I always keep coming here to check for int/hex alpha value. So, end up creating a simple method in my java utils class. This method will convert the percentage to hex value and append to the color code string value.

 public static String setColorAlpha(int percentage, String colorCode){
    double decValue = ((double)percentage / 100) * 255;
    String rawHexColor = colorCode.replace("#","");
    StringBuilder str = new StringBuilder(rawHexColor);

    if(Integer.toHexString((int)decValue).length() == 1)
        str.insert(0, "#0" + Integer.toHexString((int)decValue));
    else
        str.insert(0, "#" + Integer.toHexString((int)decValue));
    return str.toString();
}

So, Utils.setColorAlpha(30, "#000000") will give you #4c000000

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

In case you are appending to the DOM, make sure the content is compatible:

modal.find ('div.modal-body').append (content) // check content

Limit characters displayed in span

max-length is used for input elements. Use text-overflow property of CSS.

.claimedRight {
    display:block; width: 250px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

Using PHP with Socket.io

Erm, why would you want to? Leave PHP on the backend and NodeJS/Sockets to do its non-blocking thing.

Here is something to get you started: http://groups.google.com/group/socket_io/browse_thread/thread/74a76896d2b72ccc

Personally I have express running with an endpoint that is listening expressly for interaction from PHP.

For example, if I have sent a user an email, I want socket.io to display a real-time notification to the user.

Want interaction from socket.io to php, well you can just do something like this:

var http = require('http'),
            host = WWW_HOST,
            clen = 'userid=' + userid,
            site = http.createClient(80, host),
            request = site.request("POST", "/modules/nodeim/includes/signonuser.inc.php",  
                {'host':host,'Content-Length':clen.length,'Content-Type':'application/x-www-form-urlencoded'});                     

request.write('userid=' + userid);      
request.end();  

Seriously, PHP is great for doing server side stuff and let it be with the connections it has no place in this domain now. Why do anything long-polling when you have websockets or flashsockets.

How to fix "containing working copy admin area is missing" in SVN?

For me, the same issue happened when I both:

  • deleted (--force) a .map file
  • added *.map to svn:ignore via svn propedit svn:ignore .

My solution was to:

  1. undo changes to the property
  2. commit changes to the files
  3. checkout a fresh copy of the repository (alas!)
  4. change the property and commit

How do I import material design library to Android Studio?

build.gradle

implementation 'com.google.android.material:material:1.2.0-alpha02'

styles.xml

 <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

Android JSONObject - How can I loop through a flat JSON object to get each key and value

You shold use the keys() or names() method. keys() will give you an iterator containing all the String property names in the object while names() will give you an array of all key String names.

You can get the JSONObject documentation here

http://developer.android.com/reference/org/json/JSONObject.html

how to customise input field width in bootstrap 3

i solved with a max-width in my main css-file.

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

It's a simple solution with little "code"

How can I print a quotation mark in C?

Without a backslash, special characters have a natural special meaning. With a backslash they print as they appear.

\   -   escape the next character
"   -   start or end of string
’   -   start or end a character constant
%   -   start a format specification
\\  -   print a backslash
\"  -   print a double quote
\’  -   print a single quote
%%  -   print a percent sign

The statement

printf("  \"  "); 

will print you the quotes. You can also print these special characters \a, \b, \f, \n, \r, \t and \v with a (slash) preceeding it.

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

You are not getting value of $id=$_GET['id'];

And you are using it (before it gets initialised).

Use php's in built isset() function to check whether the variable is defied or not.

So, please update the line to:

$id = isset($_GET['id']) ? $_GET['id'] : '';

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

ReactJS SyntheticEvent stopPropagation() only works with React events?

I was able to resolve this by adding the following to my component:

componentDidMount() {
  ReactDOM.findDOMNode(this).addEventListener('click', (event) => {
    event.stopPropagation();
  }, false);
}

How to make Scrollable Table with fixed headers using CSS

What you want to do is separate the content of the table from the header of the table. You want only the <th> elements to be scrolled. You can easily define this separation in HTML with the <tbody> and the <thead> elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block. This way <thead> and <tbody> are separated.

table tbody, table thead
{
    display: block;
}

Now you can set the scroll to the body of the table:

table tbody 
{
   overflow: auto;
   height: 100px;
}

And last, because the <thead> doesn't share the same width as the body anymore, you should set a static width to the header of the table:

th
{
    width: 72px;
}

You should also set a static width for <td>. This solves the issue of the unaligned columns.

td
{
    width: 72px;
}


Note that you are also missing some HTML elements. Every row should be in a <tr> element, that includes the header row:

<tr>
     <th>head1</th>
     <th>head2</th>
     <th>head3</th>
     <th>head4</th>
</tr>

I hope this is what you meant.

jsFiddle

Addendum

If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:

    table th:nth-child(1), td:nth-child(1) { min-width: 50px;  max-width: 50px; }
    table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
    table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
    table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }

Can I create links with 'target="_blank"' in Markdown?

You can do this via native javascript code like so:

 
var pattern = /a href=/g;
var sanitizedMarkDownText = rawMarkDownText.replace(pattern,"a target='_blank' href=");

JSFiddle Code

Error Message: Type or namespace definition, or end-of-file expected

You have extra brackets in Hours property;

public  object Hours { get; set; }}

How do I load a PHP file into a variable?

If your file has a return statement like this:

<?php return array(
  'AF' => 'Afeganistão',
  'ZA' => 'África do Sul',
  ...
  'ZW' => 'Zimbabué'
);

You can get this to a variable like this:

$data = include $filePath;

Send Email Intent

The following code works for me fine.

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"abc@gmailcom"});
Intent mailer = Intent.createChooser(intent, null);
startActivity(mailer);

Capturing URL parameters in request.GET

If you only have access to the view object, then you can get the parameters defined in the URL path this way:

view.kwargs.get('url_param')

If you only have access to the request object, use the following:

request.resolver_match.kwargs.get('url_param')

Tested on Django 3.

How to work with string fields in a C struct?

This does not work:

string s = (string)malloc(sizeof string); 

string refers to a pointer, you need the size of the structure itself:

string s = malloc(sizeof (*string)); 

Note the lack of cast as well (conversion from void* (malloc's return type) is implicitly performed).

Also, in your main, you have a globally delcared patient, but that is uninitialized. Try:

 patient.number = 3;     
 patient.name = "John";     
 patient.address = "Baker street";     
 patient.birthdate = "4/15/2012";     
 patient.gender = 'M';     

before you read-access any of its members

Also, strcpy is inherently unsafe as it does not have boundary checking (will copy until the first '\0' is encountered, writing past allocated memory if the source is too long). Use strncpy instead, where you can at least specify the maximum number of characters copied -- read the documentation to ensure you pass the correct value, it is easy to make an off-by-one error.

How do I print bold text in Python?

class color:
   PURPLE = '\033[95m'
   CYAN = '\033[96m'
   DARKCYAN = '\033[36m'
   BLUE = '\033[94m'
   GREEN = '\033[92m'
   YELLOW = '\033[93m'
   RED = '\033[91m'
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'
   END = '\033[0m'

print(color.BOLD + 'Hello World !' + color.END)

Show data on mouseover of circle

This concise example demonstrates common way how to create custom tooltip in d3.

_x000D_
_x000D_
var w = 500;_x000D_
var h = 150;_x000D_
_x000D_
var dataset = [5, 10, 15, 20, 25];_x000D_
_x000D_
// firstly we create div element that we can use as_x000D_
// tooltip container, it have absolute position and_x000D_
// visibility: hidden by default_x000D_
_x000D_
var tooltip = d3.select("body")_x000D_
  .append("div")_x000D_
  .attr('class', 'tooltip');_x000D_
_x000D_
var svg = d3.select("body")_x000D_
  .append("svg")_x000D_
  .attr("width", w)_x000D_
  .attr("height", h);_x000D_
_x000D_
// here we add some circles on the page_x000D_
_x000D_
var circles = svg.selectAll("circle")_x000D_
  .data(dataset)_x000D_
  .enter()_x000D_
  .append("circle");_x000D_
_x000D_
circles.attr("cx", function(d, i) {_x000D_
    return (i * 50) + 25;_x000D_
  })_x000D_
  .attr("cy", h / 2)_x000D_
  .attr("r", function(d) {_x000D_
    return d;_x000D_
  })_x000D_
  _x000D_
  // we define "mouseover" handler, here we change tooltip_x000D_
  // visibility to "visible" and add appropriate test_x000D_
  _x000D_
  .on("mouseover", function(d) {_x000D_
    return tooltip.style("visibility", "visible").text('radius = ' + d);_x000D_
  })_x000D_
  _x000D_
  // we move tooltip during of "mousemove"_x000D_
  _x000D_
  .on("mousemove", function() {_x000D_
    return tooltip.style("top", (event.pageY - 30) + "px")_x000D_
      .style("left", event.pageX + "px");_x000D_
  })_x000D_
  _x000D_
  // we hide our tooltip on "mouseout"_x000D_
  _x000D_
  .on("mouseout", function() {_x000D_
    return tooltip.style("visibility", "hidden");_x000D_
  });
_x000D_
.tooltip {_x000D_
    position: absolute;_x000D_
    z-index: 10;_x000D_
    visibility: hidden;_x000D_
    background-color: lightblue;_x000D_
    text-align: center;_x000D_
    padding: 4px;_x000D_
    border-radius: 4px;_x000D_
    font-weight: bold;_x000D_
    color: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Unix command-line JSON parser?

I prefer python -m json.tool which seems to be available per default on most *nix operating systems per default.

$ echo '{"foo":1, "bar":2}' | python -m json.tool
{
    "bar": 2, 
    "foo": 1
}

Note: Depending on your version of python, all keys might get sorted alphabetically, which can or can not be a good thing. With python 2 it was the default to sort the keys, while in python 3.5+ they are no longer sorted automatically, but you have the option to sort by key explicitly:

$ echo '{"foo":1, "bar":2}' | python3 -m json.tool --sort-keys
{
    "bar": 2, 
    "foo": 1
}

How do you revert to a specific tag in Git?

Use git reset:

git reset --hard "Version 1.0 Revision 1.5"

(assuming that the specified string is the tag).

CSS I want a div to be on top of everything

For z-index:1000 to have an effect you need a non-static positioning scheme.

Add position:relative; to a rule selecting the element you want to be on top

Datanode process not running in Hadoop

You need to do something like this:

  • bin/stop-all.sh (or stop-dfs.sh and stop-yarn.sh in the 2.x serie)
  • rm -Rf /app/tmp/hadoop-your-username/*
  • bin/hadoop namenode -format (or hdfs in the 2.x serie)

the solution was taken from: http://pages.cs.brandeis.edu/~cs147a/lab/hadoop-troubleshooting/. Basically it consists in restarting from scratch, so make sure you won't loose data by formating the hdfs.

How to unpublish an app in Google Play Developer Console

Click on Store Listing and then click on 'Unpublish App'.

See image for details

java.lang.ClassNotFoundException: HttpServletRequest

I have just deleted the declaration of the servlet in the web.xml file and it works for me.

Good luck

re.sub erroring with "Expected string or bytes-like object"

The simplest solution is to apply Python str function to the column you are trying to loop through.

If you are using pandas, this can be implemented as:

dataframe['column_name']=dataframe['column_name'].apply(str)

CakePHP 3.0 installation: intl extension missing from system

Short answer: activate intl extension in php_cli.ini. Thanks to @ndm for his input.

How to remove leading zeros from alphanumeric text?

You could just do: String s = Integer.valueOf("0001007").toString();

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

Split into train test and valid

x =np.expand_dims(np.arange(100), -1)


print(x)

indices = np.random.permutation(x.shape[0])

training_idx, test_idx, val_idx = indices[:int(x.shape[0]*.9)], indices[int(x.shape[0]*.9):int(x.shape[0]*.95)],  indices[int(x.shape[0]*.9):int(x.shape[0]*.95)]


training, test, val = x[training_idx,:], x[test_idx,:], x[val_idx,:]

print(training, test, val)

Char array in a struct - incompatible assignment?

use strncpy to make sure you have no buffer overflow.

char name[]= "whatever_you_want";
strncpy( sara.first, name, sizeof(sara.first)-1 );
sara.first[sizeof(sara.first)-1] = 0;

Pass user defined environment variable to tomcat

For Unix & Mac systems, Go to /bin/setenv.sh inside tomcat folder

Add the below line

export JAVA_OPTS="$JAVA_OPTS -DAPP_MASTER_PASSWORD=mypass"

Now System.getProperty("APP_MASTER_PASSWORD") will return "mypass"

How to PUT a json object with an array using curl

It should be mentioned that the Accept header tells the server something about what we are accepting back, whereas the relevant header in this context is Content-Type

It's often advisable to specify Content-Type as application/json when sending JSON. For curl the syntax is:

-H 'Content-Type: application/json'

So the complete curl command will be:

curl -H 'Content-Type: application/json' -H 'Accept: application/json' -X PUT -d '{"tags":["tag1","tag2"],"question":"Which band?","answers":[{"id":"a0","answer":"Answer1"},{"id":"a1","answer":"answer2"}]}' http://example.com/service`

PHPMailer: SMTP Error: Could not connect to SMTP host

In my case in CPANEL i have 'Register mail ids' option where i add my email address and after 30 minutes it works fine with simple php mail function.

Should I use past or present tense in git commit messages?

The preference for present-tense, imperative-style commit messages comes from Git itself. From Documentation/SubmittingPatches in the Git repo:

Describe your changes in imperative mood, e.g. "make xyzzy do frotz" instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy to do frotz", as if you are giving orders to the codebase to change its behavior.

So you'll see a lot of Git commit messages written in that style. If you're working on a team or on open source software, it is helpful if everyone sticks to that style for consistency. Even if you're working on a private project, and you're the only one who will ever see your git history, it's helpful to use the imperative mood because it establishes good habits that will be appreciated when you're working with others.

Font awesome is not showing icon

It's something to do with v5, some of the icons don't work with older versions.

This link worked for me!

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">

Insert all values of a table into another table in SQL

Try this:

INSERT INTO newTable SELECT * FROM initial_Table

notifyDataSetChanged not working on RecyclerView

Although it is a bit strange, but the notifyDataSetChanged does not really work without setting new values to adapter. So, you should do:

array = getNewItems();                    
((MyAdapter) mAdapter).setValues(array);  // pass the new list to adapter !!!
mAdapter.notifyDataSetChanged();       

This has worked for me.

jQuery select2 get value of select tag?

Try this :

$('#input_id :selected').val(); //for getting value from selected option
$('#input_id :selected').text(); //for getting text from selected option

HTML / CSS table with GRIDLINES

For internal gridlines, use the tag: td For external gridlines, use the tag: table

AngularJS - Attribute directive input value change

There's a great example in the AngularJS docs.

It's very well commented and should get you pointed in the right direction.

A simple example, maybe more so what you're looking for is below:

jsfiddle


HTML

<div ng-app="myDirective" ng-controller="x">
    <input type="text" ng-model="test" my-directive>
</div>

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngModel, function (v) {
                console.log('value changed, new value is: ' + v);
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}


Edit: Same thing, doesn't require ngModel jsfiddle:

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        scope: {
            myDirective: '='
        },
        link: function (scope, element, attrs) {
            // set the initial value of the textbox
            element.val(scope.myDirective);
            element.data('old-value', scope.myDirective);

            // detect outside changes and update our input
            scope.$watch('myDirective', function (val) {
                element.val(scope.myDirective);
            });

            // on blur, update the value in scope
            element.bind('propertychange keyup paste', function (blurEvent) {
                if (element.data('old-value') != element.val()) {
                    console.log('value changed, new value is: ' + element.val());
                    scope.$apply(function () {
                        scope.myDirective = element.val();
                        element.data('old-value', element.val());
                    });
                }
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

Split data frame string column into multiple columns

This question is pretty old but I'll add the solution I found the be the simplest at present.

library(reshape2)
before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
newColNames <- c("type1", "type2")
newCols <- colsplit(before$type, "_and_", newColNames)
after <- cbind(before, newCols)
after$type <- NULL
after

When to use "ON UPDATE CASCADE"

It's true that if your primary key is just a identity value auto incremented, you would have no real use for ON UPDATE CASCADE.

However, let's say that your primary key is a 10 digit UPC bar code and because of expansion, you need to change it to a 13-digit UPC bar code. In that case, ON UPDATE CASCADE would allow you to change the primary key value and any tables that have foreign key references to the value will be changed accordingly.

In reference to #4, if you change the child ID to something that doesn't exist in the parent table (and you have referential integrity), you should get a foreign key error.

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

Try indextank.

As the case of elastic search, it was conceived to be much easier to use than lucene/solr. It also includes very flexible scoring system that can be tweaked without reindexing.

How to write UPDATE SQL with Table alias in SQL Server 2008?

The syntax for using an alias in an update statement on SQL Server is as follows:

UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;

The alias should not be necessary here though.

Using Java to pull data from a webpage?

The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.

For example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class DownloadPage {

    public static void main(String[] args) throws IOException {

        // Make a URL to the web page
        URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

        // Get the input stream through URL Connection
        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();

        // Once you have the Input Stream, it's just plain old Java IO stuff.

        // For this case, since you are interested in getting plain-text web page
        // I'll use a reader and output the text content to System.out.

        // For binary content, it's better to directly read the bytes from stream and write
        // to the target file.


        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Hope this helps.

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

This is not a solution but I hope it helps: This comes close except that when the KEY = %userprofile%\desktop the copy fails even though zdesktop=%userprofile%\desktop. I think because the embedded %userprofile% is not getting translated.

REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop>z.out
for /f "tokens=3 skip=4" %%t in (z.out) do set zdesktop=%%t
copy myicon %zdesktop%
set zdesktop=
del z.out

So it sucessfully parses out the REG key but if the key contains an embedded %var% it doesn't get translated during the copy command.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

Difference between static STATIC_URL and STATIC_ROOT on Django

All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static and I used the same STATIC_URL in my dev settings.py file.

This causes a silent failure in django/conf/urls/static.py.

The test elif not settings.DEBUG or '://' in prefix: picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.

It would be thoughtful if Django spit out an error message stating you can't use a http(s):// with DEBUG = True

I had to change STATIC_URL to be '/static/'

Listing contents of a bucket with boto3

ObjectSummary:

There are two identifiers that are attached to the ObjectSummary:

  • bucket_name
  • key

boto3 S3: ObjectSummary

More on Object Keys from AWS S3 Documentation:

Object Keys:

When you create an object, you specify the key name, which uniquely identifies the object in the bucket. For example, in the Amazon S3 console (see AWS Management Console), when you highlight a bucket, a list of objects in your bucket appears. These names are the object keys. The name for a key is a sequence of Unicode characters whose UTF-8 encoding is at most 1024 bytes long.

The Amazon S3 data model is a flat structure: you create a bucket, and the bucket stores objects. There is no hierarchy of subbuckets or subfolders; however, you can infer logical hierarchy using key name prefixes and delimiters as the Amazon S3 console does. The Amazon S3 console supports a concept of folders. Suppose that your bucket (admin-created) has four objects with the following object keys:

Development/Projects1.xls

Finance/statement1.pdf

Private/taxdocument.pdf

s3-dg.pdf

Reference:

AWS S3: Object Keys

Here is some example code that demonstrates how to get the bucket name and the object key.

Example:

import boto3
from pprint import pprint

def main():

    def enumerate_s3():
        s3 = boto3.resource('s3')
        for bucket in s3.buckets.all():
             print("Name: {}".format(bucket.name))
             print("Creation Date: {}".format(bucket.creation_date))
             for object in bucket.objects.all():
                 print("Object: {}".format(object))
                 print("Object bucket_name: {}".format(object.bucket_name))
                 print("Object key: {}".format(object.key))

    enumerate_s3()


if __name__ == '__main__':
    main()

Eclipse C++: Symbol 'std' could not be resolved

Try restart Eclipse first, in my case I change different Compiler setting of the project then it shows this message, after restart it works.

Deep cloning objects

Here a solution fast and easy that worked for me without relaying on Serialization/Deserialization.

public class MyClass
{
    public virtual MyClass DeepClone()
    {
        var returnObj = (MyClass)MemberwiseClone();
        var type = returnObj.GetType();
        var fieldInfoArray = type.GetRuntimeFields().ToArray();

        foreach (var fieldInfo in fieldInfoArray)
        {
            object sourceFieldValue = fieldInfo.GetValue(this);
            if (!(sourceFieldValue is MyClass))
            {
                continue;
            }

            var sourceObj = (MyClass)sourceFieldValue;
            var clonedObj = sourceObj.DeepClone();
            fieldInfo.SetValue(returnObj, clonedObj);
        }
        return returnObj;
    }
}

EDIT: requires

    using System.Linq;
    using System.Reflection;

That's How I used it

public MyClass Clone(MyClass theObjectIneededToClone)
{
    MyClass clonedObj = theObjectIneededToClone.DeepClone();
}

How to customize a Spinner in Android

The most elegant and flexible solution I have found so far is here: http://android-er.blogspot.sg/2010/12/custom-arrayadapter-for-spinner-with.html

Basically, follow these steps:

  1. Create custom layout xml file for your dropdown item, let's say I will call it spinner_item.xml
  2. Create custom view class, for your dropdown Adapter. In this custom class, you need to overwrite and set your custom dropdown item layout in getView() and getDropdownView() method. My code is as below:

    public class CustomArrayAdapter extends ArrayAdapter<String>{
    
    private List<String> objects;
    private Context context;
    
    public CustomArrayAdapter(Context context, int resourceId,
         List<String> objects) {
         super(context, resourceId, objects);
         this.objects = objects;
         this.context = context;
    }
    
    @Override
    public View getDropDownView(int position, View convertView,
        ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      return getCustomView(position, convertView, parent);
    }
    
    public View getCustomView(int position, View convertView, ViewGroup parent) {
    
    LayoutInflater inflater=(LayoutInflater) context.getSystemService(  Context.LAYOUT_INFLATER_SERVICE );
    View row=inflater.inflate(R.layout.spinner_item, parent, false);
    TextView label=(TextView)row.findViewById(R.id.spItem);
     label.setText(objects.get(position));
    
    if (position == 0) {//Special style for dropdown header
          label.setTextColor(context.getResources().getColor(R.color.text_hint_color));
    }
    
    return row;
    }
    
    }
    
  3. In your activity or fragment, make use of the custom adapter for your spinner view. Something like this:

    Spinner sp = (Spinner)findViewById(R.id.spMySpinner);
    ArrayAdapter<String> myAdapter = new CustomArrayAdapter(this, R.layout.spinner_item, options);
    sp.setAdapter(myAdapter);
    

where options is the list of dropdown item string.

WPF Image Dynamically changing Image source during runtime

Here is how it worked beautifully for me. In the window resources add the image.

   <Image x:Key="delImg" >
    <Image.Source>
     <BitmapImage UriSource="Images/delitem.gif"></BitmapImage>
    </Image.Source>
   </Image>

Then the code goes like this.

Image img = new Image()

img.Source = ((Image)this.Resources["delImg"]).Source;

"this" is referring to the Window object

Javascript to display the current date and time

Updated to use the more modern Luxon instead of MomentJS.

Don't reinvent the wheel. Use a tried and tested library do this for you, Luxon for example: https://moment.github.io/luxon/index.html

From their site:

https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-toLocaleString

//=> 'Thu, Apr 20, 11:27 AM'
DateTime.local().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });

How do I combine 2 select statements into one?

use a case into the select and use in the where close a OR

something like this, I didn't tested it but it should work, I think...

select case when CCC='D' then 'test1' else 'test2' end, *
from table
where (CCC='D' AND DDD='X') or (CCC<>'D' AND DDD='X')

Default background color of SVG root element

Found this works in Safari. SVG only colors in with background-color where an element's bounding box covers. So, give it a border (stroke) with a zero pixel boundary. It fills in the whole thing for you with your background-color.

<svg style='stroke-width: 0px; background-color: blue;'> </svg>

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

How do you run JavaScript script through the Terminal?

This is a "roundabout" solution but you could use ipython

Start ipython notebook from terminal:

$ ipython notebook

It will open in a browser where you can run the javascript

enter image description here

Inserting a value into all possible locations in a list

Coming from JavaScript, this was something I was used to having "built-in" via Array.prototype.splice(), so I made a Python function that does the same:

def list_splice(target, start, delete_count=None, *items):
    """Remove existing elements and/or add new elements to a list.

    target        the target list (will be changed)
    start         index of starting position
    delete_count  number of items to remove (default: len(target) - start)
    *items        items to insert at start index

    Returns a new list of removed items (or an empty list)
    """
    if delete_count == None:
        delete_count = len(target) - start

    # store removed range in a separate list and replace with *items
    total = start + delete_count
    removed = target[start:total]
    target[start:total] = items

    return removed

How do I setup the InternetExplorerDriver so it works

Basically you need to download the IEDriverServer.exe from Selenium HQ website without executing anything just remmeber the location where you want it and then put the code on Eclipse like this

System.setProperty("webdriver.ie.driver", "C:\\Users\\juan.torres\\Desktop\\QA stuff\\IEDriverServer_Win32_2.32.3\\IEDriverServer.exe");
WebDriver driver= new InternetExplorerDriver();

driver.navigate().to("http://www.youtube.com/");

for the path use double slash //

ok have fun !!